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

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

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

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

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

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

        // Also pull open bills so the view shows current exposure
        $db = new DB();
        $bills = $db->mySelect(
            "SELECT c0d, bill_no, bill_date, due_date, total_amount, amount_paid, status,
                    (total_amount - amount_paid) AS balance_due
               FROM supplier_bills WHERE vendor_id = :v AND deleted = 0
           ORDER BY bill_date DESC LIMIT 25",
            [':v' => (int)$id]
        ) ?: [];

        $this->view->setLayout($this->roleLayout());
        $this->view->render('Suppliers/view', [
            'page_title' => $s['vendor_name'] . ' · Supplier',
            's'          => $s,
            'bills'      => $bills,
        ]);
    }

    public function editAction($id = 0)
    {
        $m = new Suppliers();
        $s = $m->byId((int)$id);
        if (!$s) { $this->notFound('Supplier'); return; }
        $this->view->setLayout($this->roleLayout());
        $this->view->render('Suppliers/add', ['page_title' => 'Edit · ' . $s['vendor_name'],
            'form' => $s, 'fb_msg' => '', 'edit_id' => (int)$id]);
    }

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

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