<?php

namespace App\Http\Controllers\Workplace;

use App\Http\Controllers\Controller;
use App\Models\Task;
use App\Models\TaskStatus;
use Illuminate\Http\Request;
use App\Models\VoucherType;

class TaskStatusController extends Controller
{
    function __construct()
    {
        // $this->middleware('permission:task-status-list', ['only' => ['index']]);
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
       
        $data = TaskStatus::select([
            'id',
            'name',
            'code',
            'priority',
            'bg_color',
            'color',
            'status',
            'is_default',
            'voucher_code'
        ]);

        if ($request->ajax()) {
            $sort_by      = $request->get('sortby') ?? 10;
            $sort_type    = $request->get('sorttype');
            $search_query = $request->get('query');

            $data = $data->when(!empty($search_query), function ($query) use ($search_query) {
                return $query->where('name', 'like', '%'.$search_query.'%');
            })
            ->orderBy('id','ASC')
            ->paginate($sort_by);

             $data = TaskStatus::find($id);

            if (!$data) {
                return response()->json([
                    'success' => true,
                    'message' => 'Voucher Master not found.',
                ]);
            }
            return view('task-status.table', compact('data'));
        } else {
            $data = $data->groupBy('id')
                ->orderBy('id','ASC')
                ->paginate(10);

            return view('task-status.index',compact('data'));
        }

    }
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $priority = TaskStatus::max('priority');
        $priority = $priority != '' ? $priority : 0;

        $voucher_types = VoucherType::where('status' , '=' ,  '1')
        ->select('code')
        ->get();

        return view('task-status.create', compact('priority' , 'voucher_types'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        // dd($request->all());
        $validator = \Validator::make($request->all(), [
            'name' => 'required|unique:task_statuses,name,NULL,id,deleted_at,NULL',
            'voucher_code'=> '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());
        }

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

        $default_check = TaskStatus::where(['is_default' => 1,'status' => 1])->first();

        if (!$default_check) {
            $data['is_default'] = 1;
        }

        $quality = TaskStatus::create($data);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Task Status created successfully',
                'data' => $quality
            ]);
        }
        return redirect()->route('task-status.index')
            ->with('success', 'Task Status 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)
    {
        $taskStatus = TaskStatus::find($id);

        $voucher_types = VoucherType::where('status' , '=' ,  '1')
        ->select('code')
        ->get();

        return view('task-status.edit', compact('taskStatus', 'voucher_types'));
    }

    /**
     * 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(), [
            'name'       => 'required|unique:task_statuses,name,'.$id.',id,deleted_at,NULL',
            'voucher_code'=> 'required', 
        ]);

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

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

        

        $shift = TaskStatus::find($id);

        if (!$shift) {
            return redirect()->route('task-status.index')
                ->with('error', 'Task Status not found!');
        }

        $shift->update($data);

        return redirect()->route('task-status.index')
            ->with('success', 'Task Status updated successfully');
    }

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

        if ($about->is_default == '1') {
            return response()->json([
                'success' => false,
                'message' => ['Default record can not be deleted.']
            ]);
        }

        $about->delete();

        $Redirect = 'task-status';

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

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

            if ($Update) {
                return response()->json([
                    'success' => true,
                    'message' => ['TaskStatus status successfully change'],
                    'data' => [
                        'redirect' => '/users/',
                        'reload' => true,
                    ]
                ]);
            } else {
                return response()->json([
                    'success' => false,
                    'message' => ['Error for change status'],
                    'data' => [
                        'redirect' => '',
                    ]
                ]);
            }
        }
    }
    public function changedefault(Request $request)
    {
        if ($request->ajax()) {
            $data   = array('is_default' => $request->status );
            $count  = TaskStatus::where(['is_default' => $request->status])->count();

            if ($count > 0 && $request->status == 1) {
                return response()->json([
                    'success' => false,
                    'message' => ['There is already a default Task!'],
                    'data'    => []
                ]);
            }

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

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