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

        $filters = [
            'status'   => trim((string)($_GET['status']   ?? 'open')),
            'kind'     => trim((string)($_GET['kind']     ?? '')),
            'severity' => trim((string)($_GET['severity'] ?? '')),
            'truck_id' => (int)($_GET['truck_id'] ?? 0),
        ];

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

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

        $this->view->setLayout($this->roleLayout());
        $this->view->render('PmDashboard/index', [
            'page_title' => 'PM Dashboard',
            'rows'       => $result['rows'],
            'total'      => $result['total'],
            'page'       => $page,
            'filters'    => $filters,
            'counts'     => $m->statusCounts(),
            'pg_html'    => $pgHtml,
        ]);
    }

    public function viewAction($id = 0)
    {
        $e = (new PmEvents())->byId((int)$id);
        if (!$e) { $this->notFound('PM event'); return; }
        $this->view->setLayout($this->roleLayout());
        $this->view->render('PmDashboard/view', [
            'page_title' => $e['event_no'] . ' · PM',
            'e'          => $e,
        ]);
    }

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

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

    /** Manual sweep trigger — useful for testing without waiting for cron. */
    public function triggerNowAction()
    {
        $this->verifyCsrf();
        if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') { Router::redirect('PmDashboard'); return; }
        $r = (new PmEvents())->sweepDue();
        $_SESSION['flash_tenant_msg']  = "PM sweep ran · {$r['emitted']} new events · {$r['updated']} escalated.";
        $_SESSION['flash_tenant_type'] = 'success';
        Router::redirect('PmDashboard');
    }

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