<?php
class DriverAssignmentsController extends Controller
{
    public function indexAction($page = 1)
    {
        $page    = max(1, (int)$page);
        $perPage = defined('ROWS_PER_PAGE') ? ROWS_PER_PAGE : 20;

        $filters = [
            'driver_id' => (int)($_GET['driver_id'] ?? 0),
            'truck_id'  => (int)($_GET['truck_id']  ?? 0),
            'status'    => trim((string)($_GET['status'] ?? '')),
        ];

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

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

    public function addAction()
    {
        // Preselection support: /DriverAssignments/add?driver_id=X or ?truck_id=Y
        $preselDriver = (int)($_GET['driver_id'] ?? 0);
        $preselTruck  = (int)($_GET['truck_id']  ?? 0);

        $db = new DB();
        $drivers = $db->mySelect(
            "SELECT c0d, full_name, employee_no, status
               FROM drivers WHERE deleted = 0 AND status <> 'terminated'
           ORDER BY full_name ASC", []
        ) ?: [];
        $trucks = $db->mySelect(
            "SELECT c0d, reg_no, make, model, status
               FROM trucks WHERE deleted = 0 AND status IN ('active','maintenance')
           ORDER BY reg_no ASC", []
        ) ?: [];

        $this->view->setLayout($this->roleLayout());
        $this->view->render('DriverAssignments/add', [
            'page_title'    => 'New Assignment',
            'drivers'       => $drivers,
            'trucks'        => $trucks,
            'presel_driver' => $preselDriver,
            'presel_truck'  => $preselTruck,
            'form'          => [],
            'fb_msg'        => '',
        ]);
    }

    public function saveAction()
    {
        $this->verifyCsrf();
        if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') { Router::redirect('DriverAssignments/add'); return; }
        $m = new DriverAssignments();
        $r = $m->create($_POST, $this->currentUserId());
        if (!$r['ok']) {
            $_SESSION['flash_tenant_msg']  = $r['msg'];
            $_SESSION['flash_tenant_type'] = 'danger';
            Router::redirect('DriverAssignments/add');
            return;
        }
        $_SESSION['flash_tenant_msg']  = 'Assignment created. Any prior open assignment for this driver has been auto-closed.';
        $_SESSION['flash_tenant_type'] = 'success';
        Router::redirect('DriverAssignments/view/' . $r['id']);
    }

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

        $this->view->setLayout($this->roleLayout());
        $this->view->render('DriverAssignments/view', [
            'page_title' => 'Assignment · ' . ($a['driver_name'] ?? '?') . ' ↔ ' . ($a['truck_reg'] ?? '?'),
            'a'          => $a,
        ]);
    }

    public function endAction($id = 0)
    {
        $this->verifyCsrf();
        if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') { Router::redirect('DriverAssignments/view/' . (int)$id); return; }
        $m       = new DriverAssignments();
        $endDate = trim((string)($_POST['assigned_to'] ?? ''));
        $reason  = trim((string)($_POST['end_reason']  ?? ''));
        $m->endAssignment((int)$id, $endDate, $reason, $this->currentUserId());
        $_SESSION['flash_tenant_msg']  = 'Assignment ended.';
        $_SESSION['flash_tenant_type'] = 'success';
        Router::redirect('DriverAssignments/view/' . (int)$id);
    }

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

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