<?php

namespace App\Http\Controllers\API\v1;

use App\Http\Controllers\Controller;
use App\Models\Approver;
use App\Models\EmployeeOvertime;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;

class PublicOvertimeController extends Controller
{
    public function approve(EmployeeOvertime $overtime, User $approver)
    {
        return $this->handleAction($overtime, $approver, 'approve');
    }

    public function deny(EmployeeOvertime $overtime, User $approver)
    {
        return $this->handleAction($overtime, $approver, 'deny');
    }

    public function view(EmployeeOvertime $overtime, User $viewer)
    {
        return $this->handleAction($overtime, $viewer, 'view');
    }

    private function handleAction(EmployeeOvertime $overtime, $user, string $action)
    {
        $currentUser = $user;

        $processOvertimeApproval = $action === 'approve';
        $processOvertimeDenial = $action === 'deny';
        
        // Verify signed URL
        // if (!request()->hasValidSignature()) {
        //     return response()->json([
        //         'error' => 'INVALID_SIGNATURE',
        //         'message' => 'This link has expired or is invalid.'
        //     ], 401);
        // }

        // // Check overtime status
        // if (($user->employee_id == $overtime->recommending_id && $overtime->status != 0) || 
        //     $user->employee_id == $overtime->approver_id && $overtime->status != 1) {
        //     return response()->json([
        //         'error' => 'ACTION UNAVAILABLE',
        //         'message' => 'You already processed this overtime application.'
        //     ], 403);
        // }

        // // Check if action is still valid
        // if (!$this->isActionValid($overtime, $action)) {
        //     return response()->json([
        //         'error' => 'ACTION_UNAVAILABLE',
        //         'message' => 'This overtime application can no longer be ' . $action . 'd.',
        //         'overtime' => [
        //             'id' => $overtime->id,
        //             'status' => $overtime->status,
        //             'current_status_text' => $this->getStatusText($overtime)
        //         ]
        //     ], 422);
        // }

        // // Check user permissions
        // if (!$this->userCanPerformAction($user, $overtime, $action)) {
        //     return response()->json([
        //         'error' => 'UNAUTHORIZED',
        //         'message' => 'You are not authorized to perform this action.'
        //     ], 403);
        // }

        if($processOvertimeApproval){
            $overtimeApprovalController = app()->make(OvertimeApprovalController::class);

            $request = new Request();
            $request->merge($overtime->toArray());
            $request->merge([
                'status' => $currentUser->employee_id == $overtime->approver_id ? '2' : '1',
            ]);

            $overtimeApprovalController->update($request, $overtime->id);
        }

        if($processOvertimeDenial){
            $overtimeApprovalController = app()->make(OvertimeApprovalController::class);

            $request = new Request();
            $request->merge($overtime->toArray());
            $request->merge([
                'status' => 99,
            ]);

            $overtimeApprovalController->update($request, $overtime->id);
        }

        // Return overtime data and user context
        return response()->json([
            'success' => true,
            'overtime' => [
                'id' => $overtime->id,
                'employee' => [
                    'name' => $overtime->employee->firstname . ' ' . $overtime->employee->lastname,
                    'id' => $overtime->employee->id
                ],
                'overtime_date' => $overtime->date_from,
                'from_time' => $overtime->from_time,
                'to_time' => $overtime->to_time,
                'hours' => $overtime->hours,
                'purpose' => $overtime->purpose ?? $overtime->reason,
                'status' => $overtime->status,
                'created_at' => $overtime->created_at,
            ],
            'action' => $action,
            'user' => [
                'id' => $user->id,
                'name' => $user->name,
                'email' => $user->email
            ],
            'can_process' => $action !== 'view',
            'process_url' => $action !== 'view' ? route('api.overtime.public.process', [$overtime, $user]) : null
        ]);
    }

    public function process(EmployeeOvertime $overtime, User $approver, Request $request)
    {
        if (!request()->hasValidSignature()) {
            return response()->json(['error' => 'Invalid or expired link'], 401);
        }

        $action = $request->input('action');
        $comments = $request->input('comments', '');
        
        if (!in_array($action, ['approve', 'deny'])) {
            return response()->json(['error' => 'Invalid action'], 400);
        }

        if (!$this->isActionValid($overtime, $action) || 
            !$this->userCanPerformAction($approver, $overtime, $action)) {
            return response()->json(['error' => 'Action not permitted'], 403);
        }

        try {
            $this->processOvertimeAction($overtime, $action, $approver, $comments);
            
            return response()->json([
                'success' => true,
                'message' => "Overtime application has been {$action}d successfully.",
                'overtime' => [
                    'id' => $overtime->id,
                    'status' => $overtime->status,
                    'approved_by' => $overtime->approved_by,
                    'approved_at' => $overtime->approved_at,
                    'comments' => $overtime->comments
                ]
            ]);
            
        } catch (\Exception $e) {
            Log::error('Overtime action processing failed', [
                'overtime_id' => $overtime->id,
                'action' => $action,
                'approver_id' => $approver->id,
                'error' => $e->getMessage()
            ]);
            
            return response()->json(['error' => 'Failed to process action'], 500);
        }
    }

    private function isActionValid(EmployeeOvertime $overtime, string $action): bool
    {
        if (in_array($action, ['approve', 'deny'])) {
            return in_array($overtime->status, [0, 1]);
        }
        return true;
    }

    private function userCanPerformAction(User $user, EmployeeOvertime $overtime, string $action): bool
    {
        $employee = Auth::user();
        
        $currentEmp = $employee->employees ? $employee->employees->employee_id : '';

        DB::enableQueryLog();

        $approverHierarchy = Approver::where('approvers', 'like', '%"'.$currentEmp.'"%')->get()
                ->groupBy('type')->map(fn($group) => $group->pluck('type_id')->toArray());

        $classification_id = $user->employees->classification_id;

        $data = EmployeeOvertime::with(['recommending', 'approving', 'employee'])
            ->join('employees', 'employee_overtimes.employee_id', '=', 'employees.employee_id')
            ->where(function ($query) use ($employee) {
                $employeeId = optional($employee->employees)->employee_id;
                if ($employeeId) {
                    $query->where('recommending_id', $employeeId)
                        ->orWhere('approver_id', $employeeId);
                }
            })
            ->orWhere(function ($query) use ($approverHierarchy) { 
                foreach ($approverHierarchy as $type => $ids) {
                    $column = $type === 'dealership' ? 'employees.dealer_id' : "employees.{$type}_id";
                    $query->orWhereIn($column, $ids);
                }
            })
            ->where('employee_overtimes.enabled', 1)
            ->whereNull('employee_overtimes.deleted_at')
            ->select('employees.*', 'employee_overtimes.*', 'employee_overtimes.created_at as overtime_created_at')
            ->selectRaw(
                '(SELECT COUNT(*) FROM employee_overtimes AS eo WHERE eo.status IN (0, 1) AND (eo.recommending_id = ? OR eo.approver_id = ?)) AS pending,
                (SELECT COUNT(*) FROM employee_overtimes AS eo WHERE eo.status = 2 AND (eo.recommending_id = ? OR eo.approver_id = ?)) AS approved,
                (SELECT COUNT(*) FROM employee_overtimes AS eo WHERE eo.status = 99 AND (eo.recommending_id = ? OR eo.approver_id = ?)) AS denied',
                [$currentEmp, $currentEmp, $currentEmp, $currentEmp, $currentEmp, $currentEmp]
            )
            ->orderBy('status', 'ASC')
            ->get();

        if($data->isEmpty()) return false;

        return true;
    }

    private function processOvertimeAction(EmployeeOvertime $overtime, string $action, User $approver, string $comments): void
    {
        $status = $action === 'approve' ? 2 : 99;
        
        $overtime->update([
            'status' => $status,
            'approved_by' => $approver->id,
            'approved_at' => now(),
            'comments' => $comments
        ]);

        Log::info('Overtime action processed via email link', [
            'overtime_id' => $overtime->id,
            'action' => $action,
            'approver_id' => $approver->id,
            'comments' => $comments
        ]);
    }

    private function getStatusText(EmployeeOvertime $overtime): string
    {
        if ($overtime->validated == 1) return 'Validated by HR';
        if ($overtime->validated == 99) return 'Denied by HR';
        if ($overtime->status == 2) return 'Approved';
        if ($overtime->status == 99) return 'Denied';
        return 'Pending Review';
    }
}