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

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

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

    public function addAction()
    {
        $this->view->setLayout($this->roleLayout());
        $this->view->render('WorkRequests/add', [
            'page_title' => 'New Work Request',
            'trucks'     => $this->truckOptions(),
            'drivers'    => $this->driverOptions(),
            'form'       => [],
            'fb_msg'     => '',
        ]);
    }

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

    public function viewAction($id = 0)
    {
        $m = new WorkRequests();
        $w = $m->byId((int)$id);
        if (!$w) { $this->notFound('Work request'); return; }
        $this->view->setLayout($this->roleLayout());
        $this->view->render('WorkRequests/view', [
            'page_title' => $w['wr_no'] . ' · Work Request',
            'w'          => $w,
            'items'      => (new WorkRequestItems())->forRequest((int)$id),
            'history'    => $m->transitionHistory((int)$id),
            'vendors'    => (new Vendors())->allActive(),
        ]);
    }

    public function editAction($id = 0)
    {
        $w = (new WorkRequests())->byId((int)$id);
        if (!$w) { $this->notFound('Work request'); return; }
        if (in_array($w['status'], ['wo_created','completed','rejected','cancelled'], true)) {
            $_SESSION['flash_tenant_msg']  = 'Cannot edit — WR is ' . $w['status'] . '.';
            $_SESSION['flash_tenant_type'] = 'warning';
            Router::redirect('WorkRequests/view/' . (int)$id); return;
        }
        $this->view->setLayout($this->roleLayout());
        $this->view->render('WorkRequests/edit', [
            'page_title' => 'Edit · ' . $w['wr_no'],
            'w'          => $w,
            'trucks'     => $this->truckOptions(),
            'drivers'    => $this->driverOptions(),
            'form'       => $w,
            'fb_msg'     => '',
        ]);
    }

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

    /* ---- Lifecycle transitions ---- */
    public function submitAction($id = 0)  { $this->plain($id, fn($m, $id, $uid, $nm) => $m->submit($id, $uid, $nm)); }
    public function cancelAction($id = 0)
    {
        $this->verifyCsrf();
        if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') { Router::redirect('WorkRequests/view/' . (int)$id); return; }
        $reason = trim((string)($_POST['cancel_reason'] ?? ''));
        $r = (new WorkRequests())->cancel((int)$id, $reason, $this->currentUserId(), $this->currentUserName());
        $this->flashAndRedirect($r, 'WorkRequests/view/' . (int)$id);
    }
    public function rejectAction($id = 0)
    {
        $this->verifyCsrf();
        if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') { Router::redirect('WorkRequests/view/' . (int)$id); return; }
        $reason = trim((string)($_POST['reject_reason'] ?? ''));
        $r = (new WorkRequests())->reject((int)$id, $reason, $this->currentUserId(), $this->currentUserName());
        $this->flashAndRedirect($r, 'WorkRequests/view/' . (int)$id);
    }
    public function approveAction($id = 0)
    {
        $this->verifyCsrf();
        if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') { Router::redirect('WorkRequests/view/' . (int)$id); return; }
        $amt = isset($_POST['approved_amount']) && $_POST['approved_amount'] !== ''
             ? (float)str_replace(',', '', (string)$_POST['approved_amount'])
             : null;
        $notes = trim((string)($_POST['approval_notes'] ?? ''));
        $r = (new WorkRequests())->approve((int)$id, $amt, $notes, $this->currentUserId(), $this->currentUserName());
        $this->flashAndRedirect($r, 'WorkRequests/view/' . (int)$id);
    }
    public function startSourcingAction($id = 0) { $this->plain($id, fn($m, $id, $uid, $nm) => $m->startSourcing($id, $uid, $nm)); }
    public function markReadyAction($id = 0)
    {
        $this->verifyCsrf();
        if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') { Router::redirect('WorkRequests/view/' . (int)$id); return; }
        $r = (new WorkRequests())->markReady((int)$id, $_POST, $this->currentUserId(), $this->currentUserName());
        $this->flashAndRedirect($r, 'WorkRequests/view/' . (int)$id);
    }
    public function convertToWoAction($id = 0)
    {
        $this->verifyCsrf();
        if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') { Router::redirect('WorkRequests/view/' . (int)$id); return; }
        $r = (new WorkRequests())->convertToWo((int)$id, $this->currentUserId(), $this->currentUserName());
        if ($r['ok'] && !empty($r['wo_id'])) {
            $_SESSION['flash_tenant_msg']  = $r['msg'];
            $_SESSION['flash_tenant_type'] = 'success';
            Router::redirect('WorkOrders/view/' . (int)$r['wo_id']);
            return;
        }
        $this->flashAndRedirect($r, 'WorkRequests/view/' . (int)$id);
    }

    /* ---- Items sub-CRUD ---- */
    public function addItemAction($wr_id = 0)
    {
        $this->verifyCsrf();
        if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') { Router::redirect('WorkRequests/view/' . (int)$wr_id); return; }
        $r = (new WorkRequestItems())->create((int)$wr_id, $_POST, $this->currentUserId());
        $this->flashAndRedirect($r, 'WorkRequests/view/' . (int)$wr_id);
    }
    public function deleteItemAction($item_id = 0)
    {
        $this->verifyCsrf();
        if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') { Router::redirect('WorkRequests'); return; }
        $item = (new WorkRequestItems())->byId((int)$item_id);
        $r = (new WorkRequestItems())->softDelete((int)$item_id, $this->currentUserId());
        $this->flashAndRedirect($r, 'WorkRequests/view/' . (int)($item['work_request_id'] ?? 0));
    }

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

    /* ---- Helpers ---- */
    private function plain(int $id, callable $callable): void
    {
        $this->verifyCsrf();
        if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') { Router::redirect('WorkRequests/view/' . (int)$id); return; }
        $r = $callable(new WorkRequests(), $id, $this->currentUserId(), $this->currentUserName());
        $this->flashAndRedirect($r, 'WorkRequests/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, current_odometer 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", []) ?: [];
    }
}
