<?php

namespace App\Http\Controllers\API\v1;

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

class PublicObController extends Controller
{
    public function approve(EmployeeOb $ob, User $approver)
    {
        return $this->handleAction($ob, $approver, 'approve');
    }

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

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

    private function handleAction(EmployeeOb $ob, $user, string $action)
    {
        $currentUser = $user;

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

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

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

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

        if($processObApproval){
            $obApprovalController = app()->make(TravelApprovalController::class);

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

            $obApprovalController->update($request, $ob->id);
        }

        if($processObDenial){
            $obApprovalController = app()->make(TravelApprovalController::class);

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

            $obApprovalController->update($request, $ob->id);
        }

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

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

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

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

    private function userCanPerformAction(User $user, EmployeeOb $ob, 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 = EmployeeOb::with(['recommending', 'approving', 'employee'])
            ->join('employees', 'employee_obs.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_obs.enabled', 1)
            ->whereNull('employee_obs.deleted_at')
            ->select('employees.*', 'employee_obs.*', 'employee_obs.created_at as ob_created_at')
            ->selectRaw(
                '(SELECT COUNT(*) FROM employee_obs AS eo WHERE eo.status IN (0, 1) AND (eo.recommending_id = ? OR eo.approver_id = ?)) AS pending,
                (SELECT COUNT(*) FROM employee_obs AS eo WHERE eo.status = 2 AND (eo.recommending_id = ? OR eo.approver_id = ?)) AS approved,
                (SELECT COUNT(*) FROM employee_obs 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 processObAction(EmployeeOb $ob, string $action, User $approver, string $comments): void
    {
        $status = $action === 'approve' ? 2 : 99;
        
        $ob->update([
            'status' => $status,
            'approved_by' => $approver->id,
            'approved_at' => now(),
            'comments' => $comments
        ]);

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

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