<?php
class AlertsController 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),
            'from_date' => trim((string)($_GET['from_date'] ?? '')),
            'to_date'   => trim((string)($_GET['to_date']   ?? '')),
        ];

        $m      = new Alerts();
        $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 . 'Alerts/index/');
        $pgHtml  = $pg['html'];
        if ($qs && $pgHtml) $pgHtml = preg_replace('~href=\'([^\']+)\'~', "href='$1?" . htmlspecialchars($qs) . "'", $pgHtml);

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

    public function viewAction($id = 0)
    {
        $a = (new Alerts())->byId((int)$id);
        if (!$a) { $this->notFound('Alert'); return; }
        $this->view->setLayout($this->roleLayout());
        $this->view->render('Alerts/view', ['page_title' => 'Alert · ' . $a['kind'], 'a' => $a]);
    }

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

    public function resolveAction($id = 0)
    {
        $this->verifyCsrf();
        if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') { Router::redirect('Alerts'); return; }
        (new Alerts())->resolve((int)$id, $this->currentUserId(), trim((string)($_POST['resolution_note'] ?? '')));
        $_SESSION['flash_tenant_msg']  = 'Alert resolved.';
        $_SESSION['flash_tenant_type'] = 'success';
        Router::redirect('Alerts/view/' . (int)$id);
    }

    public function dismissAction($id = 0)
    {
        $this->verifyCsrf();
        if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') { Router::redirect('Alerts'); return; }
        (new Alerts())->dismiss((int)$id, $this->currentUserId(), trim((string)($_POST['resolution_note'] ?? '')));
        $_SESSION['flash_tenant_msg']  = 'Alert dismissed.';
        $_SESSION['flash_tenant_type'] = 'success';
        Router::redirect('Alerts');
    }

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