<?php

namespace App\Http\Controllers\TestManager;

use App\Http\Controllers\Controller;
use App\Models\SpecialCase;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Validator;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class SpecialCasesController extends Controller
{
    function __construct()
    {
        $this->middleware('permission:special-case-list', ['only' => ['index']]);
    }

    public function index(Request $request)
    {
        $data = SpecialCase::select([
                    'special_cases.id',
                    'special_cases.name',
                    'special_cases.code',
                    'special_cases.priority',
                    'special_cases.is_default',
                    'special_cases.status',
                ])
                ->orderBy('priority', 'ASC');

        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('special_cases.name', 'like', '%'.$search_query.'%')
                    ->orWhere('special_cases.code', 'like', '%'.$search_query.'%')
                    ->orWhere('special_cases.priority', 'like', '%'.$search_query.'%');
            })
            ->orderBy('priority', 'ASC')
            ->paginate($sort_by);

            return view('special-cases.table', compact('data'));
        }
        else
        {
            $data = $data->paginate(10);

            return view('special-cases.index', compact('data'));
        }
    }

    public function create()
    {
        $priority = SpecialCase::max('priority');
        $priority = $priority != '' ? $priority : 0;

        return view('special-cases.create',compact('priority'));
    }

    public function store(Request $request)
    {
        $validator = \Validator::make($request->all(), [
            'name' => 'required|unique:special_cases,name,NULL,id,deleted_at,NULL',
        ]);

        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 = SpecialCase::where(['is_default' => 1,'status' => 1])->first();

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

        $data['code'] = strtoupper(str_replace(' ', '_', $request->name));

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

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

    public function edit($id)
    {
        $data = SpecialCase::find($id);

        return view('special-cases.edit', compact('data'));
    }

    public function update(Request $request, $id)
    {
        $validator = \Validator::make($request->all(), [
            'name' => 'required|unique:special_cases,name,'.$id.',id,deleted_at,NULL',
        ]);

        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'
        ]);

        $SpecialCase = SpecialCase::find($id);

        if (!$SpecialCase) {
            return redirect()->route('special-cases.index')
                ->with('error','Special case not found!');
        }

        $SpecialCase->update($data);

        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Special case Updated successfully',
                'data'    => $SpecialCase
            ]);
        }
    }

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

            $Redirect = 'special-cases';

            if($Update){
                return response()->json([
                    'success' => true,
                    'message' => ['Special case status successfully change'],
                    'data'    => [
                        'redirect' => $Redirect,
                    ]
                ]);
            } else {
                return response()->json([
                    'success' => false,
                    'message' => ['Error for change status'],
                    'data'    => [
                        'redirect' => '',
                    ]
                ]);
            }
        }
    }

    public function isDefault(Request $request)
    {
        if ($request->ajax()) {
            $data   = array('is_default' => $request->status );
            $count  = SpecialCase::where(['is_default' => $request->status])->count();

            if ($count > 0 && $request->status == 1) {
                return response()->json([
                    'success' => false,
                    'message' => ['There is already a default speecial case!'],
                    'data'    => []
                ]);
            } else {
                $Update = SpecialCase::where('id', '=', $request->id)->update($data);

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

    public function destroy(Request $request)
    {
        SpecialCase::find($request->id)->delete();

        $Redirect = 'special-cases';

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