<?php

namespace App\Http\Controllers;

namespace App\Http\Controllers\API\v1;

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

class LeaveTypeController 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 = LeaveType::where(function ($query) use ($keyword) {
            $keyword = str_replace(" ", "%", $keyword);
            $query->where('name', 'like', '%' . $keyword . '%');
        })
        ->select('id', 'name', 'description', 'max_leave', 'enabled');

        if (!empty($sortBy) && !empty($sortType)) {
            $data = $data->orderBy($sortBy, $sortType);
        }
        
        $data = $data->paginate($perPage);
        return response()->json($data);
    }

    public function getLeaveType(Request $request)
    {
        //
        $keyword = $request->input('keyword', '');
        $perPage = $request->input('per_page',PHP_INT_MAX);
        $sortBy = $request->input('sortBy', '');
        $sortType = $request->input('sortType', '');
        $data = LeaveType::select('id', 'name', 'description', 'max_leave', 'enabled')->get();

        // if (!empty($sortBy) && !empty($sortType)) {
        //     $data = $data->orderBy($sortBy, $sortType);
        // }
        
        // $data = $data->paginate($perPage);
        return response()->json($data);
    }

    public function getEmployeeLeaveType(Request $request)
    {
        $user = Auth::user();

        $data = LeaveType::join('employee_leave_credits', 'leave_types.id', '=', 'employee_leave_credits.leave_type_id')
            ->select('leave_types.id', 'leave_types.name')
            ->where('employee_leave_credits.employee_id', $user->employee_id)
            ->where('employee_leave_credits.remaining', '>', '0.49')
            ->get();

        // Check if Vacation Leave (id = 2) and Sick Leave (id = 3) exist
        $vacationLeaveExists = $data->contains('id', 2);
        $sickLeaveExists = $data->contains('id', 3);

        // Add Vacation Leave to the data if it doesn't exist
        if (!$vacationLeaveExists) {
            $data->push((object)[
                'id' => 2,
                'name' => 'Vacation Leave',
            ]);
        }

        // Add Sick Leave to the data if it doesn't exist
        if (!$sickLeaveExists) {
            $data->push((object)[
                'id' => 3,
                'name' => 'Sick Leave',
            ]);
        }

        // dd($data);

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

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

        /** 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 = LeaveType::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 = LeaveType::where('id', $id)->first();

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

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

        /** 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 = LeaveType::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);
    }
}
