<?php
/**
 * TruckPmSchedulesController — nested under Trucks/view. Handles the
 * assign / edit-baseline / delete actions for the per-truck PM library
 * card.
 */
class TruckPmSchedulesController extends Controller
{
    public function assignAction($truck_id = 0)
    {
        $this->verifyCsrf();
        if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') { Router::redirect('Trucks/view/' . (int)$truck_id); return; }

        $tid = (int)$truck_id;
        $tplIds = array_map('intval', $_POST['template_ids'] ?? []);
        if (empty($tplIds)) {
            $_SESSION['flash_tenant_msg']  = 'Pick at least one template to assign.';
            $_SESSION['flash_tenant_type'] = 'danger';
            Router::redirect('Trucks/view/' . $tid); return;
        }

        $m = new TruckPmSchedules();
        $ok = 0;
        foreach ($tplIds as $tplId) {
            $r = $m->assign($tid, $tplId, [
                'baseline_km'   => $_POST['baseline_km']   ?? '',
                'baseline_date' => $_POST['baseline_date'] ?? '',
                'notes'         => $_POST['notes']         ?? '',
            ], $this->currentUserId());
            if ($r['ok']) $ok++;
        }
        $_SESSION['flash_tenant_msg']  = "{$ok} schedule(s) assigned.";
        $_SESSION['flash_tenant_type'] = 'success';
        Router::redirect('Trucks/view/' . $tid);
    }

    public function updateAction($id = 0)
    {
        $this->verifyCsrf();
        if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') { Router::redirect('Trucks'); return; }
        $m = new TruckPmSchedules();
        $s = $m->byId((int)$id);
        if (!$s) { Router::redirect('Trucks'); return; }
        $km   = isset($_POST['baseline_km'])   && $_POST['baseline_km']   !== '' ? (int)$_POST['baseline_km']   : (int)$s['baseline_km'];
        $date = isset($_POST['baseline_date']) && $_POST['baseline_date'] !== '' ? (string)$_POST['baseline_date'] : (string)$s['baseline_date'];
        $m->updateBaseline((int)$id, $km, $date, $this->currentUserId());
        $_SESSION['flash_tenant_msg']  = 'Baseline updated · next-due recomputed.';
        $_SESSION['flash_tenant_type'] = 'success';
        Router::redirect('Trucks/view/' . (int)$s['truck_id']);
    }

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