<?php

namespace App\Http\Controllers\API\v1;

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

class PublicTimeAdjustmentController extends Controller
{
    public function approve(EmployeeTimeAdjustment $timeAdjustment, User $approver)
    {
        return $this->handleAction($timeAdjustment, $approver, 'approve');
    }

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

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

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

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

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

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

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

        if($processTimeAdjustmentApproval){
            $timeAdjustmentApprovalController = app()->make(TimeAdjustmentApprovalController::class);

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

            $timeAdjustmentApprovalController->update($request, $timeAdjustment->id);
        }

        if($processTimeAdjustmentDenial){
            $timeAdjustmentApprovalController = app()->make(TimeAdjustmentApprovalController::class);

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

            $timeAdjustmentApprovalController->update($request, $timeAdjustment->id);
        }

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

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

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

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

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

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

        return true;
    }

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

        Log::info('Time adjustment action processed via email link', [
            'time_adjustment_id' => $timeAdjustment->id,
            'action' => $action,
            'approver_id' => $approver->id,
            'comments' => $comments
        ]);
    }

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