<?php
include "$_SERVER[DOCUMENT_ROOT]/root.class.php";
$html = new html();
$html->add_styles_page();
$db = new db_safeguard();

// Fetch jobcard data
$record_id = (int) $_GET['record_id'];
$jobcard = $db->query("jobcards", "SELECT * FROM jobcards WHERE record_id = $record_id")->fetch_assoc();

// Users
$user_created = $db->query("users", "SELECT username FROM users WHERE record_id={$jobcard['user_id']}")->fetch_assoc()['username'];
$user_assigned = $db->query("users", "SELECT username FROM users WHERE record_id={$jobcard['user_assigned']}")->fetch_assoc()['username'];

// Timeline & Notes
$timeline = $db->query("jobcard_timeline", "SELECT * FROM jobcard_timeline WHERE jobcard_id={$record_id} ORDER BY record_id ASC");
$notes = $db->query("notes", "SELECT * FROM notes WHERE jobcard_id={$record_id}");
?>

<style>
    /* ===== GLOBAL STYLES ===== */
    body {
        font-family: "Segoe UI", Roboto, Arial, sans-serif;
        background: #f8fafc;
        color: #0f172a;
        margin: 0;
        padding: 0;
    }

    h1,
    h2,
    h3 {
        margin: 0 0 12px 0;
    }

    h1 {
        color: #1e3a8a;
        text-align: center;
        margin: 2vw 0;
    }

    a {
        text-decoration: none;
        color: #2563eb;
    }

    button {
        cursor: pointer;
        padding: 10px 16px;
        border-radius: 8px;
        border: none;
        background: #2563eb;
        color: #fff;
        font-weight: 600;
    }

    button:hover {
        opacity: 0.9;
    }

    /* ===== STICKY NAV ===== */
    .sticky-nav {
        position: sticky;
        top: 1.9vw;
        background: #1e3a8a;
        padding: 12px 24px;
        display: flex;
        gap: 16px;
        z-index: 999;
        align-items: center;
        justify-content: space-evenly;
        border-radius: 2vw;
    }

    .sticky-nav a {
        color: #fff;
        font-weight: 600;
        text-transform: uppercase;
    }

    /* ===== SECTION CARD ===== */
    .section_card {
        background: #ffffff;
        border-radius: 16px;
        padding: 24px;
        margin: 24px auto;
        width: 85%;
        box-shadow: 0 12px 30px rgba(15, 23, 42, 0.1);
    }

    .section_card.orange {
        border-left: 6px solid #f97316;
    }

    .section_card.blue {
        border-left: 6px solid #2563eb;
    }

    .section_title {
        font-size: 1.2rem;
        font-weight: 700;
        color: #1e3a8a;
        margin-bottom: 16px;
        text-transform: uppercase;
    }

    /* ===== GRID ===== */
    .flex_row {
        display: flex;
        gap: 16px;
        flex-wrap: wrap;
        justify-content: space-between;
    }

    .flex_col {
        display: flex;
        flex-direction: column;
        flex: 1;
        min-width: 180px;
    }

    .inputs {
        border: 1px solid #cbd5e1;
        border-radius: 10px;
        padding: 10px 12px;
        background: #f8fafc;
        font-size: 0.9rem;
    }

    .inputs[readonly] {
        background: #f1f5f9;
    }

    /* ===== TIMELINE BADGES ===== */
    .timeline_badge {
        display: inline-block;
        background: #2563eb;
        color: #fff;
        padding: 6px 12px;
        border-radius: 12px;
        margin: 4px 4px 4px 0;
        font-size: 0.85rem;
    }

    /* ===== PROGRESS BAR ===== */
    .progress_wrapper {
        background: #e5e7eb;
        border-radius: 10px;
        overflow: hidden;
        height: 20px;
        margin-bottom: 12px;
    }

    .progress_bar {
        height: 100%;
        background: #f97316;
        text-align: right;
        padding-right: 6px;
        color: white;
        font-size: 0.8rem;
        font-weight: 600;
    }

    /* ===== TABLE ===== */
    table {
        width: 100%;
        border-collapse: collapse;
    }

    th {
        background: #1e3a8a;
        color: #fff;
        padding: 12px;
        text-transform: uppercase;
        font-size: 0.8rem;
    }

    td {
        padding: 10px;
        border-bottom: 1px solid #e5e7eb;
        text-align: center;
    }

    tr:nth-child(even) td {
        background: #f8fafc;
    }

    /* ===== MAP ===== */
    #map {
        width: 100%;
        height: 30vh;
        border-radius: 16px;
        margin-top: 12px;
        border: 1px solid #cbd5e1;
    }

    /* ===== MODAL ===== */
    .modal_overlay {
        position: fixed;
        inset: 0;
        background: rgba(15, 23, 42, 0.88);
        display: none;
        justify-content: center;
        align-items: center;
        z-index: 9999;
    }

    .modal_content {
        background: #fff;
        border-radius: 16px;
        width: 80%;
        max-height: 85%;
        padding: 24px;
        overflow-y: auto;
        box-shadow: 0 25px 70px rgba(15, 23, 42, 0.35);
        position: relative;
    }

    .close_modal {
        position: absolute;
        top: 16px;
        right: 22px;
        font-size: 2.6rem;
        color: #0f172a;
        cursor: pointer;
    }

    .close_modal:hover {
        transform: scale(1.15);
    }

    @media(max-width:900px) {
        .flex_row {
            flex-direction: column;
        }

        .flex_col {
            min-width: 100%;
        }
    }
</style>

<!-- ===== STICKY NAV ===== -->
<div class="sticky-nav">
    <a href="#overview">Overview</a>
    <a href="#timeline">Timeline</a>
    <a href="#meters">Meters</a>
    <a href="#maps">Map</a>
    <a href="#notes">Notes</a>
    <a href="#payments">Payments</a>
</div>

<!-- ===== OVERVIEW ===== -->
<div class="section_card blue" id="overview">
    <h1 class="section_title">Jobcard Overview</h1>
    <div class="flex_row">
        <div class="flex_col"><label>JC Number</label><input class="inputs" readonly value="<?= $jobcard['jc_no'] ?>">
        </div>
        <div class="flex_col"><label>Date Created</label><input class="inputs" readonly
                value="<?= $jobcard['date_created'] ?>"></div>
        <div class="flex_col"><label>Action Date</label><input class="inputs" readonly
                value="<?= $jobcard['action_date'] ?>"></div>
        <div class="flex_col"><label>Status</label><input class="inputs" readonly
                value="<?= $jobcard['status'] == 0 ? 'Pending' : 'Completed' ?>"></div>
    </div>
    <div class="flex_row" style="margin-top:16px;">
        <div class="flex_col"><label>User Created</label><input class="inputs" readonly value="<?= $user_created ?>">
        </div>
        <div class="flex_col"><label>User Assigned</label><input class="inputs" readonly value="<?= $user_assigned ?>">
        </div>
        <div class="flex_col"><label>Client Name</label><input class="inputs" readonly
                value="<?= $jobcard['client_name'] ?>"></div>
        <div class="flex_col"><label>Contact Name</label><input class="inputs" readonly
                value="<?= $jobcard['contact_name'] ?>"></div>
    </div>
    <button style="padding: 2vw 7vw;" onclick="window.location.href='jobcard_pdf.php?record_id=<?= $record_id ?>'">PDF</button>
</div>

<!-- ===== TIMELINE ===== -->
<div class="section_card orange" id="timeline">
    <h1 class="section_title">Jobcard Timeline</h1>

    <div style="display: flex; flex-wrap: wrap;">
        <?php if ($timeline->num_rows > 0) {
            $timeline->data_seek(0);
            while ($t = $timeline->fetch_assoc()):
                $label = str_replace("_", " ", $t['type']);
                $time = date("Y-m-d H:i", strtotime($t['date_time']));
                ?>

                <span class="timeline_badge"><?= $label ?> - <?= $time ?></span>
            <?php endwhile;
        } else {
            echo "<p>No timeline events found</p>";
        } ?>
    </div>

</div>

<!-- ===== METERS ===== -->
<div class="section_card blue" id="meters">
    <h1 class="section_title">Meters Progress</h1>
    <?php
    $timeline->data_seek(0);
    $riem = 0;
    $drill = 0;
    $casing = 0;
    $total = 0;
    while ($t = $timeline->fetch_assoc()) {
        if (strpos($t['type'], 'RIEM') !== false) {
            $riem += $t['meters'];
            $total += $t['meters'];
        }
        if (strpos($t['type'], 'DRILLING') !== false) {
            $drill += $t['meters'];
            $total += $t['meters'];
        }
        if (strpos($t['type'], 'CASING') !== false) {
            $casing += $t['meters'];
            $total += $t['meters'];
        }
    }
    $riem_percent = ($total > 0) ? round($riem / $total * 100) : 0;
    $drill_percent = ($total > 0) ? round($drill / $total * 100) : 0;
    $casing_percent = ($total > 0) ? round($casing / $total * 100) : 0;
    ?>
    <label>Riem Meters: <?= $riem ?></label>
    <div class="progress_wrapper">
        <div class="progress_bar" style="width:<?= $riem_percent ?>%"><?= $riem_percent ?>%</div>
    </div>

    <label>Drilling Meters: <?= $drill ?></label>
    <div class="progress_wrapper">
        <div class="progress_bar" style="width:<?= $drill_percent ?>%"><?= $drill_percent ?>%</div>
    </div>

    <label>Casing Meters: <?= $casing ?></label>
    <div class="progress_wrapper">
        <div class="progress_bar" style="width:<?= $casing_percent ?>%"><?= $casing_percent ?>%</div>
    </div>
</div>

<!-- ===== MAP ===== -->
<div class="section_card orange" id="maps">
    <h1 class="section_title">Jobcard Map</h1>
    <input class="inputs" readonly value="<?= $jobcard['drill_co_ordinates'] ?>" id="drill_co_ordinates">
    <div id="map"></div>
</div>

<!-- ===== NOTES ===== -->
<div class="section_card blue" id="notes">
    <h1 class="section_title">Notes</h1>
    <?php if ($notes->num_rows > 0): ?>
        <table>
            <tr>
                <th>Reason</th>
                <th>Note</th>
                <th>Date</th>
                <th>Image</th>
            </tr>
            <?php while ($n = $notes->fetch_assoc()): ?>
                <tr>
                    <td><?= $n['reason'] ?></td>
                    <td><?= $n['note'] ?></td>
                    <td><?= $n['date_time'] ?></td>
                    <td><?php if ($n['image']) { ?><img src='../jobcards/images/<?= $n['image'] ?>'
                                style="width:80px; height:auto;"><?php } ?></td>
                </tr>
            <?php endwhile; ?>
        </table>
    <?php else:
        echo "<p>No notes found</p>";
    endif; ?>
</div>

<!-- ===== PAYMENTS ===== -->
<div class="section_card orange" id="payments">
    <h1 class="section_title">Payments</h1>
    <?php
    $payments_res = $db->query("jobcard_payments", "SELECT * FROM jobcard_payments WHERE jobcard_id={$record_id} ORDER BY record_id ASC");
    if ($payments_res->num_rows > 0): ?>
        <table>
            <tr>
                <th>Payment Method</th>
                <th>User</th>
                <th>Amount</th>
                <th>File</th>
                <th>Date</th>
            </tr>
            <?php while ($p = $payments_res->fetch_assoc()):
                $user_name = $db->query("users", "SELECT username FROM users WHERE record_id={$p['user_id']}")->fetch_assoc()['username'];
                ?>
                <tr>
                    <td><?= strtoupper($p['payment_method']) ?></td>
                    <td><?= $user_name ?></td>
                    <td>R <?= number_format($p['amount'], 2) ?></td>
                    <td>
                        <?php if (!empty($p['file'])): ?>
                            <img src="../jobcards/images/<?= $p['file'] ?>" style="width:80px; height:auto;">
                        <?php else: ?>
                            -
                        <?php endif; ?>
                    </td>
                    <td><?= date("Y-m-d H:i", strtotime($p['date_time'])) ?></td>
                </tr>
            <?php endwhile; ?>
        </table>
    <?php else: ?>
        <p>No payments found for this jobcard.</p>
    <?php endif; ?>
</div>

<!-- ===== MAP SCRIPT ===== -->
<script>
    function parseCoords(inputStr) {
        const match = inputStr.match(/Latitude:\s*(-?\d+\.?\d*),\s*Longitude:\s*(-?\d+\.?\d*)/);
        if (!match) return { lat: 0, lng: 0 };
        return { lat: parseFloat(match[1]), lng: parseFloat(match[2]) };
    }
    function initMap() {
        const pos = parseCoords(document.getElementById("drill_co_ordinates").value);
        const map = new google.maps.Map(document.getElementById("map"), { center: pos, zoom: 18 });
        const marker = new google.maps.Marker({ position: pos, map: map, title: "Job Location" });
    }
</script>
<script async defer
    src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCXu62pAxEnoWh-eXMpYBkGsz_iX-EVm2k&callback=initMap">
    </script>