<?php
class GpsDevicesController extends Controller
{
    public function indexAction($page = 1)
    {
        $page    = max(1, (int)$page);
        $perPage = defined('ROWS_PER_PAGE') ? ROWS_PER_PAGE : 20;

        $filters = [
            'q'           => trim((string)($_GET['q']           ?? '')),
            'status'      => trim((string)($_GET['status']      ?? '')),
            'device_type' => trim((string)($_GET['device_type'] ?? '')),
            'unassigned'  => (int)($_GET['unassigned'] ?? 0),
        ];

        $m      = new GpsDevices();
        $result = $m->listPaginated($page, $perPage, $filters);

        $qs      = http_build_query(array_filter($filters, fn($v) => $v !== '' && $v !== 0));
        $baseUrl = PROOT . 'GpsDevices/index/';
        $pg      = Pagination::paginate($result['total'], $perPage, $page, $baseUrl);
        $pgHtml  = $pg['html'];
        if ($qs && $pgHtml) {
            $pgHtml = preg_replace('~href=\'([^\']+)\'~', "href='$1?" . htmlspecialchars($qs) . "'", $pgHtml);
        }

        $this->view->setLayout($this->roleLayout());
        $this->view->render('GpsDevices/index', [
            'page_title' => 'GPS Devices',
            'rows'       => $result['rows'],
            'total'      => $result['total'],
            'page'       => $page,
            'filters'    => $filters,
            'pg_html'    => $pgHtml,
        ]);
    }

    public function addAction()
    {
        $this->view->setLayout($this->roleLayout());
        $this->view->render('GpsDevices/add', [
            'page_title' => 'Register GPS Device',
            'trucks'     => $this->truckOptions(),
            'form'       => [],
            'fb_msg'     => '',
        ]);
    }

    public function saveAction()
    {
        $this->verifyCsrf();
        if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') { Router::redirect('GpsDevices/add'); return; }
        $r = (new GpsDevices())->create($_POST, $this->currentUserId());
        if (!$r['ok']) {
            $this->view->setLayout($this->roleLayout());
            $this->view->render('GpsDevices/add', [
                'page_title' => 'Register GPS Device',
                'trucks'     => $this->truckOptions(),
                'form'       => $_POST,
                'fb_msg'     => '<div class="alert alert-danger">' . htmlspecialchars($r['msg']) . '</div>',
            ]);
            return;
        }
        $_SESSION['flash_tenant_msg']  = $r['msg'];
        $_SESSION['flash_tenant_type'] = 'success';
        Router::redirect('GpsDevices/view/' . $r['id']);
    }

    public function viewAction($id = 0)
    {
        $m = new GpsDevices();
        $g = $m->byId((int)$id);
        if (!$g) { $this->notFound('GPS device'); return; }
        $this->view->setLayout($this->roleLayout());
        $this->view->render('GpsDevices/view', [
            'page_title' => $g['device_code'] . ' · GPS Device',
            'g'          => $g,
        ]);
    }

    public function editAction($id = 0)
    {
        $g = (new GpsDevices())->byId((int)$id);
        if (!$g) { $this->notFound('GPS device'); return; }
        $this->view->setLayout($this->roleLayout());
        $this->view->render('GpsDevices/edit', [
            'page_title' => 'Edit · ' . $g['device_code'],
            'g'          => $g,
            'trucks'     => $this->truckOptions(),
            'form'       => $g,
            'fb_msg'     => '',
        ]);
    }

    public function updateAction($id = 0)
    {
        $this->verifyCsrf();
        if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') { Router::redirect('GpsDevices/edit/' . (int)$id); return; }
        $r = (new GpsDevices())->update((int)$id, $_POST, $this->currentUserId());
        $_SESSION['flash_tenant_msg']  = $r['msg'] ?? '';
        $_SESSION['flash_tenant_type'] = $r['ok'] ? 'success' : 'danger';
        Router::redirect('GpsDevices/view/' . (int)$id);
    }

    public function deleteAction($id = 0)
    {
        $this->verifyCsrf();
        if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') { Router::redirect('GpsDevices/view/' . (int)$id); return; }
        (new GpsDevices())->softDelete((int)$id, $this->currentUserId());
        $_SESSION['flash_tenant_msg']  = 'Device removed.';
        $_SESSION['flash_tenant_type'] = 'success';
        Router::redirect('GpsDevices');
    }

    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>',
        ]);
    }

    private function truckOptions(): array
    {
        return (new DB())->mySelect(
            "SELECT c0d, reg_no, make, model FROM trucks WHERE deleted = 0 ORDER BY reg_no ASC", []
        ) ?: [];
    }
}
