<?php
include "../../root.class.php";

$html = new html();
$html->add_styles_page();
$db = new db_safeguard();

/* ================== CONFIG ================== */
$WARNING_HOURS = 72;
$STALL_HOURS = 120;

/* ================== DATA ================== */
$all_jobcards = $db->query(
    "jobcards",
    "SELECT * 
     FROM jobcards 
     WHERE status = 0 
     ORDER BY jc_no DESC 
     LIMIT 10"
);
?>

<h1>CURRENT ACTIVE JOBCARDS</h1>

<div style="display:flex; flex-wrap:wrap; justify-content:space-around;">

    <?php
    while ($jobcards = $all_jobcards->fetch_assoc()) {

        $jobcard_id = (int) $jobcards['record_id'];
        $jc_no = (int) $jobcards['jc_no'];
        $team_id = (int) $jobcards['team_assigned_id'];

        /* ======================================================
           SKIP COMPLETED JOBCARDS
        ====================================================== */
        $complete_check = $db->query(
            "jobcard_timeline",
            "SELECT 1 
         FROM jobcard_timeline 
         WHERE jobcard_id = $jobcard_id 
           AND type = 'COMPLETE'
         LIMIT 1"
        );

        if ($complete_check && $complete_check->num_rows > 0) {
            continue;
        }

        /* ======================================================
           TEAM
        ====================================================== */
        $team_name = null;
        $team_res = $db->query(
            "teams",
            "SELECT name 
         FROM teams 
         WHERE record_id = $team_id 
           AND status = 'ACTIVE'"
        );

        if ($team_res && $team_res->num_rows > 0) {
            $team_name = $team_res->fetch_assoc()['name'];
        }

        /* ======================================================
           LAST ACTION
        ====================================================== */
        $last_action = null;
        $last_action_res = $db->query(
            "jobcard_timeline",
            "SELECT type, date_time 
         FROM jobcard_timeline 
         WHERE jobcard_id = $jobcard_id 
         ORDER BY record_id DESC 
         LIMIT 1"
        );

        if ($last_action_res && $last_action_res->num_rows > 0) {
            $last_action = $last_action_res->fetch_assoc();
        }

        /* ======================================================
           STATE DETECTION
        ====================================================== */
        $jobcard_state = 'normal';
        $hours_since_last_action = null;

        if ($last_action && !empty($last_action['date_time'])) {
            $last_time = strtotime($last_action['date_time']);
            $now = time();

            $hours_since_last_action = ($now - $last_time) / 3600;

            if ($hours_since_last_action >= $STALL_HOURS) {
                $jobcard_state = 'stalled';
            } elseif ($hours_since_last_action >= $WARNING_HOURS) {
                $jobcard_state = 'warning';
            }
        }
        ?>
        <div class="searched_data <?= $jobcard_state ?>" style="margin:1vw; width:80%;">

            <?php if ($jobcard_state !== 'normal') { ?>
                <div class="state_badge <?= $jobcard_state ?>">
                    <?= strtoupper($jobcard_state) ?>
                    <?php if ($hours_since_last_action !== null) { ?>
                        (<?= floor($hours_since_last_action) ?>h)
                    <?php } ?>
                </div>
            <?php } ?>

            <div class="group_div">
                <label class="label">JOBCARD ID</label>
                <input class="inputs" readonly value="<?= $jc_no ?>">
            </div>

            <div class="group_div">
                <label class="label">DATE CREATED</label>
                <input class="inputs" readonly value="<?= $jobcards['date_created'] ?>">
            </div>

            <div class="group_div">
                <label class="label">CONTACT NUMBER</label>
                <input class="inputs" readonly value="<?= $jobcards['contact_number'] ?>">
            </div>

            <div class="group_div">
                <label class="label">ADDRESS</label>
                <textarea class="inputs" readonly><?= $jobcards['address'] ?></textarea>
            </div>

            <?php if ($team_name) { ?>
                <div class="group_div">
                    <label class="label">TEAM</label>
                    <input class="inputs" readonly value="<?= $team_name ?>">
                </div>
            <?php } ?>

            <?php if ($last_action) { ?>
                <div class="group_div">
                    <label class="label">LAST ACTION</label>
                    <input class="inputs" readonly value="<?= $last_action['type'] ?>">
                </div>

                <div class="group_div">
                    <label class="label">LAST ACTION TIME</label>
                    <input class="inputs" readonly value="<?= $last_action['date_time'] ?>">
                </div>
            <?php } ?>

            <div class="group_div">
                <label class="label">STATUS</label>
                <input class="inputs" readonly value="ACTIVE">
            </div>

            <div>
                <button class="submit_btn" onclick="openDetails(<?= $jc_no ?>)">
                    MORE DETAILS
                </button>
            </div>

            <div>
                <button class="submit_btn" onclick="completeJobcard(<?= $jobcard_id ?>)">
                    COMPLETE JOBCARD
                </button>
            </div>
        </div>
    <?php } ?>
</div>

<!-- ================= MODAL ================= -->

<div id="detailed_view" class="detailed_view" style="display:none;">
    <span class="close-btn" onclick="closeDetails()">&times;</span>

    <div id="detailed_view_content" class="detailed_view_content">
        Loading...
    </div>

    <div id="meters_div" class="meters_div"></div>

    <div id="last_action_div" class="last_action_div"></div>
</div>

<!-- ================= SCRIPTS ================= -->

<script>
    function openDetails(jc_no) {
        document.getElementById("detailed_view").style.display = "flex";

        fetch("jobcard_details.php?jc_no=" + jc_no)
            .then(res => res.text())
            .then(data => {
                document.getElementById("detailed_view_content").innerHTML = data;
            });

        fetch("jobcard_meters.php?jc_no=" + jc_no)
            .then(res => res.text())
            .then(data => {
                document.getElementById("meters_div").innerHTML = data;
            });

        fetch("jobcard_last_action.php?jc_no=" + jc_no)
            .then(res => res.text())
            .then(data => {
                document.getElementById("last_action_div").innerHTML = data;
            });
    }

    function completeJobcard(jobcard_id) {

        if (!confirm("Are you sure you want to COMPLETE this jobcard?")) {
            return;
        }

        fetch("complete_jobcard.php", {
            method: "POST",
            headers: {
                "Content-Type": "application/x-www-form-urlencoded"
            },
            body: "jobcard_id=" + jobcard_id
        })
            .then(res => res.json())
            .then(data => {
                if (data.status === "success") {
                    alert("Jobcard completed successfully.");
                    location.reload();
                } else {
                    alert("Error: " + data.message);
                }
            })
            .catch(err => {
                alert("Server error.");
                console.error(err);
            });
    }

    function closeDetails() {
        document.getElementById("detailed_view").style.display = "none";
    }
</script>

<!-- ================= STYLES ================= -->

<style>
    /* ===== GLOBAL ===== */
    body {
        font-family: "Segoe UI", Roboto, Arial, sans-serif;
        background: #f8fafc;
        color: #0f172a;
    }

    h1 {
        text-align: center;
        margin: 2vw 0;
        color: #1e3a8a;
    }

    /* ===== JOB CARD ===== */
    .searched_data {
        background: #ffffff;
        border-radius: 14px;
        padding: 20px;
        max-width: 800px;
        box-shadow: 0 10px 30px rgba(15, 23, 42, 0.12);
        margin-bottom: 2vw;
        transition: transform 0.2s ease, box-shadow 0.2s ease;
        border-top: 5px solid #2563eb;
    }

    .searched_data:hover {
        transform: translateY(-4px);
        box-shadow: 0 16px 40px rgba(15, 23, 42, 0.18);
    }

    /* ===== FORM GROUP ===== */
    .group_div {
        display: flex;
        flex-direction: column;
        margin-bottom: 12px;
    }

    .label {
        font-size: 0.75rem;
        font-weight: 700;
        color: #1f2933;
        margin-bottom: 4px;
        text-transform: uppercase;
        letter-spacing: 0.04em;
    }

    .inputs {
        border: 1px solid #cbd5e1;
        border-radius: 8px;
        padding: 9px 11px;
        font-size: 0.9rem;
        background: #ffffff;
        color: #0f172a;
    }

    .inputs:focus {
        outline: none;
        border-color: #2563eb;
        box-shadow: 0 0 0 2px rgba(37, 99, 235, 0.15);
    }

    /* ===== BUTTON ===== */
    .submit_btn {
        margin-top: 14px;
        width: 100%;
        padding: 12px;
        border-radius: 10px;
        border: none;
        background: linear-gradient(135deg, #f97316, #fb923c);
        color: #ffffff;
        font-weight: 700;
        letter-spacing: 0.04em;
        cursor: pointer;
        transition: transform 0.15s ease, box-shadow 0.15s ease;
    }

    .submit_btn:hover {
        transform: translateY(-1px);
        box-shadow: 0 8px 20px rgba(249, 115, 22, 0.35);
    }

    /* ===== MODAL OVERLAY ===== */
    .detailed_view {
        position: fixed;
        inset: 0;
        background: rgba(15, 23, 42, 0.88);
        display: flex;
        justify-content: center;
        align-items: center;
        z-index: 9999;
    }

    /* ===== MODAL CONTENT ===== */
    .detailed_view_content {
        background: #ffffff;
        width: 55%;
        height: 80%;
        border-radius: 16px;
        padding: 22px;
        overflow-y: auto;
        box-shadow: 0 25px 70px rgba(15, 23, 42, 0.35);
        border-left: 6px solid #2563eb;
        position: fixed;
        left: 2vw;
    }

    /* ===== METERS & LAST ACTION ===== */
    .meters_div,
    .last_action_div {
        background: #ffffff;
        border-radius: 16px;
        padding: 18px;
        box-shadow: 0 18px 50px rgba(15, 23, 42, 0.3);
    }

    .meters_div {
        position: fixed;
        top: 7%;
        right: 5%;
        width: 28%;
        border-top: 4px solid #2563eb;
    }

    .last_action_div {
        position: fixed;
        bottom: 7%;
        right: 5%;
        width: 28%;
        border-top: 4px solid #f97316;
    }

    /* ===== CLOSE BUTTON ===== */
    .close-btn {
        position: fixed;
        top: 18px;
        right: 22px;
        font-size: 2.6rem;
        color: #ffffff;
        cursor: pointer;
        transition: transform 0.2s ease;
    }

    .close-btn:hover {
        transform: scale(1.15);
    }

    /* ===== TABLE ===== */
    table {
        width: 100%;
        border-collapse: collapse;
        margin-top: 12px;
    }

    th {
        background: #1e3a8a;
        color: #ffffff;
        padding: 12px;
        font-size: 0.8rem;
        text-transform: uppercase;
        letter-spacing: 0.05em;
    }

    td {
        padding: 10px;
        border-bottom: 1px solid #e5e7eb;
        font-size: 0.9rem;
        color: #1f2933;
    }

    tr:nth-child(even) td {
        background: #f8fafc;
    }

    tr:hover td {
        background: #e0f2fe;
    }

    /* ===== RESPONSIVE ===== */
    @media (max-width: 900px) {
        .searched_data {
            max-width: 100%;
        }

        .detailed_view_content {
            width: 92%;
            height: 70%;
        }

        .meters_div,
        .last_action_div {
            position: static;
            width: 92%;
            margin: 12px auto;
        }

        .close-btn {
            font-size: 2rem;
        }
    }

    /* ===== JOBCARD STATE: WARNING (72h+) ===== */
    .searched_data.warning {
        border-top: 5px solid #f59e0b;
        /* amber */
        background: linear-gradient(180deg, #ffffff 0%, #fffbeb 100%);
    }

    /* ===== JOBCARD STATE: STALLED (120h+) ===== */
    .searched_data.stalled {
        border-top: 5px solid #dc2626;
        /* red */
        background: linear-gradient(180deg, #ffffff 0%, #fff5f5 100%);
    }

    /* ===== STATE BADGE ===== */
    .state_badge {
        font-size: 0.7rem;
        font-weight: 800;
        padding: 6px 12px;
        border-radius: 999px;
        display: inline-block;
        margin-bottom: 10px;
        letter-spacing: 0.05em;
    }

    .state_badge.warning {
        background: #f59e0b;
        color: #1f2937;
    }

    .state_badge.stalled {
        background: #dc2626;
        color: #ffffff;
    }
</style>