<?php
// ─── GET /api/jobcards/get.php?id=X ─────────────────────────────────────
define('ROOT', dirname(__DIR__, 2));
require_once ROOT . '/core/DB.php';
require_once ROOT . '/core/Response.php';
require_once ROOT . '/core/Auth.php';

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

$id = (int) ($_GET['id'] ?? 0);
if (!$id) Response::error('id is required.');

// Main jobcard row
$jc = $db->row(
    "SELECT j.*,
            t.name  AS team_name,
            u.username AS created_by
     FROM   jobcards j
     LEFT JOIN teams t ON t.record_id = j.team_assigned_id
     LEFT JOIN users u ON u.record_id = j.user_id
     WHERE  j.record_id = ?",
    [$id]
);
if (!$jc) Response::error('Jobcard not found.', 404);

// Timeline entries
$timeline = $db->rows(
    "SELECT jt.*, u.username
     FROM   jobcard_timeline jt
     LEFT JOIN users u ON u.record_id = jt.user_id
     WHERE  jt.jobcard_id = ?
     ORDER BY jt.record_id ASC",
    [$id]
);

// Notes
$notes = $db->rows(
    "SELECT * FROM notes WHERE jobcard_id = ? ORDER BY record_id DESC",
    [$id]
);

// Payments
$payments = $db->rows(
    "SELECT jp.*, u.username
     FROM   jobcard_payments jp
     LEFT JOIN users u ON u.record_id = jp.user_id
     WHERE  jp.jobcard_id = ?
     ORDER BY jp.date_time DESC",
    [$id]
);

// Compute meter totals from timeline
$totals = ['rieming' => 0, 'drilling' => 0, 'casing' => 0, 'blasting' => 0, 'rods' => 0];
foreach ($timeline as $t) {
    $type = strtoupper($t['type']);
    $m    = (float) ($t['meters'] ?? 0);
    if (in_array($type, ['RIEMING_STOP','RIEM_STOP','RIEMING_PAUSED','REIMING_STOP']))   $totals['rieming']  += $m;
    if (in_array($type, ['DRILLING_STOP','DRILLING_PAUSE']))                             $totals['drilling'] += $m;
    if (in_array($type, ['CASING_STOP','CASING_PAUSE']))                                 $totals['casing']   += $m;
    if (in_array($type, ['BLASTING_START','BLASTING_STOP','BLASTING_PAUSE']))            $totals['blasting'] += $m;
    if (in_array($type, ['RODS_STOP']))                                                  $totals['rods']     += $m;
}
$totals['total'] = array_sum($totals);

Response::ok([
    'jobcard'  => $jc,
    'timeline' => $timeline,
    'notes'    => $notes,
    'payments' => $payments,
    'totals'   => $totals,
]);