<?php

namespace App\Http\Controllers\API\v1;

use App\Http\Controllers\Controller;
use App\Models\Employee;
use App\Models\EmployeeMonthlySchedule;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Throwable;

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

        // DB::enableQueryLog();

        // $keyword = $request->input('keyword', '');
        // $perPage = $request->input('per_page', PHP_INT_MAX);
        // $sortBy = $request->input('sortBy', 'pending');
        // $sortType = $request->input('sortType', 'desc');

        // $data = EmployeeMonthlySchedule::with(['recommending', 'approving', 'department', 'leave_type'])
        //     ->where(function ($query) use ($employee) {
        //         $query->where('recommending_id', $employee->employees ? $employee->employees->employee_id : '')
        //             ->orWhere('approver_id', $employee->employees ? $employee->employees->employee_id : '' );
        //     })
        //     ->where('enabled', 1)
        //     ->select('employee_monthly_schedules.*')
        //     ->orderBy($sortBy, $sortType)
        //     ->paginate($perPage);

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

        $currentEmp = $employee->employees ? $employee->employees->employee_id : '';


        $monthlyEmployeeScheduleRequest = EmployeeMonthlySchedule::with(['recommending', 'approving', 'department', 'requested'])
            ->where(function ($query) use ($employee) {
                $query->where('recommending_id', $employee->employees ? $employee->employees->employee_id : '')
                    ->orWhere('approver_id', $employee->employees ? $employee->employees->employee_id : '' );
            })
            ->where('enabled', 1)
            ->select('employee_monthly_schedules.*')
            ->whereNull('deleted_at')
            ->selectRaw('
                (SELECT COUNT(*) FROM employee_monthly_schedules AS ems WHERE ems.status IN (0, 1) AND (ems.recommending_id = '.$currentEmp.' OR ems.approver_id = '.$currentEmp.')) AS pending,
                (SELECT COUNT(*) FROM employee_monthly_schedules AS ems WHERE ems.status = 2 AND (ems.recommending_id = '.$currentEmp.' OR ems.approver_id = '.$currentEmp.')) AS approved,
                (SELECT COUNT(*) FROM employee_monthly_schedules AS ems WHERE ems.status = 99 AND (ems.recommending_id = '.$currentEmp.' OR ems.approver_id = '.$currentEmp.')) AS denied
            ')
            ->orderBy('status', 'ASC')
            ->get();

        $decodedSchedules = [];

        foreach ($monthlyEmployeeScheduleRequest as $schedule) {

            $decodedData = json_decode($schedule->data, true);

            $decodedSchedules[] = [
                'id' => $schedule->id,
                'department_name' => $schedule->department->name,
                'department_id' => $schedule->department_id,
                'department_ids' => $decodedData['department_ids'],
                'entries' => $decodedData['entries'],
                'status' => $schedule->status,
                'validated' =>$schedule->validated,
                'validated_by' =>$schedule->validated_by,
                'validated_at' =>$schedule->validated_at,
                'deferred_reason' => $schedule->deferred_reason,
                'recommending' => $schedule->recommending,
                'approving' => $schedule->approving,
                'recommending_id' => $schedule->recommending_id,
                'approver_id' => $schedule->approver_id,
                'requested_by' => $schedule->requested_by,
                'requested_name' => $schedule->requested->firstname.' '.$schedule->requested->lastname,
                'created_at' => $schedule->created_at,
                'updated_at' => $schedule->updated_at,
                'pending' => $schedule->pending,
                'approved' => $schedule->approved,
                'denied' => $schedule->denied,
            ];
        }

        // Return the decoded schedules as a JSON response
        return response()->json($decodedSchedules);
    }

    public function update(Request $request, int $id)
    {
        $data = EmployeeMonthlySchedule::with(['employee', 'requested'])->find($id);

        if($request->status  == 2){
            $scheduleData = json_decode($data->data, true);

            foreach ($scheduleData['entries'] as $entry) {
                foreach ($entry['employee'] as $employeeId) {

                    $company_id = Employee::where('employee_id', $employeeId)->pluck('company_id');

                    DB::table('employee_schedules')->insert([
                        'schedule_id'  => $entry['schedule_id'],
                        'employee_id'  => $employeeId,
                        'company_id'   => $company_id[0],
                        'date_from'    => $entry['date_from'],
                        'date_to'      => $entry['date_to'],
                        'effectivity_date'    => $entry['date_from'],
                        'created_at'   => now(),
                        'updated_at'   => now(),
                    ]);
                }
            }
        }

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

        DB::beginTransaction();

        try {
            $now = date('Y-m-d H:i:s');

            ($request->status == 2 ? $request['approved_at'] = $now : $request->status == 1)
             ? $request['recommended_at'] = $now : '';

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

            $data->touch();

            $employee_id_for_notification = $request->status == 1 ? $data->approver_id : $data->employee_id;

            DB::commit();

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

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

    public function HrValidation(Request $request,int $id){
        $status = $request->status;
        $data = EmployeeMonthlySchedule::with(['employee'])->where('id', $id)->first();
        if(!$data){
            return response()->json(['messages' => 'No data found.']);
        }
        $employee_id  =Auth::user()->employees->employee_id;
        
        DB::beginTransaction();
        try{
            $data->validated_by = $employee_id;
            $data->validated_at = now();
            $data->validated = $status;
            $data->deferred_reason = $request->reason;
            $data->save();
            // $email_to = $this->getEmployeeEmailData($data->employee_id);
            // Notification::send($email_to, new Travel($data));
            
            DB::commit();
            return response()->json([
                'message' => 'Record Successfully updated!',
                'status' => 'success',
                'data' => $data,
            ], 201);
        } catch (Throwable $e) {
            DB::rollback();
            return response()->json([
                'status'  => false,
                'message' => 'Unable to process request. Please try again.',
                'data'    => $e->getMessage()
            ]);
        }
        
    }

   
}
