<?php

namespace App\Http\Controllers;

use App\Models\AuthorizationRequest;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class AuthorizationController extends Controller
{
    public function index()
    {
        $user = Auth::user();
        $accountId = $user->account_id;

        $query = AuthorizationRequest::with(['accessLog.visitor', 'accessLog.zone']);
        if ($accountId) {
            $query->where('account_id', $accountId);
        }

        $requests = $query->orderBy('created_at', 'desc')->get();

        if ($requests->isEmpty()) {
            $requests = $this->getMockRequests();
        }

        return view('authorizations.index', compact('requests'));
    }

    public function updateStatus($id, string $status)
    {
        if (!in_null($status, ['approved', 'rejected'])) {
            $req = AuthorizationRequest::findOrFail($id);
            $req->update([
                'status' => $status,
                'responded_at' => now(),
            ]);

            // Actualizar el estado del registro de acceso correspondiente
            $log = $req->accessLog;
            if ($log) {
                $log->update(['status' => $status === 'approved' ? \App\Enums\AccessStatus::AUTHORIZED : \App\Enums\AccessStatus::REJECTED]);
            }
        }

        return redirect()->route('authorizations.index')->with('success', 'Solicitud de autorización procesada.');
    }

    private function getMockRequests()
    {
        $requests = [];
        
        $r1 = new AuthorizationRequest();
        $r1->id = 1;
        $r1->requested_to_name = 'Juan Carlos Rojas (Depto 402B)';
        $r1->status = 'pending';
        $r1->created_at = now()->subMinutes(5);
        $r1->accessLog = (object)[
            'visitor' => (object)['full_name' => 'Luis Cáceres', 'rut' => '17.382.910-4'],
            'zone' => (object)['name' => 'Depto 402B'],
            'type' => (object)['value' => 'person']
        ];
        $requests[] = $r1;

        $r2 = new AuthorizationRequest();
        $r2->id = 2;
        $r2->requested_to_name = 'Administrador de Bodega Sur';
        $r2->status = 'approved';
        $r2->created_at = now()->subMinutes(15);
        $r2->responded_at = now()->subMinutes(14);
        $r2->accessLog = (object)[
            'visitor' => (object)['full_name' => 'Camión de carga Gasco', 'rut' => 'Patente RT-YG-90'],
            'zone' => (object)['name' => 'Bodega Sur'],
            'type' => (object)['value' => 'vehicle']
        ];
        $requests[] = $r2;

        return collect($requests);
    }
}
