<?php
/**
 * GpsDashboard controller.
 *
 *   /GpsDashboard                    → live map (all trucks)
 *   /GpsDashboard/truck/{id}         → single-truck detail (last 24h track + events)
 *   /GpsDashboard/trip/{id}          → trip playback
 *   /GpsDashboard/alerts             → filtered events feed
 *
 * JSON APIs (polled by the map JS):
 *   /GpsDashboard/livePositions       → all trucks + last position
 *   /GpsDashboard/truckTrack/{id}     → single truck's last 24h track + events
 *   /GpsDashboard/tripPoints/{id}     → full trip track for playback
 */
class GpsDashboardController extends Controller
{
    public function indexAction()
    {
        $m = new GpsDashboard();
        $this->view->setLayout($this->roleLayout());
        $this->view->render('GpsDashboard/index', [
            'page_title'  => 'GPS Dashboard',
            'summary'     => $m->fleetSummary(),
            'positions'   => $m->livePositions(),
            'geofences'   => $m->geofences(),
        ]);
    }

    public function truckAction($truckId = 0)
    {
        $truckId = (int)$truckId;
        $db = new DB();
        $t  = $db->mySelect(
            "SELECT tk.c0d, tk.reg_no AS truck_reg, tk.make, tk.model, tk.status,
                    d.c0d AS device_id, d.device_code, d.last_seen_at
               FROM trucks tk
          LEFT JOIN gps_devices d ON d.truck_id = tk.c0d AND d.deleted = 0
              WHERE tk.c0d = :id LIMIT 1",
            [':id' => $truckId]
        );
        if (empty($t)) { $this->notFound('Truck'); return; }

        $m     = new GpsDashboard();
        $track = $m->truckTrack($truckId, 24, 500);

        $this->view->setLayout($this->roleLayout());
        $this->view->render('GpsDashboard/truck', [
            'page_title' => 'GPS · ' . $t[0]['truck_reg'],
            'truck'      => $t[0],
            'track'      => $track,
            'geofences'  => $m->geofences(),
        ]);
    }

    public function tripAction($tripId = 0)
    {
        $tripId = (int)$tripId;
        $m = new GpsDashboard();
        $d = $m->tripPoints($tripId);
        if (empty($d['trip'])) { $this->notFound('Trip'); return; }

        $this->view->setLayout($this->roleLayout());
        $this->view->render('GpsDashboard/trip', [
            'page_title' => 'Trip playback · ' . $d['trip']['trip_no'],
            'data'       => $d,
            'geofences'  => $m->geofences(),
        ]);
    }

    public function alertsAction()
    {
        $filters = [
            'truck_id'  => (int)($_GET['truck_id'] ?? 0),
            'kind'      => trim((string)($_GET['kind']     ?? '')),
            'severity'  => trim((string)($_GET['severity'] ?? '')),
            'from'      => trim((string)($_GET['from']     ?? '')),
            'to'        => trim((string)($_GET['to']       ?? '')),
        ];

        $m = new GpsDashboard();

        // Trucks that have events (small dropdown, no pagination needed)
        $db     = new DB();
        $trucks = $db->mySelect(
            "SELECT DISTINCT tk.c0d, tk.truck_reg
               FROM trucks tk JOIN gps_events e ON e.truck_id = tk.c0d
              WHERE tk.deleted = 0
           ORDER BY tk.truck_reg", []
        ) ?: [];

        $this->view->setLayout($this->roleLayout());
        $this->view->render('GpsDashboard/alerts', [
            'page_title' => 'GPS Alerts',
            'events'     => $m->alerts($filters, 500),
            'filters'    => $filters,
            'trucks'     => $trucks,
        ]);
    }

    /* ══════════════ JSON APIs ══════════════ */

    public function livePositionsAction()
    {
        $this->jsonOut([
            'ts'        => date('c'),
            'positions' => (new GpsDashboard())->livePositions(),
            'summary'   => (new GpsDashboard())->fleetSummary(),
        ]);
    }

    public function truckTrackAction($truckId = 0)
    {
        $hours = max(1, min(168, (int)($_GET['hours'] ?? 24)));
        $this->jsonOut((new GpsDashboard())->truckTrack((int)$truckId, $hours, 800));
    }

    public function tripPointsAction($tripId = 0)
    {
        $this->jsonOut((new GpsDashboard())->tripPoints((int)$tripId));
    }

    /* ── helpers ───────────────────────────────────────────────────── */

    private function jsonOut(array $payload): void
    {
        if (ob_get_length()) ob_clean();
        header('Content-Type: application/json; charset=UTF-8');
        header('Cache-Control: no-cache, must-revalidate');
        echo json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        exit();
    }

    private function notFound(string $what): void
    {
        $this->view->setLayout($this->roleLayout());
        $this->view->render('generals/fb_page', [
            'page_title' => 'Not found',
            'fb_msg'     => '<div class="alert alert-danger">' . htmlspecialchars($what) . ' not found.</div>',
        ]);
    }
}
