<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Models\GuardLocation;
use App\Enums\UserRole;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

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

        // Historial de ubicaciones del recinto de hoy
        $query = GuardLocation::with('guardUser');
        if ($accountId) {
            $query->whereHas('guardUser', function($q) use ($accountId) {
                $q->where('account_id', $accountId);
            });
        }
        
        $locations = $query->whereDate('recorded_at', today())
                           ->orderBy('recorded_at', 'desc')
                           ->take(15)
                           ->get();

        if ($locations->isEmpty()) {
            $locations = $this->getMockLocations();
        }

        return view('tracking', compact('locations'));
    }

    /**
     * API Endpoint: Guarda la posición actual enviada por el navegador del guardia
     */
    public function storePosition(Request $request)
    {
        $request->validate([
            'latitude' => 'required|numeric',
            'longitude' => 'required|numeric',
            'accuracy' => 'nullable|numeric'
        ]);

        $guard = Auth::user();

        $location = GuardLocation::create([
            'guard_id' => $guard->id,
            'latitude' => $request->latitude,
            'longitude' => $request->longitude,
            'accuracy' => $request->accuracy,
            'recorded_at' => now(),
        ]);

        return response()->json(['success' => true, 'id' => $location->id]);
    }

    /**
     * API Endpoint: Retorna las últimas posiciones conocidas de los guardias del recinto
     */
    public function getActiveGuards()
    {
        $user = Auth::user();
        $accountId = $user->account_id;

        // Obtener guardias de este recinto
        $guardsQuery = User::where('role', UserRole::GUARD);
        if ($accountId) {
            $guardsQuery->where('account_id', $accountId);
        }
        $guards = $guardsQuery->get();

        $guardsPositions = [];

        foreach ($guards as $guard) {
            // Última ubicación registrada hoy
            $lastLoc = GuardLocation::where('guard_id', $guard->id)
                                    ->whereDate('recorded_at', today())
                                    ->orderBy('recorded_at', 'desc')
                                    ->first();

            if ($lastLoc) {
                $guardsPositions[] = [
                    'name' => $guard->name,
                    'phone' => $guard->phone,
                    'lat' => (float)$lastLoc->latitude,
                    'lng' => (float)$lastLoc->longitude,
                    'time' => $lastLoc->recorded_at->format('H:i:s'),
                    'accuracy' => $lastLoc->accuracy
                ];
            }
        }

        // Si la DB está vacía, entregamos datos ficticios realistas distribuidos en Santiago
        if (empty($guardsPositions)) {
            $guardsPositions = [
                [
                    'name' => 'Juan Pérez',
                    'phone' => '+56 9 8765 4321',
                    'lat' => -33.4485,
                    'lng' => -70.6700,
                    'time' => now()->format('H:i:s'),
                    'accuracy' => 15
                ],
                [
                    'name' => 'María González',
                    'phone' => '+56 9 7654 3210',
                    'lat' => -33.4492,
                    'lng' => -70.6690,
                    'time' => now()->subSeconds(45)->format('H:i:s'),
                    'accuracy' => 8
                ],
                [
                    'name' => 'Pedro Ramírez',
                    'phone' => '+56 9 6543 2109',
                    'lat' => -33.4490,
                    'lng' => -70.6685,
                    'time' => now()->subMinutes(2)->format('H:i:s'),
                    'accuracy' => 12
                ]
            ];
        }

        return response()->json([
            'success' => true,
            'data' => $guardsPositions
        ]);
    }

    private function getMockLocations()
    {
        $locations = [];
        
        $l1 = new GuardLocation();
        $l1->id = 1;
        $l1->latitude = -33.44850000;
        $l1->longitude = -70.67000000;
        $l1->accuracy = 15.00;
        $l1->recorded_at = now()->subMinutes(1);
        $l1->guardUser = (object)['name' => 'Juan Pérez'];
        $locations[] = $l1;

        $l2 = new GuardLocation();
        $l2->id = 2;
        $l2->latitude = -33.44920000;
        $l2->longitude = -70.66900000;
        $l2->accuracy = 8.00;
        $l2->recorded_at = now()->subMinutes(2);
        $l2->guardUser = (object)['name' => 'María González'];
        $locations[] = $l2;

        $l3 = new GuardLocation();
        $l3->id = 3;
        $l3->latitude = -33.44900000;
        $l3->longitude = -70.66850000;
        $l3->accuracy = 12.00;
        $l3->recorded_at = now()->subMinutes(4);
        $l3->guardUser = (object)['name' => 'Pedro Ramírez'];
        $locations[] = $l3;

        return collect($locations);
    }
}
