<?php

namespace App\Http\Controllers\API\v1;

use App\Http\Controllers\Controller;
use App\Models\Employee;
use App\Models\EmployeeLeaveCredits;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rule;
use PHPUnit\Event\Code\Throwable;

class EmployeeLeaveCreditsController extends Controller
{
    public function index(Request $request)
    {
        $user = Auth::user();

        $keyword = $request->input('keyword', '');
        $perPage = $request->input('per_page', PHP_INT_MAX);
        $sortBy = $request->input('sortBy', '');
        $sortType = $request->input('sortType', '');
        $dealership_id = $request->input('dealership', null);


        // Check if data exists in cache, otherwise execute the query and cache the result
        $data = EmployeeLeaveCredits::with(['leave_type','employee'])->where(function ($query) use ($keyword) {
                    $keyword = str_replace(" ", "%", $keyword);
                    $query->where('employee_id','like',"{$keyword}%")
                    ->orWhereHas('leave_type', fn($q) => $q->where('name','like',"%{$keyword}%"))
                    ->orWhereHas('employee', fn($q) =>
                        $q->where('lastname', 'like',"%{$keyword}%")
                        ->orWhere('middlename', 'like',"%{$keyword}%")
                        ->orWhere('firstname', 'like',"%{$keyword}%"));
                })
                ->when(!empty($sortBy) && !empty($sortType), function ($query) use ($sortBy, $sortType) {
                    $query->orderBy($sortBy, $sortType);
                });

        if($user->roles[0]->group_id != 1 && $user->roles[0]->group_id != 2)
        {
            $data->whereHas('employee', fn($q) => $q->where('dealer_id', $dealership_id));
        }

        $data = $data->paginate($perPage);

        return response()->json($data);
    }

    public function show(Request $request, $id)
    {
        $employee_id = $request->input('employee_id');

        // Check if data exists in cache, otherwise execute the query and cache the result
        $data = EmployeeLeaveCredits::with(['leave_type','employee'])
                ->where('employee_id', $employee_id);

        return response()->json($data);
    }

    public function store(Request $request)
    {

        // dd($request->all());
        // Validate the incoming request data
        $company_id = Employee::where('employee_id', '=', $request->employee_id)->pluck('company_id')->first();

        $request['company_id'] = $company_id;

        $validator = Validator::make($request->all(), [
            'employee_id' => [
                'required',
            ],
            'leave_type_id' => [
                'required',
            ],
            'hours' => [
                '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 {
            foreach ($request->employee_id as $employee) {
                $request['employee_id'] = $employee;

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

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

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

        } catch (\Exception $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 = EmployeeLeaveCredits::where('id', $id)->first();

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

        $validator = Validator::make($request->all(),
            [
                'employee_id' => [
                    'required',
                ],
                'leave_type_id' => [
                    'required',
                ],
                'hours' => [
                    '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();

            // Invalidate cache for 'companies_' key when a company is updated
            Cache::forget('companies_'); // Adjust cache key if necessary

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

        } catch (\Exception $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 = EmployeeLeaveCredits::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);
    }
}
