<?php
include "../../root.class.php";

$html = new html();
$html->add_styles_page();
$db = new db_safeguard();

/*
Teams ordered by ACTIVE jobcards DESC
*/
$teams_res = $db->query(
    "teams",
    "
    SELECT
    t.record_id,
    t.name,
    COUNT(j.record_id) AS active_jobs
    FROM teams t
    LEFT JOIN jobcards j
    ON j.team_assigned_id = t.record_id
    AND j.status = 0
    AND NOT EXISTS (
        SELECT 1
        FROM jobcard_timeline jt
        WHERE jt.jobcard_id = j.record_id
        AND jt.status = 1
    )
    WHERE t.status = 'ACTIVE'
    GROUP BY t.record_id, t.name
    ORDER BY active_jobs DESC, t.name ASC
    "
);
?>

<h1>ACTIVE JOBCARDS BY TEAM</h1>

<div class="teams_container">

    <?php while ($team = $teams_res->fetch_assoc()): ?>
    <div class="team_card" id="team_<?= htmlspecialchars($team['record_id']); ?>">
    <div class="team_header">
    <?= htmlspecialchars($team['name']); ?>
    <span class="count">
    <?= (int) $team['active_jobs']; ?> active
    </span>
</div>

<div
class="team_body"
data-team-id="<?= htmlspecialchars($team['record_id']); ?>"
>
Loading jobcards...
</div>
</div>
<?php endwhile; ?>

</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 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=" + encodeURIComponent(jobcard_id)
            })
        .then(response => response.json())
        .then(data => {

                if (data.status === "success") {

                    alert("Jobcard completed successfully.");

                    /* remove card instantly or reload */
                    location.reload();

                } else {

                    alert("Error: " + (data.message || "Unknown error"));

                }

            })
        .catch(error => {

                console.error(error);
                alert("Server error occurred.");

            });
    }

    function loadTeam(teamId) {
        const container = document.querySelector(
            ".team_body[data-team-id='" + teamId + "']"
        );

        if (!container) return;

        fetch("jobcards_by_team_data.php?team_id=" + encodeURIComponent(teamId))
        .then(res => res.text())
        .then(data => {
                if (container.innerHTML !== data) {
                    container.style.opacity = 0.4;
                    container.innerHTML = data;
                    container.style.opacity = 1;
                }
            });
    }

    function openDetails(jc_no) {
        document.getElementById("detailed_view").style.display = "flex";

        fetch("jobcard_details.php?jc_no=" + encodeURIComponent(jc_no))
        .then(res => res.text())
        .then(data => {
                document.getElementById("detailed_view_content").innerHTML = data;
            });

        fetch("jobcard_meters.php?jc_no=" + encodeURIComponent(jc_no))
        .then(res => res.text())
        .then(data => {
                document.getElementById("meters_div").innerHTML = data;
            });

        fetch("jobcard_last_action.php?jc_no=" + encodeURIComponent(jc_no))
        .then(res => res.text())
        .then(data => {
                document.getElementById("last_action_div").innerHTML = data;
            });
    }

    function closeDetails() {
        document.getElementById("detailed_view").style.display = "none";
    }

        /* ===== AUTO REFRESH PER TEAM ===== */
    document.querySelectorAll(".team_body").forEach(div => {
        const teamId = div.dataset.teamId;
        loadTeam(teamId);
        setInterval(() => loadTeam(teamId), 5000);
    });
</script>

<!-- ================= STYLES ================= -->

<style>
    body {
        font-family: "Segoe UI", Roboto, Arial, sans-serif;
        background: #f8fafc;
        color: #0f172a;
    }

    h1 {
        text-align: center;
        margin: 2vw 0;
        color: #1e3a8a;
    }

    /* ===== TEAMS GRID ===== */
    .teams_container {
        display: flex;
        flex-wrap: wrap;
        justify-content: center;
        gap: 20px;
    }

    /* ===== TEAM CARD ===== */
    .team_card {
        background: #ffffff;
        width: 380px;
        border-radius: 16px;
        box-shadow: 0 12px 30px rgba(15, 23, 42, 0.15);
        overflow: hidden;
    }

    /* ===== TEAM HEADER ===== */
    .team_header {
        background: linear-gradient(135deg, #1e40af, #2563eb);
        color: white;
        padding: 14px 16px;
        font-weight: 700;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }

    .team_header .count {
        font-size: 0.8rem;
        background: #f97316;
        padding: 4px 8px;
        border-radius: 999px;
    }

    /* ===== TEAM BODY ===== */
    .team_body {
        padding: 14px;
        transition: opacity 0.2s ease;
    }

    /* ===== JOBCARD ITEM ===== */
    .jobcard_item {
        background: #f8fafc;
        border: 1px solid #e5e7eb;
        border-left: 4px solid #2563eb;
        padding: 10px;
        border-radius: 10px;
        margin-bottom: 10px;
    }

    .jobcard_item strong {
        color: #1e3a8a;
    }

    .jobcard_item button {
        margin-top: 8px;
        width: 100%;
        padding: 8px;
        border: none;
        border-radius: 8px;
        background: linear-gradient(135deg, #f97316, #fb923c);
        color: white;
        font-weight: 600;
        cursor: pointer;
    }

    /* ===== MODAL ===== */
    .detailed_view {
        position: fixed;
        inset: 0;
        background: rgba(15, 23, 42, 0.9);
        z-index: 9999;
        display: flex;
        justify-content: center;
        align-items: center;
    }

    .detailed_view_content {
        background: white;
        width: 55%;
        height: 80%;
        padding: 20px;
        border-radius: 16px;
        overflow-y: auto;
        border-left: 6px solid #2563eb;
        position: fixed;
        left: 2vw;
    }

    .meters_div,
    .last_action_div {
        background: white;
        padding: 18px;
        border-radius: 16px;
        position: fixed;
        right: 4%;
        width: 28%;
    }

    .meters_div {
        top: 8%;
        border-top: 4px solid #2563eb;
    }

    .last_action_div {
        bottom: 8%;
        border-top: 4px solid #f97316;
    }

    .close-btn {
        position: fixed;
        top: 18px;
        right: 24px;
        font-size: 2.5rem;
        color: white;
        cursor: pointer;
    }

    .complete_btn{
        position: fixed;
        bottom: 3%;
        left: 40%;
        padding: 14px 28px;
        font-size: 16px;
        font-weight: 700;
        border: none;
        border-radius: 10px;
        background: linear-gradient(135deg,#16a34a,#22c55e);
        color: white;
        cursor: pointer;
        box-shadow: 0 10px 25px rgba(0,0,0,0.2);
    }

    .complete_btn:hover{
        transform: scale(1.05);
    }
</style>
