<?php
class CustomersController 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']      ?? '')),
            'tier'   => trim((string)($_GET['tier']   ?? '')),
            'sector' => trim((string)($_GET['sector'] ?? '')),
            'status' => trim((string)($_GET['status'] ?? '')),
        ];

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

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

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

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

    public function viewAction($id = 0)
    {
        $m = new Customers();
        $c = $m->byId((int)$id);
        if (!$c) { $this->notFound('Customer'); return; }

        $this->view->setLayout($this->roleLayout());
        $this->view->render('Customers/view', [
            'page_title' => $c['fname'] . ' · Customer',
            'c'          => $c,
        ]);
    }

    public function editAction($id = 0)
    {
        $m = new Customers();
        $c = $m->byId((int)$id);
        if (!$c) { $this->notFound('Customer'); return; }

        $this->view->setLayout($this->roleLayout());
        $this->view->render('Customers/edit', [
            'page_title' => 'Edit · ' . $c['fname'],
            'c'          => $c,
            'form'       => $c,
            'fb_msg'     => '',
        ]);
    }

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

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

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