<?php
include "../../root.class.php";

$db = new db_safeguard();

/* =========================
   FETCH JOBCARDS
========================= */
$res = $db->query(
    "jobcards",
    "SELECT * FROM jobcards WHERE status = 1 AND user_id != 1"
);

/* =========================
   BUILD JS ARRAY
========================= */
$js_array = "[";
$first = true;

if ($res->num_rows > 0) {

    while ($row = $res->fetch_assoc()) {

        /* =========================
           COORDINATES
        ========================= */
        if (strpos($row['drill_co_ordinates'], ":") !== false) {
            $lant = -25.5653;
            $long = 30.5279;
        } else {
            $co_ordinates = str_replace("?", "°", $row['drill_co_ordinates']);
            $location = explode(" ", trim($co_ordinates));

            $lant = isset($location[0]) ? (float)$location[0] : -25.5653;
            $long = isset($location[1]) ? (float)$location[1] : 30.5279;
        }

        /* =========================
           TOTAL METERS
        ========================= */
        $total_res = $db->query(
            "jobcard_timeline",
            "SELECT * FROM jobcard_timeline WHERE jobcard_id = '{$row['jc_no']}'"
        );

        $total_rieming = 0;
        $total_drilling = 0;
        $total_casing = 0;

        while ($total = $total_res->fetch_assoc()) {
            if ($total['type'] === "RIEMING_STOP") {
                $total_rieming += (float)$total['meters'];
            } elseif ($total['type'] === "DRILLING_STOP") {
                $total_drilling += (float)$total['meters'];
            } elseif ($total['type'] === "CASING_STOP") {
                $total_casing += (float)$total['meters'];
            }
        }

        if (!$first) $js_array .= ",";
        $first = false;

        $js_array .= "{
            latitude: {$lant},
            longitude: {$long},
            action_date: '{$row['action_date']}',
            jobcard: '{$row['jc_no']}',
            client: '{$row['client_id']}',
            water_flow: '{$row['water_flow']}',
            rieming: {$total_rieming},
            drilling: {$total_drilling},
            casing: {$total_casing}
        }";
    }
}

$js_array .= "]";
?>

<!DOCTYPE html>
<html>
<head>
    <title>Saved Jobcard Locations</title>

    <style>
        /* ===== BASE ===== */
        body {
            margin: 0;
            font-family: "Segoe UI", Roboto, Arial, sans-serif;
            background: #f8fafc;
            color: #0f172a;
        }

        h2 {
            margin: 0;
            padding: 18px 24px;
            background: linear-gradient(90deg, #1e40af, #1e3a8a);
            color: #ffffff;
            font-weight: 600;
            letter-spacing: 0.4px;
            border-bottom: 4px solid #f97316;
        }

        /* ===== MAP ===== */
        #map {
            height: calc(100vh - 72px);
            width: 100%;
        }

        /* ===== LOADER ===== */
        #map-loader {
            position: fixed;
            inset: 0;
            background: linear-gradient(
                135deg,
                rgba(224,231,255,0.95),
                rgba(255,255,255,0.95)
            );
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 9999;
            opacity: 1;
            transition: opacity 0.6s ease;
        }

        #map-loader.fade-out {
            opacity: 0;
            pointer-events: none;
        }

        .loader-box {
            background: #ffffff;
            padding: 28px 36px;
            border-radius: 14px;
            box-shadow: 0 12px 30px rgba(30,64,175,0.18);
            text-align: center;
            min-width: 220px;
        }

        .spinner {
            width: 54px;
            height: 54px;
            border: 5px solid #e0e7ff;
            border-top: 5px solid #f97316;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin: 0 auto 14px;
        }

        .loader-box p {
            margin: 0;
            font-weight: 500;
            color: #1e40af;
            letter-spacing: 0.3px;
        }

        @keyframes spin {
            to { transform: rotate(360deg); }
        }
    </style>
</head>

<body>

<h2>Saved Jobcard Locations</h2>

<!-- 🔄 LOADER -->
<div id="map-loader">
    <div class="loader-box">
        <div class="spinner"></div>
        <p>Loading map…</p>
    </div>
</div>

<div id="map"></div>

<script>
    const savedLocations = <?php echo $js_array; ?>;
    let map;

    function initMap() {

        const mapCenter = {
            lat: -25.5653,
            lng: 30.5279
        };

        map = new google.maps.Map(document.getElementById("map"), {
            center: mapCenter,
            zoom: 8
        });

        savedLocations.forEach((location, index) => {

            const marker = new google.maps.Marker({
                position: {
                    lat: location.latitude,
                    lng: location.longitude
                },
                map: map,
                label: String(index + 1)
            });

            const infoWindow = new google.maps.InfoWindow({
                content: `
                    <strong>Jobcard:</strong> ${location.jobcard}<br>
                    <strong>Client:</strong> ${location.client}<br>
                    <strong>Action Date:</strong> ${location.action_date}<br>
                    <strong>Water Flow:</strong> ${location.water_flow}<br>
                    <strong>Latitude:</strong> ${location.latitude}<br>
                    <strong>Longitude:</strong> ${location.longitude}<br>
                    <strong>Rieming:</strong> ${location.rieming} m<br>
                    <strong>Drilling:</strong> ${location.drilling} m<br>
                    <strong>Casing:</strong> ${location.casing} m
                `
            });

            marker.addListener("click", () => {
                infoWindow.open(map, marker);
            });
        });

        google.maps.event.addListenerOnce(map, "idle", () => {
            const loader = document.getElementById("map-loader");
            loader.classList.add("fade-out");

            setTimeout(() => {
                loader.style.display = "none";
            }, 600);
        });
    }
</script>

<script async defer
    src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCXu62pAxEnoWh-eXMpYBkGsz_iX-EVm2k&callback=initMap">
</script>

</body>
</html>
