<?php

namespace App\Http\Controllers\API\v1;

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

class PublicLeaveController extends Controller
{
    public function approve(EmployeeLeave $leave, User $approver)
    {
        return $this->handleAction($leave, $approver, 'approve');
    }

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

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

    // private function handleAction(EmployeeLeave $leave, User $user, string $action)
    // {
    //     // Remove &signature= from URL to rebuild it
    //     $url = request()->url();
    //     $query = request()->query();
        
    //     // Get the signature from request
    //     $providedSignature = $query['signature'] ?? null;
    //     unset($query['signature']);
        
    //     // Rebuild URL without signature
    //     $urlWithoutSignature = $url . '?' . http_build_query($query);
        
    //     // Generate what the signature SHOULD be
    //     $expectedSignature = hash_hmac('sha256', $urlWithoutSignature, config('app.key'));
        
    //     dd([
    //         'PROVIDED_SIGNATURE' => $providedSignature,
    //         'EXPECTED_SIGNATURE' => $expectedSignature,
    //         'SIGNATURES_MATCH' => hash_equals($expectedSignature, $providedSignature ?? ''),
    //         'URL_WITHOUT_SIG' => $urlWithoutSignature,
    //         'FULL_URL' => request()->fullUrl(),
    //         'APP_KEY_EXISTS' => !empty(config('app.key')),
    //         'EXPIRES' => $query['expires'] ?? null,
    //         'CURRENT_TIME' => time(),
    //         'IS_EXPIRED' => isset($query['expires']) ? (time() > $query['expires']) : null,
    //     ]);
    // }
    private function handleAction(EmployeeLeave $leave, $user, string $action)
    {
        $currentUser = $user;

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

        // Check leave status
        // dd([
        //     'employee id' => $currentUser->employee_id,
        //     'recommending id' => $leave->recommending_id,
        //     'leave status' => $leave->status,
        //     'approver id' => $leave->approver_id,
        // ]);

        // if(($currentUser->employee_id == $leave->recommending_id && $currentUser->employee_id == $leave->approver_id) && $leave->status == 2){
        //     return response()->json([
        //         'error' => 'ACTION UNAVAILABLE',
        //         'message' => 'You already processed this leave application.'
        //     ], 403);
        // } else if(($currentUser->employee_id == $leave->recommending_id && $leave->status == 1)){
        //     return response()->json([
        //         'error' => 'ACTION UNAVAILABLE',
        //         'message' => 'You already processed this leave application.'
        //     ], 403);
        // } else if(($currentUser->employee_id == $leave->approver_id && $leave->status == 2)){
        //     return response()->json([
        //         'error' => 'ACTION UNAVAILABLE',
        //         'message' => 'You already processed this leave application.'
        //     ], 403);
        // }

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

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

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

        if($processLeaveApproval){
            $leaveApprovalController = app()->make(LeaveApprovalController::class);

            $request = new Request();
            $request->merge($leave->toArray()); // Convert leave model to array
            $approvers = explode(',', $leave->approvers); // convert string to array

            $request->merge([
                'status' => in_array($currentUser->employee_id, $approvers) ? '2' : '1',
            ]);

            $leaveApprovalController->update($request, $leave->id);
        }

        if($processLeaveDenial){
            $leaveApprovalController = app()->make(LeaveApprovalController::class);

            $request = new Request();
            $request->merge($leave->toArray()); // Convert leave model to array
            $request->merge([
                'status' => 99,
            ]);

            $leaveApprovalController->update($request, $leave->id);
        }

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

    public function process(EmployeeLeave $leave, 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($leave, $action) || 
            !$this->userCanPerformAction($approver, $leave, $action)) {
            return response()->json(['error' => 'Action not permitted'], 403);
        }

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

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

    private function userCanPerformAction(User $user, EmployeeLeave $leave, 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 = EmployeeLeave::with(['recommending', 'approving', 'employee', 'leave_type'])
        //     ->join('employees', 'employee_leaves.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_leaves.enabled', 1)
        //     ->whereNull('employee_leaves.deleted_at')
        //     ->select('employees.*', 'employee_leaves.*', 'employee_leaves.created_at as leave_created_at')
        //     ->selectRaw(
        //         '(SELECT COUNT(*) FROM employee_leaves AS el WHERE el.status IN (0, 1) AND (el.recommending_id = ? OR el.approver_id = ?)) AS pending,
        //         (SELECT COUNT(*) FROM employee_leaves AS el WHERE el.status = 2 AND (el.recommending_id = ? OR el.approver_id = ?)) AS approved,
        //         (SELECT COUNT(*) FROM employee_leaves AS el WHERE el.status = 99 AND (el.recommending_id = ? OR el.approver_id = ?)) AS denied',
        //         [$currentEmp, $currentEmp, $currentEmp, $currentEmp, $currentEmp, $currentEmp]
        //     )
        //     ->orderBy('status', 'ASC')
        //     ->get();

        $approvers = explode(',', $leave->approvers);
        $recommendings = explode(',', $leave->recommendings);

        $data = EmployeeLeave::with(['recommending', 'approving', 'employee', 'leave_type'])
            ->join('employees', 'employee_leaves.employee_id', '=', 'employees.employee_id')
            ->where('employee_leaves.enabled', 1)
            ->whereNull('employee_leaves.deleted_at')
            ->where(function ($q) use ($currentEmp) {
                $q->whereRaw("FIND_IN_SET(?, employee_leaves.approvers)", [$currentEmp])
                ->orWhereRaw("FIND_IN_SET(?, employee_leaves.recommendings)", [$currentEmp]);
            })
            ->select('employees.*', 'employee_leaves.*', 'employee_leaves.created_at as leave_created_at')
            ->orderBy('status', 'ASC')
            ->get();


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

        return true;
        // dd($leave->employee_id);
        // if (($leave->employee_id === $user->employee_id) && in_array($action, ['approve', 'deny'])) {
        //     return false;
        // }

        // return false;
    }

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

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

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