<?php
class RoutesController 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']          ?? '')),
            'route_type' => trim((string)($_GET['route_type'] ?? '')),
            'active'     => isset($_GET['active']) && $_GET['active'] !== '' ? (int)$_GET['active'] : '',
        ];

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

        $qs      = http_build_query(array_filter($filters, fn($v) => $v !== '' && $v !== 0));
        $baseUrl = PROOT . 'Routes/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('Routes/index', [
            'page_title' => 'Routes',
            'rows'       => $result['rows'],
            'total'      => $result['total'],
            'page'       => $page,
            'filters'    => $filters,
            'pg_html'    => $pgHtml,
        ]);
    }

    public function addAction()
    {
        $this->view->setLayout($this->roleLayout());
        $this->view->render('Routes/add', [
            'page_title' => 'Add Route',
            'form'       => [],
            'fb_msg'     => '',
        ]);
    }

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

    public function viewAction($id = 0)
    {
        $m = new Routes();
        $r = $m->byId((int)$id);
        if (!$r) { $this->notFound('Route'); return; }
        $this->view->setLayout($this->roleLayout());
        $this->view->render('Routes/view', [
            'page_title' => $r['name'] . ' · Route',
            'r'          => $r,
        ]);
    }

    public function editAction($id = 0)
    {
        $m = new Routes();
        $r = $m->byId((int)$id);
        if (!$r) { $this->notFound('Route'); return; }
        $this->view->setLayout($this->roleLayout());
        $this->view->render('Routes/edit', [
            'page_title' => 'Edit · ' . $r['name'],
            'r'          => $r,
            'form'       => $r,
            'fb_msg'     => '',
        ]);
    }

    public function updateAction($id = 0)
    {
        $this->verifyCsrf();
        if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') { Router::redirect('Routes/edit/' . (int)$id); return; }
        $m = new Routes();
        $r = $m->update((int)$id, $_POST, $this->currentUserId());
        if (!$r['ok']) {
            $this->view->setLayout($this->roleLayout());
            $this->view->render('Routes/edit', [
                'page_title' => 'Edit Route',
                'r'          => $m->byId((int)$id),
                'form'       => $_POST,
                'fb_msg'     => '<div class="alert alert-danger">' . htmlspecialchars($r['msg']) . '</div>',
            ]);
            return;
        }
        $_SESSION['flash_tenant_msg']  = 'Route updated.';
        $_SESSION['flash_tenant_type'] = 'success';
        Router::redirect('Routes/view/' . (int)$id);
    }

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

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