<?php

namespace App\Http\Controllers\Workplace;

use App\Http\Controllers\Controller;
use App\Models\TaskEntry;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class TaskEntriesController extends Controller
{
    function __construct()
    {
        $this->middleware('permission:responsible-team-list', ['only' => ['index']]);
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {

    }
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $assign_to = User::select('id','name','email','prepared_by')->get();

        return view('task-entries.create',compact('assign_to'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validator = \Validator::make($request->all(), [
            // 'assigned_to_id' => 'required|unique:responsible_teams,assigned_to_id,NULL,id,deleted_at,NULL',
            'assigned_to_id' => 'required',
            'assigned_date'  => 'required',
        ]);

        if ($validator->fails()) {
            if ($request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => $validator->getMessageBag()->first(),
                    'data'    => []
                ]);
            }

            return redirect()->back()->with('error', $validator->getMessageBag()->first());
        }

        $currentUser = Auth::user();

        $data = $request->except([
            '_token',
            'assigned_date',
            'expected_completion_date',
            'actual_completion_date'
        ]);

        $data['assigned_date'] = $request->assigned_date != '' && $request->assigned_date != '0000-00-00' &&  $request->assigned_date != Null ? date('Y-m-d', strtotime($request->assigned_date)) : null;
        $data['expected_completion_date'] = $request->expected_completion_date != '' && $request->expected_completion_date != '0000-00-00' &&  $request->expected_completion_date != Null ? date('Y-m-d', strtotime($request->expected_completion_date)) : null;
        $data['actual_completion_date'] = $request->actual_completion_date != '' && $request->actual_completion_date != '0000-00-00' &&  $request->actual_completion_date != Null ? date('Y-m-d', strtotime($request->actual_completion_date)) : null;

        $data['assigned_by_id'] = $currentUser->id;
        $main_exists = TaskEntry::where('task_id', $request->task_id)->exists();

        if (!$main_exists) {
            $data['is_main'] = 1;
        }

        $data = TaskEntry::create($data);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Project Team created successfully',
                'data' => $data
            ]);
        }

        return redirect()->route('project-teams.index')
            ->with('success', 'Project Team created successfully');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $data       = TaskEntry::find($id);
        $assign_to    = User::select('id','name','email','prepared_by')->get();

        return view('task-entries.edit',compact('assign_to','data'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $validator = \Validator::make($request->all(), [

        ]);

        if ($validator->fails()) {
            if ($request->ajax()) {
                return response()->json([
                    'success' => false,
                    'message' => $validator->getMessageBag()->first(),
                    'data'    => []
                ]);
            }

            return redirect()->back()->with('error', $validator->getMessageBag()->first());
        }

        $data = $request->except([
            '_token',
            '_method',
            'assigned_date',
            'expected_completion_date',
            'actual_completion_date'
        ]);

        $data['assigned_date'] = $request->assigned_date != '' && $request->assigned_date != '0000-00-00' &&  $request->assigned_date != Null ? date('Y-m-d', strtotime($request->assigned_date)) : null;
        $data['expected_completion_date'] = $request->expected_completion_date != '' && $request->expected_completion_date != '0000-00-00' &&  $request->expected_completion_date != Null ? date('Y-m-d', strtotime($request->expected_completion_date)) : null;
        $data['actual_completion_date'] = $request->actual_completion_date != '' && $request->actual_completion_date != '0000-00-00' &&  $request->actual_completion_date != Null ? date('Y-m-d', strtotime($request->actual_completion_date)) : null;


        $data = TaskEntry::whereId($id)->update($data);
        $data = TaskEntry::find($id);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Task Entry updated successfully',
                'data' => $data
            ]);
        }
        return redirect()->route('task-entry.index')
            ->with('success', 'Task Entry updated successfully');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request)
    {
        $data = TaskEntry::find($request->id);

        TaskEntry::find($request->id)->delete();

        $Redirect = 'task-entry';

        return response()->json([
            'success' => true,
            'message' => ['Task EntryDeleted successfully'],
            'data' => [
                'redirect' => $Redirect,
            ]
        ]);
    }


    public function changeStatus(Request $request)
    {
        if ($request->ajax()) {
            $data   = array('status' => $request->status);
            $Update = TaskEntry::where('id', '=', $request->id)->update($data);

            if ($Update) {
                return response()->json([
                    'success' => true,
                    'message' => ['Task Entry status successfully change'],
                    'data' => [
                        'redirect' => '/tags/',
                        'reload' => true,
                    ]
                ]);
            } else {
                return response()->json([
                    'success' => false,
                    'message' => ['Error for change status'],
                    'data' => [
                        'redirect' => '',
                    ]
                ]);
            }
        }
    }
    public function teamApproval(Request $request)
    {
        if ($request->ajax()) {
            $data   = array('task_accepted_status' => $request->task_status_id);

            if (!empty($request->reason)) {
                $data['reject_reason'] = $request->reason;
            }

            $Update = TaskEntry::where('id', '=', $request->team_id)->update($data);

            if ($Update) {
                return response()->json([
                    'success' => true,
                    'message' => ['Task Entry status successfully change'],
                    'data' => [
                        'redirect' => '/tags/',
                        'reload' => true,
                    ]
                ]);
            } else {
                return response()->json([
                    'success' => false,
                    'message' => ['Error for change status'],
                    'data' => [
                        'redirect' => '',
                    ]
                ]);
            }
        }
    }
}
