<?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"
);

/* =========================
   COORDINATE PARSER
========================= */
function parseCoordinates(?string $raw, float $defLat = -25.5653, float $defLng = 30.5279): array
{
    if ($raw === null || trim($raw) === '') return [$defLat, $defLng];
    $raw = trim($raw);
    if (preg_match('/\d+:\d+/', $raw)) return [$defLat, $defLng];

    $clean = str_replace(['°', "'", '"', '?', ','], ' ', $raw);
    $clean = preg_replace('/\s+/', ' ', trim($clean));

    preg_match_all('/-?\d+(?:\.\d+)?/', $clean, $m);
    $n = $m[0];

    if (count($n) >= 2) {
        $lat = (float)$n[0];
        $lng = (float)$n[1];
        if (preg_match('/[Ss]/', $raw)) $lat = -abs($lat);
        if (preg_match('/[Ww]/', $raw)) $lng = -abs($lng);
        if ($lat >= -35 && $lat <= -22 && $lng >= 16 && $lng <= 33) {
            return [$lat, $lng];
        }
    }
    return [$defLat, $defLng];
}

/* =========================
   BUILD PHP ARRAY
========================= */
$locations = [];

if ($res->num_rows > 0) {
    while ($row = $res->fetch_assoc()) {
        [$lant, $long] = parseCoordinates($row['drill_co_ordinates']);

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

        $tr = $td = $tc = $tb = 0;
        while ($t = $total_res->fetch_assoc()) {
            if     ($t['type'] === 'RIEMING_STOP'   || $t['type'] === 'RIEMING_PAUSE')  $tr += (float)$t['meters'];
            elseif ($t['type'] === 'DRILLING_STOP'  || $t['type'] === 'DRILLING_PAUSE') $td += (float)$t['meters'];
            elseif ($t['type'] === 'CASING_STOP'    || $t['type'] === 'CASING_PAUSE')   $tc += (float)$t['meters'];
            elseif ($t['type'] === 'BLASTING_STOP'  || $t['type'] === 'BLASTING_PAUSE') $tb += (float)$t['meters'];
        }

        $locations[] = [
            'latitude'    => $lant,
            'longitude'   => $long,
            'action_date' => $row['action_date'],
            'jobcard'     => $row['jc_no'],
            'water_flow'  => $row['water_flow'],
            'rieming'     => $tr,
            'drilling'    => $td,
            'casing'      => $tc,
            'blasting'    => $tb,
        ];
    }
}

$js_array = json_encode($locations, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Jobcard Locations</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link href="https://fonts.googleapis.com/css2?family=DM+Mono:wght@400;500&family=Plus+Jakarta+Sans:wght@400;500;600;700&display=swap" rel="stylesheet">
    <style>
        :root {
            --bg:            #fff4ec;
            --surface:       #fff8f3;
            --surface-2:     #fff1e6;
            --border:        #fad8bc;
            --border-strong: #f4b98a;
            --accent:        #c2500a;
            --accent-light:  rgba(194,80,10,.07);
            --accent-mid:    rgba(194,80,10,.18);
            --text:          #2d1200;
            --muted:         #7a4020;
            --faint:         #c4825a;
            --green:       #16a34a;
            --green-bg:    #f0fdf4;
            --blue:        #1d4ed8;
            --blue-bg:     #eff6ff;
            --red:         #dc2626;
            --red-bg:      #fef2f2;
            --amber:       #b45309;
            --amber-bg:    #fffbeb;
            --header-h:    58px;
            --panel-w:     320px;
            --shadow-sm:   0 1px 3px rgba(0,0,0,.08), 0 1px 2px rgba(0,0,0,.04);
            --shadow-md:   0 4px 12px rgba(0,0,0,.08), 0 2px 4px rgba(0,0,0,.04);
        }

        *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }

        body {
            font-family: 'Plus Jakarta Sans', sans-serif;
            background: var(--bg);
            color: var(--text);
            height: 100vh;
            display: flex;
            flex-direction: column;
            overflow: hidden;
        }

        /* ── HEADER ──────────────────────────── */
        header {
            height: var(--header-h);
            background: var(--surface);
            border-bottom: 1px solid var(--border);
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 0 20px;
            flex-shrink: 0;
            box-shadow: var(--shadow-sm);
            z-index: 10;
        }

        .h-left { display: flex; align-items: center; gap: 12px; }

        .h-icon {
            width: 34px; height: 34px;
            background: var(--accent);
            border-radius: 9px;
            display: flex; align-items: center; justify-content: center;
            box-shadow: 0 2px 8px rgba(194,80,10,.30);
        }
        .h-icon svg { width: 18px; height: 18px; fill: #fff; }

        header h1 {
            font-size: 15px;
            font-weight: 700;
            letter-spacing: .2px;
            color: var(--text);
        }

        .badge {
            background: var(--accent-light);
            border: 1px solid var(--accent-mid);
            color: var(--accent);
            font-family: 'DM Mono', monospace;
            font-size: 11px;
            font-weight: 500;
            padding: 4px 11px;
            border-radius: 20px;
        }

        /* ── LAYOUT ──────────────────────────── */
        .body-wrap { flex: 1; display: flex; overflow: hidden; }

        /* ── SIDEBAR ─────────────────────────── */
        aside {
            width: var(--panel-w);
            background: var(--surface);
            border-right: 1px solid var(--border);
            display: flex;
            flex-direction: column;
            overflow: hidden;
            flex-shrink: 0;
            box-shadow: 2px 0 8px rgba(0,0,0,.04);
            z-index: 5;
        }

        .panel-head {
            padding: 14px 16px 12px;
            border-bottom: 1px solid var(--border);
            background: var(--surface-2);
        }
        .panel-head h2 {
            font-size: 10px;
            font-weight: 700;
            letter-spacing: 1.2px;
            text-transform: uppercase;
            color: var(--faint);
        }

        .search-wrap {
            padding: 10px 12px;
            border-bottom: 1px solid var(--border);
            background: var(--surface);
        }
        .search-wrap input {
            width: 100%;
            background: var(--surface-2);
            border: 1.5px solid var(--border);
            border-radius: 7px;
            padding: 7px 10px 7px 32px;
            color: var(--text);
            font-family: 'DM Mono', monospace;
            font-size: 12px;
            outline: none;
            transition: border-color .2s, box-shadow .2s;
            background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='14' height='14' viewBox='0 0 24 24' fill='none' stroke='%2394a3b8' stroke-width='2'%3E%3Ccircle cx='11' cy='11' r='8'/%3E%3Cpath d='m21 21-4.35-4.35'/%3E%3C/svg%3E");
            background-repeat: no-repeat;
            background-position: 10px center;
        }
        .search-wrap input:focus {
            border-color: var(--accent);
            box-shadow: 0 0 0 3px var(--accent-light);
        }
        .search-wrap input::placeholder { color: var(--faint); }

        /* ── LIST ────────────────────────────── */
        .jc-list { flex: 1; overflow-y: auto; padding: 6px 8px; }
        .jc-list::-webkit-scrollbar { width: 4px; }
        .jc-list::-webkit-scrollbar-track { background: transparent; }
        .jc-list::-webkit-scrollbar-thumb { background: var(--border-strong); border-radius: 4px; }

        .jc-item {
            padding: 11px 12px;
            cursor: pointer;
            border-radius: 8px;
            border: 1.5px solid transparent;
            margin-bottom: 4px;
            transition: background .15s, border-color .15s, box-shadow .15s;
        }
        .jc-item:hover {
            background: var(--surface-2);
            border-color: var(--border);
        }
        .jc-item.active {
            background: var(--accent-light);
            border-color: var(--accent-mid);
            box-shadow: 0 2px 8px rgba(234,88,12,.1);
        }

        .jc-num {
            font-family: 'DM Mono', monospace;
            font-size: 12px;
            font-weight: 500;
            color: var(--text);
            margin-bottom: 6px;
        }
        .jc-item.active .jc-num { color: var(--accent); }

        .jc-chips {
            display: flex;
            flex-wrap: wrap;
            gap: 4px;
        }

        .chip {
            display: inline-flex;
            align-items: center;
            gap: 3px;
            padding: 2px 7px;
            border-radius: 4px;
            font-family: 'DM Mono', monospace;
            font-size: 10px;
            font-weight: 500;
            line-height: 1.6;
        }
        .chip-date  { background: #f1f5f9; color: var(--muted); }
        .chip-drill { background: var(--blue-bg);  color: var(--blue);  }
        .chip-water { background: var(--green-bg); color: var(--green); }
        .chip-blast { background: var(--red-bg);   color: var(--red);   }

        /* ── PANEL FOOTER ────────────────────── */
        .panel-foot {
            padding: 10px 16px;
            border-top: 1px solid var(--border);
            background: var(--surface-2);
            display: flex;
            justify-content: space-between;
            font-family: 'DM Mono', monospace;
            font-size: 10px;
            color: var(--faint);
        }

        /* ── MAP ─────────────────────────────── */
        #map { flex: 1; }

        /* ── LOADER ──────────────────────────── */
        #map-loader {
            position: fixed; inset: 0;
            background: var(--bg);
            display: flex; align-items: center; justify-content: center;
            z-index: 9999;
            opacity: 1; transition: opacity .5s ease;
        }
        #map-loader.fade-out { opacity: 0; pointer-events: none; }

        .loader-card {
            background: var(--surface);
            border: 1px solid var(--border);
            border-radius: 14px;
            padding: 32px 44px;
            text-align: center;
            display: flex; flex-direction: column;
            align-items: center; gap: 16px;
            box-shadow: var(--shadow-md);
        }
        .loader-ring {
            width: 44px; height: 44px;
            border: 3px solid var(--border);
            border-top: 3px solid var(--accent);
            border-radius: 50%;
            animation: spin .9s linear infinite;
        }
        .loader-card p {
            font-size: 12px; font-weight: 600;
            color: var(--muted); letter-spacing: .4px;
        }
        @keyframes spin { to { transform: rotate(360deg); } }

        /* ── INFO WINDOW ─────────────────────── */
        .gm-style .gm-style-iw-c {
            background: var(--surface) !important;
            border: 1px solid var(--border) !important;
            border-radius: 10px !important;
            padding: 0 !important;
            box-shadow: var(--shadow-md) !important;
        }
        .gm-style .gm-style-iw-d  { overflow: hidden !important; }
        .gm-style .gm-style-iw-t::after { background: var(--surface) !important; }
        .gm-style .gm-ui-hover-effect { display: none !important; }

        .ic {
            padding: 14px 16px 13px;
            min-width: 220px;
            font-family: 'Plus Jakarta Sans', sans-serif;
        }
        .ic-title {
            font-family: 'DM Mono', monospace;
            font-size: 13px; font-weight: 500;
            color: var(--accent);
            margin-bottom: 10px; padding-bottom: 9px;
            border-bottom: 1px solid var(--border);
        }
        .ic-row {
            display: flex; justify-content: space-between; align-items: center;
            font-size: 11.5px;
            padding: 3px 0;
        }
        .ic-row .lbl { color: var(--muted); font-weight: 500; }
        .ic-row .val { font-weight: 600; color: var(--text); }
        .ic-row .val.blue  { color: var(--blue); }
        .ic-row .val.green { color: var(--green); }
        .ic-row .val.red   { color: var(--red); }
        .ic-row .val.amber { color: var(--amber); }
        .ic-coords {
            margin-top: 9px; padding-top: 9px;
            border-top: 1px solid var(--border);
            font-size: 10px; font-family: 'DM Mono', monospace;
            color: var(--faint); line-height: 1.8;
        }

        @media (max-width: 680px) { aside { display: none; } }
    </style>
</head>
<body>

<div id="map-loader">
    <div class="loader-card">
        <div class="loader-ring"></div>
        <p>Loading Map…</p>
    </div>
</div>

<header>
    <div class="h-left">
        <div class="h-icon">
            <svg viewBox="0 0 24 24"><path d="M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7zm0 9.5c-1.38 0-2.5-1.12-2.5-2.5s1.12-2.5 2.5-2.5 2.5 1.12 2.5 2.5-1.12 2.5-2.5 2.5z"/></svg>
        </div>
        <h1>Jobcard Locations</h1>
    </div>
    <span class="badge" id="total-badge">— SITES</span>
</header>

<div class="body-wrap">
    <aside>
        <div class="panel-head"><h2>Active Jobcards</h2></div>
        <div class="search-wrap">
            <input type="text" id="jc-search" placeholder="Search jobcard number…">
        </div>
        <div class="jc-list" id="jc-list"></div>
        <div class="panel-foot">
            <span id="visible-count">0 visible</span>
            <span>Click to fly to site</span>
        </div>
    </aside>
    <div id="map"></div>
</div>

<script>
const savedLocations = <?php echo $js_array; ?>;
let map, markers = [], infoWindows = [], activeIdx = null;

/* ── Custom SVG pin ─────────────────────────────────────────── */
function makePinUrl(label, active) {
    const bg  = active ? '#c2500a' : '#fff8f3';
    const bdr = active ? '#9a3d06' : '#c2500a';
    const tx  = active ? '#ffffff' : '#c2500a';
    const fs  = 9;
    const w   = Math.max(52, label.length * fs * 0.72 + 18);
    const bh  = 26;
    const h   = bh + 14;
    const cx  = w / 2;
    const shadow = active ? '' : `<filter id="s"><feDropShadow dx="0" dy="1" stdDeviation="1.5" flood-opacity=".18"/></filter>`;
    const fAttr  = active ? '' : ' filter="url(#s)"';
    const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${w}" height="${h}">
      <defs>${shadow}</defs>
      <rect x="1" y="1" width="${w-2}" height="${bh}" rx="5" fill="${bg}" stroke="${bdr}" stroke-width="1.5"${fAttr}/>
      <polygon points="${cx-6},${bh} ${cx+6},${bh} ${cx},${h-1}" fill="${bg}" stroke="${bdr}" stroke-width="1.5" stroke-linejoin="round"/>
      <polygon points="${cx-4},${bh-1} ${cx+4},${bh-1} ${cx},${h-4}" fill="${bg}"/>
      <text x="${cx}" y="${bh/2+1}" text-anchor="middle" dominant-baseline="middle"
            font-family="DM Mono,monospace" font-size="${fs}" font-weight="500" fill="${tx}">${label}</text>
    </svg>`;
    return 'data:image/svg+xml;charset=UTF-8,' + encodeURIComponent(svg);
}

function pinAnchor(label) {
    const w = Math.max(52, label.length * 9 * 0.72 + 18);
    return new google.maps.Point(w / 2, 39);
}

/* ── Build sidebar ──────────────────────────────────────────── */
function buildSidebar() {
    const list = document.getElementById('jc-list');
    list.innerHTML = '';
    document.getElementById('total-badge').textContent = savedLocations.length + ' SITES';
    document.getElementById('visible-count').textContent = savedLocations.length + ' visible';

    savedLocations.forEach((loc, i) => {
        const div = document.createElement('div');
        div.className = 'jc-item';
        div.dataset.idx = i;

        const totalDrill = (loc.rieming + loc.drilling + loc.casing).toFixed(1);

        div.innerHTML = `
            <div class="jc-num">${loc.jobcard}</div>
            <div class="jc-chips">
                <span class="chip chip-date">${loc.action_date}</span>
                <span class="chip chip-drill">⬇ ${totalDrill} m drilled</span>
                <span class="chip chip-water">≈ ${loc.water_flow}</span>
                <span class="chip chip-blast">💥 ${loc.blasting.toFixed(1)} m blast</span>
            </div>`;
        div.addEventListener('click', () => flyTo(i));
        list.appendChild(div);
    });
}

/* ── Search ─────────────────────────────────────────────────── */
document.getElementById('jc-search').addEventListener('input', function () {
    const q = this.value.trim().toLowerCase();
    const items = document.querySelectorAll('.jc-item');
    let n = 0;
    items.forEach(el => {
        const show = el.querySelector('.jc-num').textContent.toLowerCase().includes(q);
        el.style.display = show ? '' : 'none';
        if (show) n++;
    });
    document.getElementById('visible-count').textContent = n + ' visible';
});

/* ── Fly to ─────────────────────────────────────────────────── */
function flyTo(idx) {
    if (activeIdx !== null) {
        setActive(activeIdx, false);
        document.querySelectorAll('.jc-item')[activeIdx]?.classList.remove('active');
    }
    activeIdx = idx;
    setActive(idx, true);
    infoWindows.forEach(iw => iw.close());
    infoWindows[idx].open(map, markers[idx]);
    map.panTo({ lat: savedLocations[idx].latitude, lng: savedLocations[idx].longitude });
    map.setZoom(14);
    document.querySelectorAll('.jc-item')[idx]?.classList.add('active');
    document.querySelectorAll('.jc-item')[idx]?.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
}

function setActive(idx, active) {
    const label = savedLocations[idx].jobcard;
    markers[idx].setIcon({ url: makePinUrl(label, active), anchor: pinAnchor(label) });
}

/* ── Init map ───────────────────────────────────────────────── */
function initMap() {
    map = new google.maps.Map(document.getElementById('map'), {
        center: { lat: -25.5653, lng: 30.5279 },
        zoom: 8,
        disableDefaultUI: true,
        zoomControl: true,
        zoomControlOptions: { position: google.maps.ControlPosition.RIGHT_BOTTOM },
        styles: [
            { elementType: 'geometry',           stylers: [{ color: '#fdf1e8' }] },
            { elementType: 'labels.text.fill',   stylers: [{ color: '#7a4020' }] },
            { elementType: 'labels.text.stroke', stylers: [{ color: '#fdf1e8' }] },
            { featureType: 'road',               elementType: 'geometry',         stylers: [{ color: '#fff8f3' }] },
            { featureType: 'road',               elementType: 'geometry.stroke',  stylers: [{ color: '#fad8bc' }] },
            { featureType: 'road.arterial',      elementType: 'labels.text.fill', stylers: [{ color: '#7a4020' }] },
            { featureType: 'road.highway',       elementType: 'geometry',         stylers: [{ color: '#fce8d4' }] },
            { featureType: 'road.highway',       elementType: 'labels.text.fill', stylers: [{ color: '#5c3010' }] },
            { featureType: 'road.local',         elementType: 'labels.text.fill', stylers: [{ color: '#c4825a' }] },
            { featureType: 'water',              elementType: 'geometry',         stylers: [{ color: '#fbd4a8' }] },
            { featureType: 'water',              elementType: 'labels.text.fill', stylers: [{ color: '#7a4020' }] },
            { featureType: 'poi',                elementType: 'geometry',         stylers: [{ color: '#fce8d4' }] },
            { featureType: 'poi',                elementType: 'labels.text.fill', stylers: [{ color: '#a05828' }] },
            { featureType: 'poi.park',           elementType: 'geometry',         stylers: [{ color: '#f8dfc4' }] },
            { featureType: 'poi.park',           elementType: 'labels.text.fill', stylers: [{ color: '#c4825a' }] },
            { featureType: 'landscape',          elementType: 'geometry',         stylers: [{ color: '#faeade' }] },
            { featureType: 'administrative',     elementType: 'geometry.stroke',  stylers: [{ color: '#f4b98a' }] },
            { featureType: 'transit',            elementType: 'geometry',         stylers: [{ color: '#fce8d4' }] },
        ]
    });

    savedLocations.forEach((loc, idx) => {
        const label  = loc.jobcard;
        const marker = new google.maps.Marker({
            position: { lat: loc.latitude, lng: loc.longitude },
            map,
            icon: { url: makePinUrl(label, false), anchor: pinAnchor(label) },
            title: label
        });

        const iw = new google.maps.InfoWindow({
            content: `
              <div class="ic">
                <div class="ic-title">${loc.jobcard}</div>
                <div class="ic-row"><span class="lbl">Date</span>       <span class="val">${loc.action_date}</span></div>
                <div class="ic-row"><span class="lbl">Water Flow</span> <span class="val green">${loc.water_flow}</span></div>
                <div class="ic-row"><span class="lbl">Rieming</span>    <span class="val blue">${loc.rieming} m</span></div>
                <div class="ic-row"><span class="lbl">Drilling</span>   <span class="val blue">${loc.drilling} m</span></div>
                <div class="ic-row"><span class="lbl">Casing</span>     <span class="val amber">${loc.casing} m</span></div>
                <div class="ic-row"><span class="lbl">Blasting</span>   <span class="val red">${loc.blasting} m</span></div>
                <div class="ic-coords">
                  Lat: ${loc.latitude.toFixed(6)}<br>
                  Lng: ${loc.longitude.toFixed(6)}
                </div>
              </div>`
        });

        marker.addListener('click', () => flyTo(idx));
        markers.push(marker);
        infoWindows.push(iw);
    });

    buildSidebar();

    google.maps.event.addListenerOnce(map, 'idle', () => {
        const loader = document.getElementById('map-loader');
        loader.classList.add('fade-out');
        setTimeout(() => loader.style.display = 'none', 550);
    });
}
</script>

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