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

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

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

    public function addAction()
    {
        $this->view->setLayout($this->roleLayout());
        $this->view->render('TripRequests/add', [
            'page_title' => 'New Trip Request',
            'customers'  => (new Customers())->allActive(),
            'routes'     => (new Routes())->allActive(),
            'form'       => [],
            'fb_msg'     => '',
        ]);
    }

    public function saveAction()
    {
        $this->verifyCsrf();
        if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') { Router::redirect('TripRequests/add'); return; }
        $m = new TripRequests();
        $r = $m->create($_POST, $this->currentUserId());
        if (!$r['ok']) {
            $this->view->setLayout($this->roleLayout());
            $this->view->render('TripRequests/add', [
                'page_title' => 'New Trip Request',
                'customers'  => (new Customers())->allActive(),
                'routes'     => (new Routes())->allActive(),
                'form'       => $_POST,
                'fb_msg'     => '<div class="alert alert-danger">' . htmlspecialchars($r['msg']) . '</div>',
            ]);
            return;
        }
        $_SESSION['flash_tenant_msg']  = 'Trip request created.';
        $_SESSION['flash_tenant_type'] = 'success';
        Router::redirect('TripRequests/view/' . $r['id']);
    }

    public function viewAction($id = 0)
    {
        $m = new TripRequests();
        $tr = $m->byId((int)$id);
        if (!$tr) { $this->notFound('Trip Request'); return; }

        $ci   = new TripRequestCargoItems();
        $stops= (new TripStops())->forRequest((int)$id);

        $this->view->setLayout($this->roleLayout());
        $this->view->render('TripRequests/view', [
            'page_title'  => $tr['request_no'] . ' · Trip Request',
            'tr'          => $tr,
            'cargo_items' => $ci->forRequest((int)$id),
            'cargo_sums'  => $ci->sumsForRequest((int)$id),
            'stops'       => $stops,
        ]);
    }

    public function editAction($id = 0)
    {
        $m = new TripRequests();
        $tr = $m->byId((int)$id);
        if (!$tr) { $this->notFound('Trip Request'); return; }
        if (in_array($tr['status'], ['dispatched','rejected','cancelled'], true)) {
            $_SESSION['flash_tenant_msg']  = 'This request is ' . $tr['status'] . ' — no further edits allowed.';
            $_SESSION['flash_tenant_type'] = 'warning';
            Router::redirect('TripRequests/view/' . (int)$id);
            return;
        }
        $this->view->setLayout($this->roleLayout());
        $this->view->render('TripRequests/edit', [
            'page_title' => 'Edit · ' . $tr['request_no'],
            'tr'         => $tr,
            'customers'  => (new Customers())->allActive(),
            'routes'     => (new Routes())->allActive(),
            'form'       => $tr,
            'fb_msg'     => '',
        ]);
    }

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

    /* ---- Status transitions ---- */

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

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

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

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

    /* ---- Cargo items sub-CRUD ---- */
    public function addCargoItemAction($req_id = 0)
    {
        $this->verifyCsrf();
        if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') { Router::redirect('TripRequests/view/' . (int)$req_id); return; }
        $r = (new TripRequestCargoItems())->create((int)$req_id, $_POST, $this->currentUserId());
        $_SESSION['flash_tenant_msg']  = $r['msg'];
        $_SESSION['flash_tenant_type'] = $r['ok'] ? 'success' : 'danger';
        Router::redirect('TripRequests/view/' . (int)$req_id);
    }

    public function deleteCargoItemAction($item_id = 0)
    {
        $this->verifyCsrf();
        if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') { Router::redirect('TripRequests'); return; }
        $item = (new TripRequestCargoItems())->byId((int)$item_id);
        (new TripRequestCargoItems())->softDelete((int)$item_id, $this->currentUserId());
        $_SESSION['flash_tenant_msg']  = 'Cargo item removed.';
        $_SESSION['flash_tenant_type'] = 'success';
        Router::redirect('TripRequests/view/' . (int)($item['trip_request_id'] ?? 0));
    }

    /* ---- Stops sub-CRUD (planning stops on a trip request) ---- */
    public function addStopAction($req_id = 0)
    {
        $this->verifyCsrf();
        if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') { Router::redirect('TripRequests/view/' . (int)$req_id); return; }
        $r = (new TripStops())->create((int)$req_id, 0, $_POST, $this->currentUserId());
        $_SESSION['flash_tenant_msg']  = $r['msg'];
        $_SESSION['flash_tenant_type'] = $r['ok'] ? 'success' : 'danger';
        Router::redirect('TripRequests/view/' . (int)$req_id);
    }

    public function deleteStopAction($stop_id = 0)
    {
        $this->verifyCsrf();
        if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') { Router::redirect('TripRequests'); return; }
        $stop = (new TripStops())->byId((int)$stop_id);
        (new TripStops())->softDelete((int)$stop_id, $this->currentUserId());
        $_SESSION['flash_tenant_msg']  = 'Stop removed.';
        $_SESSION['flash_tenant_type'] = 'success';
        Router::redirect('TripRequests/view/' . (int)($stop['trip_request_id'] ?? 0));
    }

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

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