<?php
include "../../root.class.php";
$db = new db_safeguard();

/* ===== VALIDATE INPUT ===== */
$team_id = $_GET['team_id'] ?? '';

if ($team_id === '') {
    exit;
}

/* ===== FETCH ACTIVE JOBCARDS FOR TEAM ===== */
$res = $db->query(
    "jobcards",
    "
    SELECT *
    FROM jobcards
    WHERE status = 0
      AND team_assigned_id = '" . $team_id . "'
    ORDER BY jc_no DESC
    "
);

if ($res->num_rows === 0) {
    echo "<em>No active jobcards</em>";
    exit;
}

/* ===== SHOW ALL ACTIVE JOBCARDS ===== */
while ($jc = $res->fetch_assoc()) {

    /* Get latest timeline entry */
    $timeline_res = $db->query(
        "jobcard_timeline",
        "
        SELECT status
        FROM jobcard_timeline
        WHERE jobcard_id = {$jc['record_id']}
        ORDER BY record_id DESC
        LIMIT 1
        "
    );

    $timeline = $timeline_res->fetch_assoc();

    /* Skip completed jobcards */
    if ($timeline && $timeline['status'] == 1) {
        continue;
    }
    ?>
    <div class="jobcard_item">
        <strong>Jobcard #<?= (int) $jc['jc_no']; ?></strong><br>
        <?= htmlspecialchars($jc['address']); ?><br>
        <small><?= htmlspecialchars($jc['action_date']); ?></small>

        <button onclick="openDetails(<?= (int) $jc['jc_no']; ?>)">
            VIEW DETAILS
        </button>
    </div>
    <?php
}

/* If everything was skipped */
if ($res->num_rows > 0 && !isset($jc)) {
    echo "<em>No active jobcards</em>";
}
