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

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

$js_array = "[";
if ($res->num_rows > 0) {
    $first = true;
    while ($row = $res->fetch_assoc()) {

        if (strpos($row['drill_co_ordinates'], ":")) {
            $lant = -25.482195;
            $long = 30.963575;
        } else {
            $co_ordinates = str_replace("?", "°", $row['drill_co_ordinates']);
            $location = explode(" ", $co_ordinates);
            $lant = $location[0];
            $long = $location[1];
            ?>
            <script>
                console.log(<?php echo $lant; ?>);
                console.log(<?php echo $long; ?>);
            </script>
            <?php
        }

        $jobcard = $row['jc_no'];
        $date = $row['action_date'];
        $water_flow = $row['water_flow'];
        $client = $row['client_id'];
        if ($first) {
            $first = false;
        } else {
            $js_array .= ",";
        }

        $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 += $total['meters'];
                // echo $total_rieming;
                ?>
                <script>
                    console.log(<?php echo $total_rieming; ?>);
                </script>
                <?php
            } elseif ($total['type'] == "DRILLING_STOP") {
                $total_drilling += $total['meters'];
                // echo $total_drilling;
                ?>
                <script>
                    console.log(<?php echo $total_drilling; ?>);
                </script>
                <?php
            } elseif ($total['type'] == "CASING_STOP") {
                $total_casing += $total['meters'];
                // echo $total_casing;
                ?>
                <script>
                    console.log(<?php echo $total_casing; ?>);
                </script>
                <?php
            }
        }

        $js_array .= "{
                latitude: `" . $lant . "`,
                longitude: `" . $long . "`,
                action_date: '" . $date . "',
                jobcard: '" . $jobcard . "',
                client: '" . $client . "',
                water_flow: '" . $water_flow . "',
                rieming: `" . $total_rieming . "`,
                drilling: `" . $total_drilling . "`,
                casing: `" . $total_casing . "`
            }";

    }
}
$js_array .= "]";

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

?>

<!DOCTYPE html>
<html>

<head>
    <title>Saved Locations Viewer</title>
    <style>
        #map {
            height: 90vh;
            width: 100%;
            margin-top: 10px;
        }

        body {
            font-family: Arial, sans-serif;
            padding: 10px;
        }
    </style>
</head>

<body>

    <h2>Saved Jobcard Locations</h2>
    <div id="map"></div>

    <script>
        // 🔧 Add your saved locations here:
        const savedLocations = <?php echo $js_array; ?>;

        let map;

        function initMap() {
            if (savedLocations.length === 0) {
                alert("No locations to display.");
                return;
            }

            const firstLocation = {
                lat: parseFloat(savedLocations[0].latitude),
                lng: parseFloat(savedLocations[0].longitude)
            };

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

            savedLocations.forEach((location, index) => {
                const position = {
                    lat: parseFloat(location.latitude),
                    lng: parseFloat(location.longitude)
                };

                const marker = new google.maps.Marker({
                    position,
                    map,
                    label: (index + 1).toString()
                });

                const infoContent = `
                    <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>Lat:</strong> ${location.latitude}<br>
                    <strong>Lng:</strong> ${location.longitude}<br>
                    <strong>Rieming:</strong> ${location.rieming}<br>
                    <strong>Drilling:</strong> ${location.drilling}<br>
                    <strong>Casing:</strong> ${location.casing}<br>
                `;

                const infoWindow = new google.maps.InfoWindow({
                    content: infoContent
                });

                marker.addListener('click', () => {
                    infoWindow.open(map, marker);
                });
            });
        }
    </script>

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

</html>