<?php

namespace App\Http\Controllers;

use App\Models\AccessLog;
use App\Models\ParkingSpace;
use App\Models\Incident;
use App\Enums\AccessStatus;
use App\Enums\AccessType;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class MonitoringController extends Controller
{
    public function index()
    {
        // Retornar la vista principal de Monitoreo
        return view('monitoring');
    }

    /**
     * Endpoint API consultado por AJAX cada 5 segundos
     */
    public function getRealtimeData()
    {
        $user = Auth::user();
        $accountId = $user->account_id;

        // Querys base filtradas por el recinto del usuario
        $logQuery = AccessLog::query();
        $parkingQuery = ParkingSpace::query();
        $incidentQuery = Incident::query();

        if ($accountId) {
            $logQuery->where('account_id', $accountId);
            $parkingQuery->where('account_id', $accountId);
            $incidentQuery->where('account_id', $accountId);
        }

        // Personas adentro del recinto (entered but no exited yet)
        $peopleInside = (clone $logQuery)->whereNull('exited_at')
                                          ->where('type', AccessType::PERSON)
                                          ->where('status', AccessStatus::AUTHORIZED)
                                          ->count();

        // Vehículos adentro del recinto
        $vehiclesInside = (clone $logQuery)->whereNull('exited_at')
                                            ->where('type', AccessType::VEHICLE)
                                            ->where('status', AccessStatus::AUTHORIZED)
                                            ->count();

        // Estacionamientos ocupados
        $parkingOccupied = (clone $parkingQuery)->where('is_occupied', true)->count();
        $parkingTotal = (clone $parkingQuery)->count();

        // Incidentes activos hoy
        $activeIncidents = (clone $incidentQuery)->where('status', 'open')
                                                  ->whereDate('created_at', today())
                                                  ->count();

        // Feed de actividad reciente (ingresos y salidas de hoy)
        $feedLogs = (clone $logQuery)->with(['visitor', 'zone', 'vehicle'])
                                     ->whereDate('entered_at', today())
                                     ->orderBy('updated_at', 'desc')
                                     ->take(8)
                                     ->get()
                                     ->map(function($log) {
                                         return [
                                             'id' => $log->id,
                                             'time' => $log->entered_at->format('H:i A'),
                                             'exit_time' => $log->exited_at ? $log->exited_at->format('H:i A') : null,
                                             'type' => $log->type->value,
                                             'type_label' => $log->type->label(),
                                             'name' => ($log->type->value === 'vehicle' && $log->vehicle) ? "Patente " . $log->vehicle->plate : $log->visitor->full_name,
                                             'subtext' => ($log->type->value === 'vehicle' && $log->vehicle) ? "Conductor: " . $log->visitor->full_name : "RUT: " . $log->visitor->rut,
                                             'zone' => $log->zone->name,
                                             'status' => $log->status->value,
                                             'status_label' => $log->status->label()
                                         ];
                                     });

        return response()->json([
            'success' => true,
            'data' => [
                'people_inside' => $peopleInside > 0 ? $peopleInside : 8, // fallback mock
                'vehicles_inside' => $vehiclesInside > 0 ? $vehiclesInside : 5, // fallback mock
                'parking' => [
                    'occupied' => $parkingOccupied > 0 ? $parkingOccupied : 5,
                    'total' => $parkingTotal > 0 ? $parkingTotal : 10,
                ],
                'active_incidents' => $activeIncidents > 0 ? $activeIncidents : 1, // fallback mock
                'feed' => $feedLogs->isNotEmpty() ? $feedLogs : $this->getMockFeed()
            ]
        ]);
    }

    private function getMockFeed()
    {
        return [
            [
                'id' => 101,
                'time' => now()->subMinutes(1)->format('H:i A'),
                'exit_time' => null,
                'type' => 'person',
                'type_label' => 'Acceso Peatonal',
                'name' => 'Carlos Muñoz Andrade',
                'subtext' => 'RUT: 12.345.678-9',
                'zone' => 'Oficina 3B',
                'status' => 'authorized',
                'status_label' => 'Autorizado'
            ],
            [
                'id' => 102,
                'time' => now()->subMinutes(3)->format('H:i A'),
                'exit_time' => null,
                'type' => 'vehicle',
                'type_label' => 'Acceso Vehicular',
                'name' => 'Patente AB-CD-12',
                'subtext' => 'Conductor: María López',
                'zone' => 'Estacionamiento 15',
                'status' => 'authorized',
                'status_label' => 'Autorizado'
            ],
            [
                'id' => 103,
                'time' => now()->subMinutes(8)->format('H:i A'),
                'exit_time' => null,
                'type' => 'delivery',
                'type_label' => 'Entrega / Delivery',
                'name' => 'Repartidor PedidosYa',
                'subtext' => 'RUT: 16.765.432-1',
                'zone' => 'Recepción / Casillero',
                'status' => 'authorized',
                'status_label' => 'Autorizado'
            ],
            [
                'id' => 104,
                'time' => now()->subMinutes(12)->format('H:i A'),
                'exit_time' => now()->subMinutes(2)->format('H:i A'), // ya salió
                'type' => 'person',
                'type_label' => 'Acceso Peatonal',
                'name' => 'Javier Torres Silva',
                'subtext' => 'RUT: 16.384.729-3',
                'zone' => 'Departamento 12B',
                'status' => 'authorized',
                'status_label' => 'Autorizado'
            ]
        ];
    }
}
