<?php

namespace App\Http\Controllers;

namespace App\Http\Controllers\API\v1;

use App\Http\Controllers\Controller;
use App\Models\Holiday;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rule;
use PHPUnit\Event\Code\Throwable;
use Illuminate\Support\Str;

class HolidayController extends Controller
{
    
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
    {
        //
        $keyword = $request->input('keyword', '');
        $perPage = $request->input('per_page',PHP_INT_MAX);
        $sortBy = $request->input('sortBy', '');
        $sortType = $request->input('sortType', '');

        $data = Holiday::select(
            "holidays.id", 
            "holidays.name", 
            "holidays.from_date", 
            "holidays.to_date", 
            "holidays.description", 
            "holidays.recurring", 
            DB::raw("ht.id as holiday_type"), 
            DB::raw("c.id as company_id"), 
            DB::raw("d.id as dealership_id"), 
            DB::raw("ht.name as holiday_type_name"), 
            DB::raw("c.name as company_name"), 
            DB::raw("d.name as dealership_name") 
        )
        ->join('holiday_types as ht','holidays.holiday_type', '=', 'ht.id')
        ->join('companies as c','holidays.company_id', '=', 'c.id', 'left')
        ->join('dealerships as d','holidays.dealership_id', '=', 'd.id', 'left')
        ->where(function ($query) use ($keyword){
            $query->where('holidays.name', 'like', '%' . $keyword . '%')
            ->orWhere('ht.name', 'like', '%' . $keyword . '%')
            ->orWhere('c.name', 'like', '%' . $keyword . '%')
            ->orWhere('d.name', 'like', '%' . $keyword . '%');
        });  
        if (!empty($sortBy) && !empty($sortType)) {
            $data = $data->orderBy($sortBy, $sortType);
        }


        if (!empty($sortBy) && !empty($sortType)) {
            $data = $data->orderBy($sortBy, $sortType);
        }

        $data = $data->paginate($perPage);
        return response()->json($data);
    }

    public function store(Request $request)
    {
        // Validate the incoming request data
        $validator = Validator::make($request->all(), [
            'holiday_type' => [
                'required',
            ],
            'name' => [
                'required',
                'min:2',
                Rule::unique('holidays')->whereNull('deleted_at')
            ],
            'from_date' => [
                'required',
            ],
            'to_date' => [
                'required',
            ],
        ]);

        /** If validation fails return with error message */
        if ($validator->fails()) {
            $errors = $validator->errors();
            $first = $errors->getMessages();
            return response()->json([
                'status'  => false,
                'message' => (reset($first))[0],
                'errors'  => $errors
            ], Response::HTTP_UNPROCESSABLE_ENTITY);
        }

        DB::connection()->beginTransaction();

        try {

            $data = Holiday::create($request->all());

            DB::connection()->commit();

            return response()->json([
                'message' => 'Record Successfully added!',
                'status' => 'success',
            ],201);

        } catch (Throwable $e) {
            DB::connection()->rollback();
            return response()->json([
                'status'  => false,
                'message' => 'Unable to process request. Please try again.',
                'data'    => $e->getMessage()
            ]);
        }
    }

    public function update(Request $request, int $id)
    {

        $data = Holiday::where('id', $id)->first();

        if (!$data) {
            return response()->json(['messages' => 'No data found.'], 404);
        }

        $validator = Validator::make($request->all(),
            [
                'holiday_type' => [
                    'required',
                ],
                'name' => [
                    'required',
                    'min:2',
                    Rule::unique('holidays')->ignore($id)->whereNull('deleted_at')
                ],
                'from_date' => [
                    'required',
                ],
                'to_date' => [
                    'required',
                ],
            ]
        );

        /** If validation fails return with error message */
        if ($validator->fails()) {
            $errors = $validator->errors();
            $first = $errors->getMessages();
            return response()->json([
                'status'  => false,
                'message' => (reset($first))[0],
                'errors'  => $errors
            ], Response::HTTP_UNPROCESSABLE_ENTITY);
        }

        DB::connection()->beginTransaction();

        try {

            $data->fill($request->all());
            $data->save();

            $data->touch();

            DB::connection()->commit();

            return response()->json([
                'message' => 'Record Successfully updated!',
                'status' => 'success',
                'data' => $data,
            ],201);

        } catch (Throwable $e) {
            DB::connection()->rollback();
            return response()->json([
                'status'  => false,
                'message' => 'Unable to process request. Please try again.',
                'data'    => $e->getMessage()
            ]);
        }
    }

    public function destroy(int $id)
    {
        $data = Holiday::find($id);
        if(!$data)
        {
            return response()->json(['message' => "Record not found!"],204);
        }
        DB::connection()->beginTransaction();
        $data->delete();
        DB::connection()->commit();
        return response()->json(['message' => "Record successfully deleted!"],201);
    }
}
