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

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

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

    public function addAction()
    {
        $this->view->setLayout($this->roleLayout());
        $this->view->render('FuelEntries/add', [
            'page_title' => 'Record Fuel Entry',
            'trucks'     => $this->truckOptions(),
            'drivers'    => $this->driverOptions(),
            'trips'      => $this->recentTripOptions(),
            'form'       => [],
            'fb_msg'     => '',
        ]);
    }

    public function saveAction()
    {
        $this->verifyCsrf();
        if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') { Router::redirect('FuelEntries/add'); return; }
        $r = (new FuelEntries())->create($_POST, $this->currentUserId(), $this->currentUserName());
        if (!$r['ok']) {
            $this->view->setLayout($this->roleLayout());
            $this->view->render('FuelEntries/add', [
                'page_title' => 'Record Fuel Entry',
                'trucks'     => $this->truckOptions(),
                'drivers'    => $this->driverOptions(),
                '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('FuelEntries/view/' . $r['id']);
    }

    public function viewAction($id = 0)
    {
        $e = (new FuelEntries())->byId((int)$id);
        if (!$e) { $this->notFound('Fuel entry'); return; }
        $this->view->setLayout($this->roleLayout());
        $this->view->render('FuelEntries/view', [
            'page_title' => $e['entry_no'] . ' · Fuel Entry',
            'e'          => $e,
        ]);
    }

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

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

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

    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, current_odometer, fuel_tank_liters
               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 recentTripOptions(int $limit = 100): array
    {
        return (new DB())->mySelect(
            "SELECT c0d, trip_no, cargo_description, truck_id, driver_id
               FROM trips WHERE deleted = 0
           ORDER BY c0d DESC LIMIT $limit", []
        ) ?: [];
    }
}
