<?php
class ExpensesController extends Controller
{
    /* =========================================================
     *  Read
     * ========================================================= */
    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']          ?? '')),
            'expense_type_id' => (int)($_GET['expense_type_id']         ?? 0),
            'truck_id'        => (int)($_GET['truck_id']                ?? 0),
            'driver_id'       => (int)($_GET['driver_id']               ?? 0),
            'from_date'       => trim((string)($_GET['from_date']       ?? '')),
            'to_date'         => trim((string)($_GET['to_date']         ?? '')),
        ];

        $m      = new Expenses();
        $result = $m->listPaginated($page, $perPage, $filters);
        $counts = $m->statusCounts();

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

    public function addAction()
    {
        $this->view->setLayout($this->roleLayout());
        $this->view->render('Expenses/add', [
            'page_title' => 'Add Expense',
            'types'      => (new ExpenseTypes())->allActive(),
            'trucks'     => $this->truckOptions(),
            'drivers'    => $this->driverOptions(),
            'vendors'    => $this->vendorOptions(),
            'customers'  => (new Customers())->allActive(),
            'trips'      => $this->recentTripOptions(),
            'form'       => [],
            'fb_msg'     => '',
        ]);
    }

    public function saveAction()
    {
        $this->verifyCsrf();
        if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') { Router::redirect('Expenses/add'); return; }
        $r = (new Expenses())->create($_POST, $this->currentUserId());
        if (!$r['ok']) {
            $this->view->setLayout($this->roleLayout());
            $this->view->render('Expenses/add', [
                'page_title' => 'Add Expense',
                'types'      => (new ExpenseTypes())->allActive(),
                'trucks'     => $this->truckOptions(),
                'drivers'    => $this->driverOptions(),
                'vendors'    => $this->vendorOptions(),
                'customers'  => (new Customers())->allActive(),
                'trips'      => $this->recentTripOptions(),
                '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('Expenses/view/' . $r['id']);
    }

    public function viewAction($id = 0)
    {
        $m = new Expenses();
        $e = $m->byId((int)$id);
        if (!$e) { $this->notFound('Expense'); return; }
        $this->view->setLayout($this->roleLayout());
        $this->view->render('Expenses/view', [
            'page_title' => $e['expense_no'] . ' · Expense',
            'e'          => $e,
            'history'    => $m->approvalHistory((int)$id),
        ]);
    }

    public function editAction($id = 0)
    {
        $m = new Expenses();
        $e = $m->byId((int)$id);
        if (!$e) { $this->notFound('Expense'); return; }
        if (in_array($e['status'], ['approved','paid','rejected','cancelled'], true)) {
            $_SESSION['flash_tenant_msg']  = 'Cannot edit — expense is ' . $e['status'] . '.';
            $_SESSION['flash_tenant_type'] = 'warning';
            Router::redirect('Expenses/view/' . (int)$id); return;
        }
        $this->view->setLayout($this->roleLayout());
        $this->view->render('Expenses/edit', [
            'page_title' => 'Edit · ' . $e['expense_no'],
            'e'          => $e,
            'types'      => (new ExpenseTypes())->allActive(),
            'trucks'     => $this->truckOptions(),
            'drivers'    => $this->driverOptions(),
            'vendors'    => $this->vendorOptions(),
            'customers'  => (new Customers())->allActive(),
            'trips'      => $this->recentTripOptions(),
            'form'       => $e,
            'fb_msg'     => '',
        ]);
    }

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

    /* ---- Lifecycle transitions ---- */

    public function submitAction($id = 0)  { $this->transition($id, 'submit'); }
    public function reviewAction($id = 0)  { $this->transition($id, 'review'); }
    public function approveAction($id = 0) { $this->transition($id, 'approve'); }
    public function cancelAction($id = 0)  { $this->transition($id, 'cancel'); }

    public function rejectAction($id = 0)
    {
        $this->verifyCsrf();
        if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') { Router::redirect('Expenses/view/' . (int)$id); return; }
        $reason = trim((string)($_POST['rejection_reason'] ?? ''));
        $r = (new Expenses())->reject((int)$id, $reason, $this->currentUserId(), $this->currentUserName());
        $this->flashAndRedirect($r, 'Expenses/view/' . (int)$id);
    }

    public function payAction($id = 0)
    {
        $this->verifyCsrf();
        if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') { Router::redirect('Expenses/view/' . (int)$id); return; }
        $r = (new Expenses())->pay((int)$id, $_POST, $this->currentUserId(), $this->currentUserName());
        $this->flashAndRedirect($r, 'Expenses/view/' . (int)$id);
    }

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

    /* =========================================================
     *  Helpers
     * ========================================================= */
    private function transition(int $id, string $verb): void
    {
        $this->verifyCsrf();
        if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') { Router::redirect('Expenses/view/' . (int)$id); return; }
        $m = new Expenses();
        $r = $m->$verb((int)$id, $this->currentUserId(), $this->currentUserName());
        $this->flashAndRedirect($r, 'Expenses/view/' . (int)$id);
    }

    private function currentUserName(): string
    {
        return $_SESSION['full_name'] ?? $_SESSION['username'] ?? '';
    }

    private function flashAndRedirect(array $r, string $to): void
    {
        $_SESSION['flash_tenant_msg']  = $r['msg'] ?? '';
        $_SESSION['flash_tenant_type'] = ($r['ok'] ?? false) ? 'success' : 'danger';
        Router::redirect($to);
    }

    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 truckOptions(): array
    {
        return (new DB())->mySelect(
            "SELECT c0d, reg_no, make, model FROM trucks WHERE deleted = 0 ORDER BY reg_no ASC", []
        ) ?: [];
    }

    private function driverOptions(): array
    {
        return (new DB())->mySelect(
            "SELECT c0d, full_name, employee_no FROM drivers WHERE deleted = 0 ORDER BY full_name ASC", []
        ) ?: [];
    }

    private function vendorOptions(): array
    {
        return (new DB())->mySelect(
            "SELECT c0d, vendor_name AS name FROM vendors WHERE deleted = 0 ORDER BY vendor_name ASC", []
        ) ?: [];
    }

    private function recentTripOptions(int $limit = 100): array
    {
        return (new DB())->mySelect(
            "SELECT c0d, trip_no, cargo_description FROM trips WHERE deleted = 0 ORDER BY c0d DESC LIMIT $limit", []
        ) ?: [];
    }
}
