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

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

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

    public function addAction()
    {
        $this->view->setLayout($this->roleLayout());
        $this->view->render('WorkOrders/add', [
            'page_title' => 'New Work Order',
            'trucks'     => $this->truckOptions(),
            'vendors'    => (new Vendors())->allActive(),
            'form'       => [],
            'fb_msg'     => '',
        ]);
    }

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

    public function viewAction($id = 0)
    {
        $m = new WorkOrders();
        $w = $m->byId((int)$id);
        if (!$w) { $this->notFound('Work order'); return; }
        $this->view->setLayout($this->roleLayout());
        $this->view->render('WorkOrders/view', [
            'page_title' => $w['wo_no'] . ' · Work Order',
            'w'          => $w,
            'parts'      => $m->partsForWo((int)$id),
        ]);
    }

    public function editAction($id = 0)
    {
        $w = (new WorkOrders())->byId((int)$id);
        if (!$w) { $this->notFound('Work order'); return; }
        if (in_array($w['status'], ['closed','cancelled'], true)) {
            $_SESSION['flash_tenant_msg']  = 'Cannot edit — WO is ' . $w['status'] . '.';
            $_SESSION['flash_tenant_type'] = 'warning';
            Router::redirect('WorkOrders/view/' . (int)$id); return;
        }
        $this->view->setLayout($this->roleLayout());
        $this->view->render('WorkOrders/edit', [
            'page_title' => 'Edit · ' . $w['wo_no'],
            'w'          => $w,
            'trucks'     => $this->truckOptions(),
            'vendors'    => (new Vendors())->allActive(),
            'form'       => $w,
            'fb_msg'     => '',
        ]);
    }

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

    /* ---- Lifecycle ---- */
    public function startAction($id = 0)    { $this->simple($id, 'start',    fn($m, $id, $uid) => $m->start($id, $uid)); }
    public function completeAction($id = 0) { $this->simple($id, 'complete', fn($m, $id, $uid) => $m->complete($id, $uid)); }
    public function cancelAction($id = 0)
    {
        $this->verifyCsrf();
        if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') { Router::redirect('WorkOrders/view/' . (int)$id); return; }
        $reason = trim((string)($_POST['cancel_reason'] ?? ''));
        $r = (new WorkOrders())->cancel((int)$id, $reason, $this->currentUserId());
        $this->flashAndRedirect($r, 'WorkOrders/view/' . (int)$id);
    }
    public function closeAction($id = 0)
    {
        $this->verifyCsrf();
        if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') { Router::redirect('WorkOrders/view/' . (int)$id); return; }
        $r = (new WorkOrders())->close((int)$id, $_POST, $this->currentUserId(), $this->currentUserName());
        $this->flashAndRedirect($r, 'WorkOrders/view/' . (int)$id);
    }

    /* ---- Parts sub-CRUD ---- */
    public function addPartAction($wo_id = 0)
    {
        $this->verifyCsrf();
        if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') { Router::redirect('WorkOrders/view/' . (int)$wo_id); return; }
        $r = (new WorkOrders())->addPart((int)$wo_id, $_POST, $this->currentUserId());
        $this->flashAndRedirect($r, 'WorkOrders/view/' . (int)$wo_id);
    }

    public function deletePartAction($part_id = 0)
    {
        $this->verifyCsrf();
        if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') { Router::redirect('WorkOrders'); return; }
        $db = new DB();
        $rs = $db->mySelect("SELECT work_order_id FROM work_order_parts WHERE c0d = :id", [':id' => (int)$part_id]);
        $woId = (int)($rs[0]['work_order_id'] ?? 0);
        $r = (new WorkOrders())->deletePart((int)$part_id, $this->currentUserId());
        $this->flashAndRedirect($r, 'WorkOrders/view/' . $woId);
    }

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

    /* ---- Helpers ---- */
    private function simple(int $id, string $verb, callable $callable): void
    {
        $this->verifyCsrf();
        if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') { Router::redirect('WorkOrders/view/' . (int)$id); return; }
        $m = new WorkOrders();
        $r = $callable($m, $id, $this->currentUserId());
        $this->flashAndRedirect($r, 'WorkOrders/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, status FROM trucks WHERE deleted = 0 ORDER BY reg_no ASC", []
        ) ?: [];
    }
}
