<?php
class SupplierBillsController 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']         ?? '')),
            'status'    => trim((string)($_GET['status']    ?? '')),
            'vendor_id' => (int)   ($_GET['vendor_id']      ?? 0),
            'from_date' => trim((string)($_GET['from_date'] ?? '')),
            'to_date'   => trim((string)($_GET['to_date']   ?? '')),
        ];

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

        $qs      = http_build_query(array_filter($filters, fn($v) => $v !== '' && $v !== 0));
        $baseUrl = PROOT . 'SupplierBills/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('SupplierBills/index', [
            'page_title'  => 'Supplier Bills',
            'rows'        => $result['rows'],
            'suppliers'   => (new Suppliers())->allActive(),
            'counts'      => $m->statusCounts(),
            'filters'     => $filters,
            'pg_html'     => $pgHtml,
        ]);
    }

    public function addAction()
    {
        $this->view->setLayout($this->roleLayout());
        $this->view->render('SupplierBills/add', [
            'page_title' => 'New Supplier Bill',
            'suppliers'  => (new Suppliers())->allActive(),
            'expenses'   => $this->expenseAccounts(),
            'form'       => [],
            'fb_msg'     => '',
        ]);
    }

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

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

        $this->view->setLayout($this->roleLayout());
        $this->view->render('SupplierBills/view', [
            'page_title' => $bill['bill_no'] . ' · Bill',
            'bill'       => $bill,
            'payments'   => $m->paymentsFor((int)$id),
        ]);
    }

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

    public function voidBillAction($id = 0)
    {
        $this->verifyCsrf();
        if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') { Router::redirect('SupplierBills/view/' . (int)$id); return; }
        $reason = trim((string)($_POST['reason'] ?? ''));
        if ($reason === '') { $_SESSION['flash_tenant_msg'] = 'Reason required.'; $_SESSION['flash_tenant_type'] = 'danger';
            Router::redirect('SupplierBills/view/' . (int)$id); return; }
        $r = (new SupplierBills())->voidBill((int)$id, $reason, $this->currentUserId(), $_SESSION['full_name'] ?? '');
        $_SESSION['flash_tenant_msg']  = $r['msg'];
        $_SESSION['flash_tenant_type'] = $r['ok'] ? 'success' : 'danger';
        Router::redirect('SupplierBills/view/' . (int)$id);
    }

    /* ── helpers ───────────────────────────────────────────────────── */

    private function expenseAccounts(): array
    {
        $db = new DB();
        return $db->mySelect(
            "SELECT c0d, account_code, account_name FROM chart_of_accounts
              WHERE is_active = 1 AND account_type = 'EXPENSE'
           ORDER BY account_code", []
        ) ?: [];
    }

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