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

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

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

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

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

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

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

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

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

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