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

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

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

    public function addAction()
    {
        $this->view->setLayout($this->roleLayout());
        $this->view->render('Geofences/edit', [
            'page_title' => 'Add Geofence',
            'g'          => [],
            'form'       => [],
            'customers'  => $this->customerOptions(),
            'is_new'     => true,
            'fb_msg'     => '',
        ]);
    }

    public function saveAction()
    {
        $this->verifyCsrf();
        if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') { Router::redirect('Geofences/add'); return; }
        $r = (new Geofences())->create($_POST, $this->currentUserId());
        if (!$r['ok']) {
            $this->view->setLayout($this->roleLayout());
            $this->view->render('Geofences/edit', [
                'page_title' => 'Add Geofence',
                'g'          => [],
                'form'       => $_POST,
                'customers'  => $this->customerOptions(),
                'is_new'     => true,
                '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('Geofences/view/' . $r['id']);
    }

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

    public function editAction($id = 0)
    {
        $g = (new Geofences())->byId((int)$id);
        if (!$g) { $this->notFound('Geofence'); return; }
        $this->view->setLayout($this->roleLayout());
        $this->view->render('Geofences/edit', [
            'page_title' => 'Edit · ' . $g['name'],
            'g'          => $g,
            'form'       => $g,
            'customers'  => $this->customerOptions(),
            'is_new'     => false,
            'fb_msg'     => '',
        ]);
    }

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

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

    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 customerOptions(): array
    {
        return (new DB())->mySelect(
            "SELECT c0d, TRIM(CONCAT(fname, ' ', lname)) AS customer_name
               FROM customers WHERE deleted = 0
           ORDER BY fname ASC, lname ASC", []
        ) ?: [];
    }
}
