<?php

namespace App\Http\Controllers\API\v1;

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

class PublicUndertimeController extends Controller
{
    public function approve(EmployeeUndertime $undertime, User $approver)
    {
        return $this->handleAction($undertime, $approver, 'approve');
    }

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

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

    private function handleAction(EmployeeUndertime $undertime, User $user, string $action)
    {
        $currentUser = Auth::user();

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

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

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

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

        if($processUndertimeApproval){
            $undertimeApprovalController = app()->make(UndertimeApprovalController::class);

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

            $undertimeApprovalController->update($request, $undertime->id);
        }

        if($processUndertimeDenial){
            $undertimeApprovalController = app()->make(UndertimeApprovalController::class);

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

            $undertimeApprovalController->update($request, $undertime->id);
        }

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

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

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

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

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

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

        return true;
    }

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

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

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