<?php
class DriversController 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'] ?? '')),
            'licence_expiring_days' => (int)($_GET['licence_expiring_days'] ?? 0),
        ];

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

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

    public function addAction()
    {
        $this->view->setLayout($this->roleLayout());
        $this->view->render('Drivers/add', [
            'page_title' => 'Add Driver',
            'form'       => [],
            'fb_msg'     => '',
        ]);
    }

    public function saveAction()
    {
        $this->verifyCsrf();
        if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') { Router::redirect('Drivers/add'); return; }

        $body = $_POST;

        // Optional portrait upload — save first, stash the URL onto the payload
        // so Drivers::create() persists it in the same insert.
        if (!empty($_FILES['photo']['name']) && $_FILES['photo']['error'] === UPLOAD_ERR_OK) {
            $up = $this->handleFileUpload($_FILES['photo'], 'driver_photo');
            if (!$up['ok']) {
                $this->view->setLayout($this->roleLayout());
                $this->view->render('Drivers/add', [
                    'page_title' => 'Add Driver',
                    'form'       => $body,
                    'fb_msg'     => '<div class="alert alert-danger">' . htmlspecialchars($up['msg']) . '</div>',
                ]);
                return;
            }
            $body['photo_url'] = $up['url'];
        }

        $m = new Drivers();
        $r = $m->create($body, $this->currentUserId());
        if (!$r['ok']) {
            $this->view->setLayout($this->roleLayout());
            $this->view->render('Drivers/add', [
                'page_title' => 'Add Driver',
                'form'       => $body,
                'fb_msg'     => '<div class="alert alert-danger">' . htmlspecialchars($r['msg']) . '</div>',
            ]);
            return;
        }
        $_SESSION['flash_tenant_msg']  = 'Driver added: ' . htmlspecialchars($body['full_name'] ?? '');
        $_SESSION['flash_tenant_type'] = 'success';
        Router::redirect('Drivers/view/' . $r['id']);
    }

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

        $dm  = new DriverDocs();
        $dtm = new DriverDocTypes();

        $this->view->setLayout($this->roleLayout());
        $this->view->render('Drivers/view', [
            'page_title' => $d['full_name'] . ' · Driver',
            'd'          => $d,
            'docs'       => $dm->forDriver((int)$id),
            'doc_types'  => $dtm->allActive(),
        ]);
    }

    public function editAction($id = 0)
    {
        $m = new Drivers();
        $d = $m->byId((int)$id);
        if (!$d) { $this->notFound('Driver'); return; }

        $this->view->setLayout($this->roleLayout());
        $this->view->render('Drivers/edit', [
            'page_title' => 'Edit · ' . $d['full_name'],
            'd'          => $d,
            'form'       => $d,
            'fb_msg'     => '',
        ]);
    }

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

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

    public function uploadDocAction($driver_id = 0)
    {
        $this->verifyCsrf();
        if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') { Router::redirect('Drivers/view/' . (int)$driver_id); return; }
        $driverId = (int)$driver_id;
        $dm = new Drivers();
        if (!$dm->byId($driverId)) { $this->notFound('Driver'); return; }

        $fileUrl = ''; $fileName = ''; $fileSize = 0;
        if (!empty($_FILES['doc_file']['name']) && $_FILES['doc_file']['error'] === UPLOAD_ERR_OK) {
            $up = $this->handleFileUpload($_FILES['doc_file'], 'driver_' . $driverId);
            if (!$up['ok']) {
                $_SESSION['flash_tenant_msg']  = $up['msg'];
                $_SESSION['flash_tenant_type'] = 'danger';
                Router::redirect('Drivers/view/' . $driverId); return;
            }
            $fileUrl  = $up['url'];
            $fileName = $up['orig_name'];
            $fileSize = $up['size'];
        }

        $docs = new DriverDocs();
        $r    = $docs->create(array_merge($_POST, [
            'driver_id' => $driverId,
            'file_url'  => $fileUrl,
            'file_name' => $fileName,
            'file_size' => $fileSize,
        ]), $this->currentUserId());

        $_SESSION['flash_tenant_msg']  = $r['msg'];
        $_SESSION['flash_tenant_type'] = $r['ok'] ? 'success' : 'danger';
        Router::redirect('Drivers/view/' . $driverId);
    }

    public function deleteDocAction($doc_id = 0)
    {
        $this->verifyCsrf();
        if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') { Router::redirect('Drivers'); return; }
        $docs = new DriverDocs();
        $doc  = $docs->byId((int)$doc_id);
        if (!$doc) { $this->notFound('Document'); return; }
        $docs->softDelete((int)$doc_id, $this->currentUserId());
        $_SESSION['flash_tenant_msg']  = 'Document removed.';
        $_SESSION['flash_tenant_type'] = 'success';
        Router::redirect('Drivers/view/' . (int)$doc['driver_id']);
    }

    /**
     * Renders the Pacific staff-ID card as a PDF.
     *   /Drivers/staffId/12          → single-card PDF (2 pages: front, back)
     *   /Drivers/staffId/12?sheet=1  → A4 sheet layout (2 × 5 grid) for laser printing
     *   ?dl=1 forces attachment download rather than inline preview.
     */
    public function staffIdAction($id = 0)
    {
        $m = new Drivers();
        $d = $m->byId((int)$id);
        if (!$d) { $this->notFound('Driver'); return; }

        if (!class_exists('FPDF')) require_once ROOT . '/core/FPDF.php';

        $pdf = new PacificStaffIdPdf();
        $pdf->render($d);

        if (ob_get_length()) ob_clean();
        $filename = 'StaffID-' . preg_replace('/[^A-Za-z0-9_-]/', '_', ($d['employee_no'] ?: 'driver-' . $id)) . '.pdf';
        $mode     = !empty($_GET['dl']) ? 'D' : 'I';
        $pdf->Output($mode, $filename);
        exit();
    }

    /* --------------- helpers --------------- */

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

    /**
     * Same whitelist + MIME sniff + random filename pattern as TrucksController.
     * (Kept in-controller for now; extract to a shared FileUploader helper once
     * a third module needs it — Iter 2 Fuel Officer receipt upload most likely.)
     */
    private function handleFileUpload(array $file, string $scope): array
    {
        $maxBytes = defined('MAX_UPLOAD_SIZE') ? MAX_UPLOAD_SIZE : (8 * 1024 * 1024);
        if ($file['size'] > $maxBytes) {
            return ['ok' => false, 'msg' => 'File exceeds max size of ' . formatFileSize($maxBytes) . '.'];
        }
        $allowedExt  = ['pdf','jpg','jpeg','png','webp','doc','docx'];
        $allowedMime = [
            'application/pdf',
            'image/jpeg','image/png','image/webp',
            'application/msword',
            'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        ];
        $origName = basename((string)$file['name']);
        $ext      = strtolower(pathinfo($origName, PATHINFO_EXTENSION));
        if (!in_array($ext, $allowedExt, true)) {
            return ['ok' => false, 'msg' => 'File type .' . $ext . ' is not allowed.'];
        }
        $finfo = finfo_open(FILEINFO_MIME_TYPE);
        $mime  = $finfo ? finfo_file($finfo, $file['tmp_name']) : '';
        if ($finfo) finfo_close($finfo);
        if ($mime && !in_array($mime, $allowedMime, true)) {
            return ['ok' => false, 'msg' => 'File content does not match expected type.'];
        }

        $subdir  = preg_replace('/[^a-z0-9_]/', '_', strtolower($scope));
        $destDir = UPLOAD_PATH . $subdir;
        if (!is_dir($destDir)) @mkdir($destDir, 0775, true);

        $rand     = bin2hex(random_bytes(8));
        $newName  = date('Ymd_His') . '_' . $rand . '.' . $ext;
        $destPath = $destDir . DS . $newName;
        if (!move_uploaded_file($file['tmp_name'], $destPath)) {
            return ['ok' => false, 'msg' => 'Server could not save the uploaded file.'];
        }
        return [
            'ok'        => true,
            'url'       => UPLOAD_URL . $subdir . '/' . $newName,
            'orig_name' => $origName,
            'size'      => (int)$file['size'],
        ];
    }
}
