<?php
// ─── POST /api/pumps/timeline-add.php ───────────────────────────────────
define('ROOT', dirname(__DIR__, 2));
require_once ROOT . '/core/DB.php';
require_once ROOT . '/core/Response.php';
require_once ROOT . '/core/Auth.php';

$user = Auth::require();
$db   = DB::get();

$jobcard_no = trim($_POST['jobcard_no'] ?? '');
$type       = strtoupper(trim($_POST['type'] ?? ''));
$meters     = (int) ($_POST['meters'] ?? 0);
$date_time  = str_replace('T', ' ', trim($_POST['date_time'] ?? ''));

$valid = ['DEPARTURE','ARRIVED','INSTALLING','START','PAUSE','RESUME','STOP','COMPLETE','OTHER'];
if (!$jobcard_no) Response::error('jobcard_no is required.');
if (!in_array($type, $valid)) Response::error("Unknown type: $type");
if (!$date_time) $date_time = date('Y-m-d H:i');

$db->run(
    "INSERT INTO pump_timeline (jobcard_no, user_id, type, meters, status)
     VALUES (?, ?, ?, ?, 0)",
    [$jobcard_no, (int) $user['user_id'], $type, $meters]
);

// Also update jc_current_status on install or repair
$db->run("UPDATE pump_installation SET jc_current_status = ? WHERE jobcard_no = ?", [$type, $jobcard_no]);
$db->run("UPDATE pump_repair        SET jc_current_status = ? WHERE jobcard_no = ?", [$type, $jobcard_no]);

Response::ok([
    'record_id'  => (int) $db->lastId(),
    'jobcard_no' => $jobcard_no,
    'type'       => $type,
    'meters'     => $meters,
    'date_time'  => $date_time,
    'username'   => $user['username'],
], 'Timeline entry added.');