<?php include "../../../root.class.php";
$html = new html();
$html->add_styles_page();
$db = new db_safeguard();

$jobcard_data_res = $db->query("pump_installation", "SELECT * FROM pump_installation WHERE record_id = '{$_GET['record_id']}'");
$jobcard_data = $jobcard_data_res->fetch_assoc();

$jobcard_history_res = $db->query("jobcards", "SELECT * FROM jobcards WHERE jc_no = '{$jobcard_data['drilling_invoice']}'");
$jobcard_history = $jobcard_history_res->fetch_assoc();

$user_res = $db->query("users", "SELECT * FROM users WHERE record_id = '{$_SESSION['user_id']}'");
$user = $user_res->fetch_assoc();

$current_date = date("Y-m-d H:i", strtotime("+2 Hours"));

?>

<style>

    .notes_popup {
        display: none;
        position: fixed;
        z-index: 1000;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.5);
    }

    .notes_content {
        background: linear-gradient(90deg, #110151, #3331e7);
        margin: 3% auto;
        padding: 20px;
        border-radius: 10px;
        width: 80%;
        height: 85%;
        box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
        position: relative;
        overflow-y: scroll;
    }

    .notes_images {
        width: 10vw;
        height: 10vw;
    }

    .close-btn {
        position: absolute;
        top: 10px;
        right: 15px;
        font-weight: bolder;
        font-size: 5vw;
        cursor: pointer;
        color: white;
    }

    table {
        width: 95%;
        border-collapse: collapse;
    }

    th {
        padding: 10px;
        border: 3px solid black;
        text-align: left;
        background-color: white;

        @media all and (min-width: 651px) and (max-width: 1050px) {
            font-size: 1.5em;
        }
    }

    td {
        padding: 10px;
        border: 3px solid black;
        text-align: left;
        background-color: white;

        @media all and (min-width: 651px) and (max-width: 1050px) {
            font-size: 1.5em;
        }
    }

    @media all and (min-width: 651px) and (max-width: 1050px) {

        .notes_content {
            width: 90%;
            height: 95%;
        }

        .close-btn {
            top: 0px;
            font-size: 15vw;
        }
    }

    @media (min-width: 651px) and (max-width: 1050px) {
        .save_sign_btn {
            position: relative;
            font-size: 2em;
            cursor: pointer;
            border: 3px solid navy;
            background: white;
            color: black;
            border-radius: 15px;
            padding: 1.5vw;
            height: 15vw;
            width: 55vw;
            text-align: center;
        }

        .signature_form {
            display: flex;
            flex-direction: column;
            align-items: center;
            background: white;
            /* justify-content: space-around; */
            flex-wrap: wrap;
            align-content: space-around;
            /* height: 210vw; */
            border-radius: 3vw;
        }

        .div_signatures {
            position: relative;
            display: flex;
            flex-direction: column;
            width: 100%;
            justify-content: space-around;
            width: fit-content;
            /* margin-top: 30vh; */
            /* margin-bottom: 30vh; */
        }

        .history_div {
            display: flex;
            flex-direction: column;
            align-items: center;
            background: white;
            /* justify-content: space-around; */
            flex-wrap: wrap;
            align-content: space-around;
            /* height: 210vw; */
            border-radius: 3vw;
            margin: 1vw;
            padding: 4vw;
        }

        .install_div {
            display: flex;
            flex-direction: column;
            align-items: center;
            background: white;
            /* justify-content: space-around; */
            flex-wrap: wrap;
            align-content: space-around;
            /* height: 210vw; */
            border-radius: 3vw;
            margin: 1vw;
            padding: 4vw;
        }
    }

    video,canvas {
        width: 400px;
        height: 300px;
        border: 3px solid #ccc;
        border-radius: 2vw;
        margin-top: 10px;
    }

    @media all and (max-width: 600px) {

        video,canvas {
            width: 600px;
            height: 450px;
            margin-top: -5vw;
        }
    }
</style>

<div class="notes_popup" id="notes_popup">
    <div class="notes_content">
        <span class="close-btn" onclick="close_notesPopup()">&times;</span>

        <?php
            $res_data = $db->query("jobcard_timeline", "SELECT * FROM jobcard_timeline WHERE jobcard_id = '{$_GET['jobcard_no']}' ORDER BY record_id DESC LIMIT 1");
            $data = $res_data->fetch_assoc();
        ?>

        <input type="text" class="inputs" value="<?php echo $data['type'] ?>" readonly hidden/>
        <input type="text" class="inputs" name="jobcard_no" id="jobcard_no" value="<?php echo $_GET['jobcard_no']; ?>" readonly hidden/>

        <label for="notes" class="notes_heading" style="color: white;margin:1px;">NOTES</label>

        <div style="display: flex; flex-direction: column;">
            <label for="reasons" class="big_labels" style="color: white;">REASONS</label>
            <select id="reason" name="reason" class="big_inputs">
                <option value="">--SELECT--</option>
                <option value="ARRIVED AT LOCATION">ARRIVED AT LOCATION</option>
                <option value="WAITING FOR CLIENT">WAITING FOR CLIENT</option>
                <option value="TRAVELING TO SITE">TRAVELING TO SITE</option>
                <option value="ARRIVED ON SITE">ARRIVED ON SITE</option>
                <option value="TALKING TO CLIENT">TALKING TO CLIENT</option>
                <option value="ARRIVED ON SITE">ARRIVED ON SITE</option>
                <option value="TALKING TO CLIENT">TALKING TO CLIENT</option>
                <option value="FETCHING MONEY">FETCHING MONEY</option>
                <option value="BRAKING">BRAKING</option>
                <option value="CHANGING RIEMER">CHANGING RIEMER</option>
                <option value="STOP">STOP</option>
                <option value="PENDING">PENDING</option>
                <option value="START">START</option>
                <option value="INSTALLING">INSTALLING</option>
                <option value="RECEIVED">RECEIVED</option>
                <option value="BACK TO WORKSHOP">BACK TO WORKSHOP</option>
                <option value="OTHER">OTHER</option>
            </select>

            <label for="notes" class="big_labels" style="color: white">NOTES</label>
        </div>

        <div id="normal_section" style="display: flex; flex-direction: column; align-items: center;">
            <textarea name="note" id="note" class="inputs" style="width: 70vw; font-size: 3em;" rows="5"></textarea>
            <label for="reasons" class="big_labels" style="color: white;">UPLOAD TYPE</label>
            <select id="image_type" name="image_type" onchange="file_camera_type()" class="big_inputs">
                <option></option>
                <option value="file">ATTACH FILE</option>
                <option value="camera">CAMERA</option>
            <select>

                <style>
                    video,
                    canvas {
                        width: 400px;
                        height: 300px;
                        border: 3px solid #ccc;
                        border-radius: 2vw;
                        margin-top: 10px;
                    }

                    @media all and (max-width: 600px) {

                        video,
                        canvas {
                            width: 600px;
                            height: 450px;
                            margin-top: -5vw;
                        }
                    }
                </style>

            <div style="background-color: white; padding: 2vw; display: flex; flex-direction: column; align-items: center;">
                <div id="attach_file_div" style="display:none; flex-direction: column; align-items: center;">
                    <label for="proof" class="big_labels">ATTACH FILE</label>
                    <input type="file" name="attach_note" id="attach_note" style="width: 90%;" class="big_inputs" onchange="upload_file()">
                </div>

                <div id="camera_div" style="display:none; flex-direction: column; align-items: center;">
                    <video style="display: none;" id="camera_notes" autoplay playsinline></video>
                    <br>

                    <button id="open_camera_notes" class="submit_btn"
                        onclick="open_notes_Camera()">Open
                        Camera</button>

                    <div id="load_camera_notes"
                        style="display: none; width: 100%; justify-content: center;">
                        <button class="submit_btn" onclick="capture_notes_Photo()">Capture
                            Photo</button>
                        <button class="submit_btn" onclick="stop_notes_Camera()">Stop
                            Camera</button>
                    </div>

                    <div id="captured_image_notes" style="display:none">
                        <h3>Captured Image:</h3>
                        <canvas id="snapshot_notes"></canvas>
                    </div>

                    <script>
                        let stream_notes;

                        async function open_notes_Camera() {
                            const video = document.getElementById("camera_notes");
                            const load_camera = document.getElementById("load_camera_notes");
                            const open_camera = document.getElementById("open_camera_notes");

                            try {

                                stream_notes = await navigator.mediaDevices.getUserMedia({
                                    video: { facingMode: "environment" },
                                    audio: false
                                });

                                const video = document.getElementById("camera_notes");
                                video.srcObject = stream_notes;
                                video.style.display = "block";

                                load_camera.style.display = "flex";
                                open_camera.style.display = "none";


                            } catch (error) {
                                alert("Error accessing camera: " + error.message);
                            }
                        }

                        function stop_notes_Camera() {
                            const open_camera = document.getElementById("open_camera_notes");
                            const load_camera = document.getElementById("load_camera_notes");
                            const video = document.getElementById("camera_notes");

                            video.style.display = "none";
                            load_camera.style.display = "none";
                            open_camera.style.display = "block";
                            if (stream_notes) {
                                stream_notes.getTracks().forEach(track => track.stop());
                                stream_notes = null;
                                document.getElementById("camera_notes").srcObject = null;
                            }
                        }

                        function capture_notes_Photo() {
                            const video = document.getElementById("camera_notes");
                            const canvas = document.getElementById("snapshot_notes");
                            const context = canvas.getContext("2d");
                            const captured_image = document.getElementById("captured_image_notes");
                            const load_camera = document.getElementById("load_camera_notes");
                            const jobcard_no = "<?php echo $_GET['jobcard_no']; ?>";

                            load_camera.style.display = "none";
                            canvas.width = video.videoWidth;
                            canvas.height = video.videoHeight;
                            context.drawImage(video, 0, 0, canvas.width, canvas.height);

                            captured_image.style.display = "none";

                            const imageData = canvas.toDataURL("image/png");
                            // console.log("Captured image data:", imageData);

                            stop_notes_Camera();
                            save_notes_CapturedImage(imageData, jobcard_no);
                        }

                        function save_notes_CapturedImage(imageData, jobcard_no) {
                            const video = document.getElementById("camera_notes");
                            const folder_path = "/notes/";
                            const section_name = "notes";

                            video.style.display = "none";

                            var formData = new FormData();

                            formData.append('image', imageData);
                            formData.append('jobcard_no', jobcard_no);
                            formData.append('folder_path', folder_path);
                            formData.append('section_name', section_name);

                            const xhr = new XMLHttpRequest();
                            xhr.open('POST', '../pump/save_camera.php', true);
                            xhr.onreadystatechange = function () {
                                if (xhr.readyState == 4 && xhr.status == 200) {
                                    const response = xhr.responseText.trim();
                                    // FIX: previously used || which made the check always true
                                    if (response !== '0' && response !== '') {
                                        console.log('fileName: ' + response);
                                        alert('Photo saved successfully!');

                                        document.getElementById('image').style.display = 'block';
                                        document.getElementById('image').value = response;
                                    } else {
                                        alert('Error saving photo!');
                                    }
                                }
                            };
                            xhr.send(formData);
                        }
                    </script>
                </div>
            </div>

            <input type="text" id="image" name="image" style="display: none;"/>

            <button type="button" class="submit_btn" onclick="add_notes()">ADD</button>

        </div>


        <div id="note_save_response" style="color:white; margin-top:10px; font-weight:bold;"></div>
            <div
            style="display:flex; flex-direction: column; align-items: center; background-color: white; padding: 2vw 2vw 2vw 4vw; width: 100%; margin-top:20px; overflow-x: auto; box-sizing: border-box;" id="notes_table">
            </div>
        </div>
    </div>
    <script>

        function file_camera_type(){
            var image_type = document.getElementById("image_type").value;

            if (image_type == "file") {
                document.getElementById("attach_file_div").style.display = "flex";
                document.getElementById("camera_div").style.display = "none";
            } else if (image_type == "camera") {
                document.getElementById("attach_file_div").style.display = "none";
                document.getElementById("camera_div").style.display = "flex";
            } else {
                document.getElementById("attach_file_div").style.display = "none";
                document.getElementById("camera_div").style.display = "none";
            }
        }

        function upload_file() {
            var attach_note = document.getElementById("attach_note");
            var file = attach_note.files[0];
            var jobcard_no = "<?php echo $_GET['jobcard_no']; ?>";

            if (file) {
                var formData = new FormData();
                formData.append('file', file);
                formData.append('jobcard_no', jobcard_no);
                formData.append('ajax_type', "note_section");
                formData.append('section_name', "notes");
                formData.append('file_save_path', "../pump/notes/");

                var xhr = new XMLHttpRequest();
                xhr.onreadystatechange = function () {
                    if (xhr.readyState === 4) {
                        if (xhr.status === 200 && xhr.responseText.includes("OK")) {
                            var filename = xhr.responseText.replace('OK | ', '').trim();

                            var uploadedFileInput = document.getElementById('uploaded_file_name');
                            if (!uploadedFileInput) {
                                uploadedFileInput = document.createElement('input');
                                uploadedFileInput.type = 'hidden';
                                uploadedFileInput.id = 'uploaded_file_name';
                                uploadedFileInput.name = 'uploaded_file_name';
                                document.getElementById('file_div').appendChild(uploadedFileInput);
                            }
                            uploadedFileInput.value = filename;
                            document.getElementById('image').value = filename;
                            alert("File uploaded successfully!");
                        } else {
                            alert('Error uploading file! Try again.');
                        }
                    }
                };
                xhr.open("POST", "../pump/upload_slip.php", true);
                xhr.send(formData);
            }
        }

        function loadNotes() {
            var jobcard_id = document.getElementById("jobcard_no").value;

            var xhr = new XMLHttpRequest();
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    document.getElementById("notes_table").innerHTML = xhr.responseText;
                }
            };
            xhr.open("POST", "../pump/notes_table.ajax.php", true);
            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            xhr.send("jobcard_id=" + encodeURIComponent(jobcard_id));
        }

        loadNotes();

        function add_notes() {
            var jobcard_no  = document.getElementById("jobcard_no").value;
            var reason      = document.getElementById("reason").value;
            var note        = document.getElementById("note").value;
            var image       = document.getElementById("image").value;

            if (reason === "") {
                alert("Please select a reason.");
                return false;
            }

            if (note.trim() === "") {
                alert("Please enter a note.");
                return false;
            }

            var form = new FormData();
            form.append("jobcard_no", jobcard_no);
            form.append("reason", reason);
            form.append("note", note);
            form.append("image", image);

            var xhr = new XMLHttpRequest();
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    if (xhr.responseText.trim() === "success") {
                        // Clear inputs
                        document.getElementById("reason").value = "";
                        document.getElementById("note").value   = "";
                        document.getElementById("image").value  = "";
                        document.getElementById("attach_note").value  = "";
                        document.getElementById("camera_div").style.display = "none";
                        document.getElementById("attach_file_div").style.display = "none";
                        document.getElementById("image").style.display = "none";

                        stop_notes_Camera();
                        loadNotes(); // 👈 refresh the notes table
                    } else {
                        console.log(xhr.responseText);
                        alert("Error saving note, please try again.");
                    }
                }
            };
            xhr.open("POST", "../pump/save_notes.ajax.php", true);
            xhr.send(form);
        }
    </script>
</div>

<?php

$res_data = $db->query("jobcard_timeline", "SELECT * FROM jobcard_timeline WHERE jobcard_id = '{$jobcard_data['jobcard_no']}' ORDER BY record_id DESC LIMIT 1");

// echo "SELECT * FROM jobcard_timeline WHERE jobcard_id = '{$jobcard_data['jobcard_no']}' ORDER BY record_id DESC LIMIT 1";
$data = $res_data->fetch_assoc();

if ($res_data->num_rows == 0 || $data['type'] == "DEPARTURE" || $data['type'] == "ARRIVED") {

    $res_arrival = $db->query("jobcard_timeline", "SELECT * FROM jobcard_timeline WHERE jobcard_id = '{$_GET['jobcard_no']}' ORDER BY record_id DESC");

    $has_departed = false;
    $has_arrived = false;

    if ($res_arrival->num_rows > 0) {
        while ($current_status = $res_arrival->fetch_assoc()) {

            if ($current_status['type'] == "DEPARTURE") {
                $has_departed = true;
            }

            if ($current_status['type'] == "ARRIVED") {
                $has_arrived = true;
            }
        }
    }

    if ($has_departed && $has_arrived) {
        $current_jc_status = new input();
        $current_jc_status->value("DEPARTED AND ARRIVED");
        $current_jc_status->readonly();
        $current_jc_status->class("inputs");
        $current_jc_status->type("hidden");
        $current_jc_status->id("jc_current_status");
        $current_jc_status->onchange("check_status()");
        $current_jc_status->add();

        ?>

        <div class="history_div">
            <h2 class="create_h2">JOCARD HISTORY</h2><br>
            <div style="display: flex; flex-direction: column; width: 100%; align-items: center;">
                <label for="jobcard_id_label" class="create_details_label" style="width: 100%;">JOBCARD ID : </label>
                <input class="create_details_input" value="<?php echo $jobcard_history['jc_no']; ?>" readonly>
            </div>
            <div style="display: flex; flex-direction: column; width: 100%; align-items: center;">
                <label for="client_name_label" class="create_details_label" style="width: 100%;">CLIENT NAME : </label>
                <input class="create_details_input" value="<?php echo $jobcard_history['client_name']; ?>" readonly>
                <input class="create_details_input" value="<?php echo $_SESSION['user_id']; ?>" id="user_id" readonly hidden>
            </div>
            <div style="display: flex; flex-direction: column; width: 100%; align-items: center;">
                <label for="address_label" class="create_details_label" style="width: 100%;">ADDRESS : </label>
                <input class="create_details_input" value="<?php echo $jobcard_history['address']; ?>" readonly>
            </div>
            <div style="display: flex; flex-direction: column; width: 100%; align-items: center;">
                <label for="contact_no_label" class="create_details_label" style="width: 100%;">CONTACT NUMBER : </label>
                <input class="create_details_input" value="<?php echo $jobcard_history['contact_number']; ?>" readonly>
            </div>
            <div style="display: flex; flex-direction: column; width: 100%; align-items: center;">
                <label for="other_no_label" class="create_details_label" style="width: 100%;">OTHER NUMBER : </label>
                <input class="create_details_input" value="<?php echo $jobcard_history['other_number']; ?>" readonly>
            </div>
            <div style="display: flex; flex-direction: column; width: 100%; align-items: center;">
                <label for="alternate_no_label" class="create_details_label" style="width: 100%;">ALTERNATE NUMBER : </label>
                <input class="create_details_input" value="<?php echo $jobcard_history['alternate_number']; ?>" readonly>
            </div>
            <div style="display: flex; flex-direction: column; width: 100%; align-items: center;">
                <label for="break_found_label" class="create_details_label" style="width: 100%;">BREAK FOUND ON : </label>
                <input class="create_details_input" value="<?php echo $jobcard_history['break_found_on']; ?>" readonly>
            </div>
            <div style="display: flex; flex-direction: column; width: 100%; align-items: center;">
                <label for="water_strike_label" class="create_details_label" style="width: 100%;">WATER STRIKE : </label>
                <input class="create_details_input" value="<?php echo $jobcard_history['water_strike']; ?>" readonly>
            </div>
            <div style="display: flex; flex-direction: column; width: 100%; align-items: center;">
                <label for="water_flow_label" class="create_details_label" style="width: 100%;">WATER FLOW : </label>
                <input class="create_details_input" value="<?php echo $jobcard_history['water_flow']; ?>" readonly>
            </div>

            <?php
            //get the total meters drilled from the drilling jobcard
            $drilling_jobcard_res = $db->query("jobcard_timeline", "SELECT * FROM jobcard_timeline WHERE jobcard_id = '{$jobcard_history['record_id']}'");
            $drilling_jobcard = $drilling_jobcard_res->fetch_assoc();

            $total_meters = 0;
            if ($drilling_jobcard_res->num_rows > 0) {
                while ($current_record = $drilling_jobcard_res->fetch_assoc()) {
                    if ($current_record['type'] == "DRILLING_STOP" || $current_record['type'] == "DRILLING_PAUSE" || $current_record['type'] == "RIEMING_STOP" || $current_record['type'] == "RIEMING_PAUSE" || $current_record['type'] == "BLASTING_STOP" || $current_record['type'] == "BLASTING_PAUSE" || $current_record['type'] == "CASING_STOP" || $current_record['type'] == "CASING_PAUSE") {
                        $total_meters += $current_record['meters'];
                    }
                }
            }
            ?>

            <div style="display: flex; flex-direction: column; width: 100%; align-items: center;">
                <label for="total_meters_label" class="create_details_label" style="width: 100%;">TOTAL METERS DRILLED :
                </label>
                <input class="create_details_input" value="<?php echo $total_meters; ?>" readonly>
            </div>
        </div>

        <div style="background-color: rgb(255 255 255 / 87%); ">
            <h1 class="heading_h1">PAYMENTS</h1><br>
                <div style="padding: 2vw; background-color: navy; width: 95%;">
                    <div style="width: 98%; display: flex; flex-direction: column;">
                        <div id="payment_history_table" style="display: flex; flex-direction: column;width: 98%;justify-content: center; padding: 1vw; background-color: whitesmoke;">
                    </div>

            <div id="payments" style='display:flex; flex-direction: column; width: 100%; align-items: center; background-color: whitesmoke; padding: 1vw;'>
                <label for="payment" class="big_labels">PAYMENT TYPE</label>
                <select id="payment_method" name="payment_method" class="big_inputs" onchange="payment_type()" style="width: 90%;">
                    <option>Payment Method</option>
                    <option value="CASH">CASH</option>
                    <option value="EFT">EFT</option>
                </select>

                <div id='eft' style='display: none; flex-direction: column; align-items: center;'>
                    <label for="eft_type" class="big_labels">TYPE</label>
                    <!-- Add this as a new option in your EFT type dropdown -->

                    <select name="eft_type" id="eft_type" onchange="eft_option()" class="big_inputs"
                    style="width: 90%;">
                        <option value=""></option>
                        <option value="FILE">ATTACH FILE</option>
                        <option value="CAMERA">OPEN CAMERA</option>
                    </select>

                    <div id="file_div" style="display:none; flex-direction: column; align-items: center;">
                        <label for="proof" class="big_labels">Insert Payment Proof</label>
                        <input type="file" name="payment_proof" id="payment_proof" style="width: 90%;"
                            class="big_inputs" onchange="upload_file_ajax()">
                        <span id="upload_status" style="font-size:13px; margin-top:5px; color:gray;"></span>
                        <!-- FIXED: Static hidden input — no longer created dynamically -->
                        <input type="hidden" id="uploaded_file_name" name="uploaded_file_name" value="">
                    </div>

                    <div id="camera_div" style="display:none; flex-direction: column; align-items: center;">
                        <style>
                            video,
                            canvas {
                                width: 400px;
                                height: 300px;
                                border: 3px solid #ccc;
                                border-radius: 2vw;
                                margin-top: 10px;
                            }

                            @media all and (max-width: 600px) {

                                video,
                                canvas {
                                    width: 600px;
                                    height: 450px;
                                    margin-top: -5vw;
                                }
                            }
                        </style>

                        <video style="display: none;" id="camera_slip" autoplay playsinline></video>
                        <br>

                        <button id="open_camera_slip" class="submit_btn" onclick="openSlipCamera()">Open
                        Camera</button>

                        <div id="load_camera_slip" style="display: none; width: 100%; justify-content: center;">
                            <button class="submit_btn" onclick="captureSlipPhoto()">Capture Photo</button>
                            <button class="submit_btn" onclick="stopSlipCamera()">Stop Camera</button>
                        </div>

                        <div id="captured_image_slip" style="display:none">
                            <h3>Captured Image:</h3>
                            <canvas id="snapshot_slip"></canvas>
                        </div>

                        <script>
                            let stream_slip;

                            async function openSlipCamera() {
                                const video = document.getElementById("camera_slip");
                                const load_camera = document.getElementById("load_camera_slip");
                                const open_camera = document.getElementById("open_camera_slip");

                                try {

                                    stream_slip = await navigator.mediaDevices.getUserMedia({
                                            video: { facingMode: "environment" },
                                            audio: false
                                        });

                                    const video = document.getElementById("camera_slip");
                                    video.srcObject = stream_slip;
                                    video.style.display = "block";

                                    load_camera.style.display = "flex";
                                    open_camera.style.display = "none";

                                } catch (error) {
                                    alert("Error accessing camera: " + error.message);
                                }
                            }

                            function captureSlipPhoto() {
                                const video = document.getElementById("camera_slip");
                                const canvas = document.getElementById("snapshot_slip");
                                const context = canvas.getContext("2d");
                                const captured_image = document.getElementById("captured_image_slip");
                                const load_camera = document.getElementById("load_camera_slip");
                                const jobcard_no = "<?php echo $_GET['jobcard_no']; ?>";

                                load_camera.style.display = "none";
                                canvas.width = video.videoWidth;
                                canvas.height = video.videoHeight;
                                context.drawImage(video, 0, 0, canvas.width, canvas.height);

                                captured_image.style.display = "none";

                                const imageData = canvas.toDataURL("image/png");

                                stopSlipCamera();
                                saveCapturedSlipImage(imageData, jobcard_no);
                            }

                            function stopSlipCamera() {
                                const open_camera = document.getElementById("open_camera_slip");
                                const load_camera = document.getElementById("load_camera_slip");
                                const video = document.getElementById("camera_slip");

                                video.style.display = "none";
                                load_camera.style.display = "none";
                                open_camera.style.display = "block";
                                if (stream_slip) {
                                    stream_slip.getTracks().forEach(track => track.stop());
                                    stream_slip = null;
                                    document.getElementById("camera_slip").srcObject = null;
                                }
                            }

                            function saveCapturedSlipImage(imageData, jobcard_no) {
                                const video = document.getElementById("camera_slip");
                                const folder_path = "../pump/slips/";
                                const section_name = "slip";

                                video.style.display = "none";

                                var formData = new FormData();

                                formData.append('image', imageData);
                                formData.append('jobcard_no', jobcard_no);
                                formData.append('folder_path', folder_path);
                                formData.append('section_name', section_name);

                                const xhr = new XMLHttpRequest();
                                xhr.open('POST', '../pump/save_camera.php', true);
                                xhr.onreadystatechange = function () {
                                    if (xhr.readyState == 4 && xhr.status == 200) {
                                        if (xhr.responseText != '0') {
                                            console.log('fileName: ' + xhr.responseText);
                                            alert('Photo saved successfully!');
                                            if ('slip' != '') {
                                                document.getElementById('slip_file').style.display = 'block';
                                                document.getElementById('slip_file').value = xhr.responseText;
                                            }
                                        } else {
                                            alert('Error saving photo!');
                                        }
                                    }
                                };
                                xhr.send(formData);
                            }
                        </script>

                        <input type='text' style="display: none; width: 90%;" class="inputs" id='slip_file'
                        name='slip_file'>
                </div>
            </div>

            <div id='cash' style='display: none; flex-direction: column; align-items: center;'>
                <label for="amount" class="big_labels">Amount</label>
                <input type="text" class="big_inputs" name="cash_amount" id="cash_amount" placeholder="AMOUNT" style="width: 90%;" />
                <button class="submit_btn" onclick="complete_payment()">SEND PAYMENT</button>
            </div>

            <div style="display: flex; flex-direction: column;align-items: center;width: 100%;">

            </div>

            <script>
                function payment_type() {
                    var payment = document.getElementById("payment_method").value;

                    if (payment == "EFT") {
                        document.getElementById("eft").style.display = "flex";
                        document.getElementById("cash").style.display = "flex";
                    } else if (payment == "CASH") {
                        document.getElementById("cash").style.display = "flex";
                        document.getElementById("eft").style.display = "none";
                    } else {
                        document.getElementById("cash").style.display = "none";
                        document.getElementById("eft").style.display = "none";
                    }
                }

                function eft_option() {
                    var select = document.getElementById("eft_type");
                    var file_div = document.getElementById("file_div");
                    var camera_div = document.getElementById("camera_div");

                    if (select.value === "FILE") {
                        file_div.style.display = "flex";
                        camera_div.style.display = "none";
                    } else if (select.value === "CAMERA") {
                        file_div.style.display = "none";
                        camera_div.style.display = "flex";
                    } else {
                        file_div.style.display = "none";
                        camera_div.style.display = "none";
                    }
                }

                // ─── Upload state tracker ───────────────────────────────────────────────────
                var uploadInProgress = false;
                var uploadComplete   = false;

                function upload_file_ajax() {
                    var payment_proof = document.getElementById("payment_proof");
                    var file          = payment_proof.files[0];
                    var jobcard_no    = "<?php echo $_GET['jobcard_no']; ?>";
                    var statusEl      = document.getElementById("upload_status");
                    var hiddenInput   = document.getElementById("uploaded_file_name");

                    // Reset state on new file selection
                    uploadComplete = false;
                    hiddenInput.value = "";

                    if (!file) return;

                    uploadInProgress = true;
                    statusEl.style.color = "gray";
                    statusEl.textContent  = "⏳ Uploading…";

                    var formData = new FormData();
                    formData.append('file',           file);
                    formData.append('jobcard_no',     jobcard_no);
                    formData.append('ajax_type',      "lead_payment_slip");
                    formData.append('section_name',   "slip");
                    formData.append('file_save_path', "../jobcards/pump/slips/");

                    var xhr = new XMLHttpRequest();

                    xhr.onreadystatechange = function () {
                        if (xhr.readyState === 4) {
                            uploadInProgress = false;

                            if (xhr.status === 200 && xhr.responseText.includes("OK")) {
                                // Extract filename — handles "OK | filename.jpg" or just "filename.jpg"
                                var filename = xhr.responseText.replace(/^OK\s*\|\s*/i, '').trim();

                                if (filename === "") {
                                    statusEl.style.color = "red";
                                    statusEl.textContent  = "⚠ Upload succeeded but no filename returned.";
                                    console.error("Server returned OK but no filename:", xhr.responseText);
                                    return;
                                }

                                hiddenInput.value = filename;
                                uploadComplete    = true;

                                statusEl.style.color = "green";
                                statusEl.textContent  = "✔ Uploaded: " + filename;
                                console.log("Uploaded filename stored:", filename);

                            } else {
                                uploadComplete = false;
                                statusEl.style.color = "red";
                                statusEl.textContent  = "✖ Upload failed. Try again.";
                                console.error("Upload error:", xhr.responseText);
                            }
                        }
                    };

                    xhr.open("POST", "../pump/upload_slip.php", true);
                    xhr.send(formData);
                }

                function complete_payment() {
                    var payment = document.getElementById("payment_method").value;
                    var eft_type = document.getElementById("eft_type").value;
                    var user_id = "<?= $_SESSION['user_id'] ?>";
                    var record_id  = "<?= $_GET['jobcard_no'] ?>";

                    if (payment == "") {
                        alert("Please select Payment Method");
                        return false;
                    }

                    var amount = document.getElementById("cash_amount").value;
                    if (amount.trim() === "" || isNaN(amount) || amount <= 0) {
                        alert("Please enter a valid Amount Paid");
                        return false;
                    }

                    var formData = new FormData();
                    formData.append('record_id', record_id);
                    formData.append('payment_method', payment);
                    formData.append('amount', amount);
                    formData.append('user_id', user_id);

                    if (payment === "EFT") {
                        if (eft_type === "CAMERA") {
                            var slip_input = document.getElementById("slip_file").value;
                            if (slip_input === "" || slip_input.trim() === "") {
                                alert("Please capture Slip Image");
                                return false;
                            }
                            formData.append('file', slip_input);

                        } else if (eft_type === "FILE") {
                            var uploaded_filename = document.getElementById("uploaded_file_name");
                            if (!uploaded_filename || uploaded_filename.value === "") {
                                alert("Please upload a file first.");
                                return false;
                            }
                            formData.append('file', uploaded_filename.value);

                        } else {
                            alert("Please select how you want to provide payment proof.");
                            return false;
                        }
                    }

                                // Continue with existing AJAX submission code...
                                const xhr = new XMLHttpRequest();
                                xhr.open('POST', '../jobcard_payments.ajax.php', true);
                                xhr.onreadystatechange = function () {
                                    if (xhr.readyState === 4) {
                                        if (xhr.status === 200 && xhr.responseText.includes("OK")) {
                                            console.log(`PAYMENT SUCCESS: ${xhr.responseText}`);
                                            alert('Payment completed successfully!');

                                            document.getElementById("cash_amount").value = "";
                                            document.getElementById("slip_file").value = "";
                                            document.getElementById("payment_proof").value = "";

                                            if (document.getElementById("uploaded_file_name")) {
                                                document.getElementById("uploaded_file_name").value = "";
                                            }

                                            document.getElementById("payment_method").selectedIndex = 0;
                                            document.getElementById("eft_type").selectedIndex = 0;
                                            document.getElementById("cash").style.display = "none";
                                            document.getElementById("eft").style.display = "none";

                                            loadPaymentHistory();
                                        } else {
                                            console.log(`Error saving PAYMENT: ${xhr.responseText}`);
                                            alert('Error completing payment! Try again.');
                                            return false;
                                        }
                                    }
                                };
                                xhr.send(formData);
                            }

                function loadPaymentHistory() {
                    var jobcard_no = "<?php echo $_GET['jobcard_no']; ?>";

                    var xhr = new XMLHttpRequest();
                    xhr.onreadystatechange = function () {
                        if (xhr.readyState === 4 && xhr.status === 200) {
                            document.getElementById("payment_history_table").innerHTML = xhr.responseText;
                        }
                    };

                    xhr.open("POST", "../pump/payment_history.ajax.php", true);
                    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                    xhr.send("jobcard_no=" + encodeURIComponent(jobcard_no));
                }

                // Load history on page load
                document.addEventListener("DOMContentLoaded", loadPaymentHistory);

                loadPaymentHistory();
            </script>
            </div>

            </div>
        </div>

        <div class="signature_form" id="signatures" style="padding: 4vw; margin: 3vw 1vw; height: 130vh;">
            <h1 class="sign_h1">SIGNATURES</h1>
            <div class="list_inputs">
                Please Note: Savuki Drilling Mpumalanga
                <ul>
                    <li>1. Cannot be held responsible for any damage or borehole collapse.</li>
                    <li>2. Steel casings must be installed on the recommendation of the drill team.</li>
                    <li>3. Will not be held liable for any damage on property.</li>
                    <li>4. No water is guaranteed even if Savuki Drilling surveyed.</li>
                    <li>5. Client pays for service of drilling, not water.</li>
                </ul>
                <b><i>SAFETY PRECAUTION - <br> CUSTOMER IS RESPONSIBLE FOR COVERING OF BOREHOLE AFTER DRILLING.<br> SAVUKI
                DRILLING MPUMALANGA WILL NOT BE LIABLE FOR ANY ACCIDENTS CAUSED BY ANY UNCOVERED BOREHOLES.</i></b>
            </div>

            <input type="text" id="jobcard_id" name="jobcard_id" value="<?php echo $jobcard_data['jobcard_no']; ?>" hidden>

            <div class='div_signatures'>
                <div class="sub_down">

                    <?php

                        $target_dir = __DIR__ . "/signatures/";
                        $target_url = "/app/jobcards/pump/signatures/";

                        $employee_flie = $target_dir . "employee-jc_" . $_GET['jobcard_no'] . "-" . $_SESSION['user_id'] . "-signature.png";
                        $employee_url = $target_url . "employee-jc_" . $_GET['jobcard_no'] . "-" . $_SESSION['user_id'] . "-signature.png";

                        // EMPLOYEE SIGNATURE
                        if (file_exists($employee_flie)) {
                            ?>
                                <div class='jobcard_work_signature' style='margin-bottom:1vw;'>
                                <h2 style="font-size: 3em;">EMPLOYEE SIGNATURE</h2>
                                <input type='image' src='<?php echo $employee_url; ?>' alt='employee signature' class="signature_image">
                                </div>
                            <?php
                        } else {
                            ?>
                                <div class='jobcard_work_signature' style='margin-bottom:1vw;'>
                                <h2 style="font-size: 3em;">EMPLOYEE SIGNATURE</h2>
                                <canvas id="employee_signature" class="signature-pad"></canvas>
                                <div style="display:flex;gap:10px;">
                                <button type="button" id="clear_employee_signature" class="sign_btn">CLEAR</button>
                                </div>
                                </div>
                            <?php
                        }

                        // CLIENT SIGNATURE
                        $client_file = $target_dir . "client-jc_" . $_GET['jobcard_no'] . "-" . $_SESSION['user_id'] . "-signature.png";
                        $client_url = $target_url . "client-jc_" . $_GET['jobcard_no'] . "-" . $_SESSION['user_id'] . "-signature.png";

                        if (file_exists($client_file)) {
                            ?>
                                <div class='jobcard_work_signature' style='margin-bottom:1vw;'>
                                <h2 style="font-size: 3em;">CLIENT SIGNATURE</h2>
                                <input type="image" src="<?php echo $client_url; ?>" alt="client signature" class="signature_image">
                                </div>
                            <?php
                        } else {
                            ?>
                                <div class='jobcard_work_signature' style='margin-bottom:1vw;'>
                                <h2 style="font-size: 3em;">CLIENT SIGNATURE</h2>
                                <canvas id="client_signature" class="signature-pad"></canvas>
                                <div style="display:flex;gap:10px;">
                                <button type="button" id="clear_client_signature" class="sign_btn">CLEAR</button>
                                </div>
                                </div>
                            <?php
                        }
                    ?>

                    <div style="margin-top: 40vw;">
                        <?php
                            if (
                                !file_exists("../jobcards/pump/signatures/employee-jc" . $_GET['jobcard_no'] . "-" . $_SESSION['user_id'] . "-signature.png") ||
                                !file_exists("../jobcards/pump/signatures/client-jc" . $_GET['jobcard_no'] . "-" . $_SESSION['user_id'] . "-signature.png")
                            ) {
                                echo "<button type='button' id='save_signatures' class='save_sign_btn' >SAVED</button>";
                            }
                        ?>
                    </div>
                </div>
            </div>
        </div>

        <div
        style="background-color: rgb(255 255 255 / 87%); height: fit-content; width: 98%; display: flex; flex-direction: column; margin-top: 1vw; margin-bottom: 2vw; border-radius: 2vw; align-items: center; padding-bottom: 2vw;">
            <h2 class="heading_h2">MAP</h2>
            <?php
                $res_jobcard = $db->query("pump_installation", "SELECT * FROM pump_installation WHERE record_id = {$_GET['record_id']} ORDER BY record_id DESC");
                $jobcard_data = $res_jobcard->fetch_assoc();

                //split the string with a comma
                $lat = explode(", ", $jobcard_data['map_co_ordinates'])[0];
                $long = explode(", ", $jobcard_data['map_co_ordinates'])[1];
            ?>
            <button class="submit_btn" onclick="getLocation()">GET LOCATION</button>
            <div id="map_loader" style="display:none;">
                <div class="spinner"></div>
                <div>Getting location...</div>
            </div>

            <div id="map"></div>

            <style>
            #map_loader {
                position: absolute;
                width: 80%;
                height: 70vh;
                background: rgba(255, 255, 255, 0.9);
                display: flex;
                flex-direction: column;
                align-items: center;
                justify-content: center;
                z-index: 10;
                font-weight: bold;
            }

            .spinner {
                width: 40px;
                height: 40px;
                border: 5px solid #ccc;
                border-top: 5px solid #333;
                border-radius: 50%;
                animation: spin 1s linear infinite;
                margin-bottom: 10px;
            }

            @keyframes spin {
                100% {
                    transform: rotate(360deg);
                }
            }

            #map {
                height: 70vh;
                width: 80%;
                margin-top: 10px;
            }

            #coords {
                font-family: monospace;
                margin-top: 10px;
            }

            #pin {
                width: 100%;
                font-family: monospace;
                padding: 5px;
                margin-top: 10px;
            }

            @media all and (min-width: 425px) and (max-width: 768px) {
                #map {
                    height: 30vh;
                    width: 90%;
                    margin-top: 5vw;
                }

                #map_loader {
                    position: absolute;
                    width: 90%;
                    height: 32vh;
                    background: rgba(255, 255, 255, 0.9);
                    display: flex;
                    flex-direction: column;
                    align-items: center;
                    justify-content: center;
                    z-index: 10;
                    font-weight: bold;
                    margin-top: 36vw;
                }

                .spinner {
                    width: 150px;
                    height: 150px;
                    border: 5px solid #ccc;
                    border-top: 5px solid #333;
                    border-radius: 50%;
                    animation: spin 1s linear infinite;
                    margin-bottom: 10px;
                }

                #coords {
                    font-family: monospace;
                    margin-top: 10px;
                }

                #pin {
                    width: 100%;
                    font-family: monospace;
                    padding: 5px;
                    margin-top: 10px;
                }
            }
            </style>

            <script>
            let map;
            let marker;

            function updateCoords(lat, lng) {
                document.getElementById("map_co_ordinates").value =
                `${lat.toFixed(6)}, ${lng.toFixed(6)}`;
            }

            function getLocation() {

                // 🔥 SHOW loader immediately when button is clicked
                document.getElementById("map_loader").style.display = "flex";

                if (navigator.geolocation) {
                    navigator.geolocation.getCurrentPosition(
                        position => {

                            const lat = position.coords.latitude;
                            const lng = position.coords.longitude;

                            const userLocation = { lat, lng };
                            updateCoords(lat, lng);

                            if (!map) {
                                map = new google.maps.Map(document.getElementById("map"), {
                                        center: userLocation,
                                        zoom: 18
                                    });

                                google.maps.event.addListenerOnce(map, 'tilesloaded', function () {
                                        document.getElementById("map_loader").style.display = "none";
                                    });

                            } else {
                                map.setCenter(userLocation);
                                document.getElementById("map_loader").style.display = "none";
                            }

                            if (!marker) {
                                marker = new google.maps.Marker({
                                        position: userLocation,
                                        map: map,
                                        draggable: true
                                    });

                                marker.addListener("dragend", () => {
                                        const pos = marker.getPosition();
                                        updateCoords(pos.lat(), pos.lng());
                                    });

                            } else {
                                marker.setPosition(userLocation);
                            }
                        },

                        error => {
                            document.getElementById("map_loader").style.display = "none";
                            alert("Error getting location: " + error.message);
                        },

                        {
                            enableHighAccuracy: true,
                            timeout: 10000,
                            maximumAge: 0
                        }
                    );
                } else {
                    document.getElementById("map_loader").style.display = "none";
                    alert("Geolocation not supported.");
                }
            }
            </script>

            <script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCXu62pAxEnoWh-eXMpYBkGsz_iX-EVm2k"></script>

        </div>

        <div class="install_div" id="install_data">
            <h2 class="create_h2">JOBCARD</h2>
            <button class="submit_btn" onclick="open_notesPopup()">MAKE NOTES</button>
            <input class="big_inputs" placeholder="PIN" id="map_co_ordinates" name="map_co_ordinates" style="width: 30%;" hidden>

            <br>
            <div style="display: flex; flex-direction: column; width: 100%; align-items: center;">
                <label for="jobcard_id_label" class="create_details_label" style="width: 100%;">JOBCARD ID : </label>
                <input class="create_details_input" id="jobcard_no" name="jobcard_id" value="<?php echo $jobcard_data['jobcard_no']; ?>" readonly>`
                <input class="create_details_input" id="record_id" name="record_id" value="<?php echo $_GET['record_id']; ?>" hidden>
            </div>
            <div style="display: flex; flex-direction: column; width: 100%; align-items: center;">
                <label for="installed_by_label" class="create_details_label" style="width: 100%;">CLIENT NAME</label>
                <input type="text" name="client_name" id="client_name" class="create_details_input" value="<?php echo $jobcard_data['client_name'] ?>">
            </div>
            <div style="display: flex; flex-direction: column; width: 100%; align-items: center;">
                <label for="installed_by_label" class="create_details_label" style="width: 100%;">INSTALLED BY</label>
                <input type="text" name="installed_by" id="installed_by" class="create_details_input" value="<?php echo $user['username'] ?>">
                <input type="text" name="date_attended" id="date_attended" class="create_details_input" value="<?php echo $current_date; ?>" hidden>
            </div><br>
            <div style="display: flex; flex-direction: column; width: 100%; align-items: center;">
                <label for="" class="create_details_label" style="width: 100%;">CABLE METERS</label>
                <input type="text" name="cable_meters" id="cable_meters" class="create_details_input" value="<?php echo htmlspecialchars($jobcard_data['cable_meters']); ?>">
            </div>

            <div style="display: flex; flex-direction: column; width: 100%; align-items: center;">
                <label for="hdpe_meters_label" class="create_details_label" style="width: 100%;">HDPE PIPE</label>
                <input type="text" name="hdpe_meters" id="hdpe_meters" class="create_details_input" value="<?php echo htmlspecialchars($jobcard_data['hdpe_meters']); ?>">
            </div>

            <div style="display: flex; flex-direction: column; width: 100%; align-items: center;">
                <label for="pack_no_label" class="create_details_label" style="width: 100%;">PACK NO</label>
                <select name="pack_no" id="pack_no" class="create_details_input">
                    <?php 
                    if ($jobcard_data['pack_no'] == "") {
                        ?>
                            <option value=""></option>
                            <option value="1">1</option>
                            <option value="2">2</option>
                            <option value="3">3</option>
                        <?php
                    } else {
                        ?>
                            <option value=""></option>
                            <option value="1" <?= ($jobcard_data['pack_no'] == "1") ? 'selected' : '' ?>>1</option>
                            <option value="2" <?= ($jobcard_data['pack_no'] == "2") ? 'selected' : '' ?>>2</option>
                            <option value="3" <?= ($jobcard_data['pack_no'] == "3") ? 'selected' : '' ?>>3</option>
                        <?php
                    }
                    ?>
                </select>
            </div>

            <div style="display: flex; flex-direction: column; width: 100%; align-items: center;">
                <label for="pump_no_label" class="create_details_label" style="width: 100%;">PUMP NO</label>
                <input type="text" name="pump_no" id="pump_no" class="create_details_input" value="<?php echo htmlspecialchars($jobcard_data['pump_no']); ?>">
            </div>

            <div style="display: flex; flex-direction: column; width: 100%; align-items: center;">
                <label for="" class="create_details_label" style="width: 100%;">BOREHOLE METERS</label>
                <input type="text" name="borehole_meters" id="borehole_meters" class="create_details_input" value="<?php echo htmlspecialchars($jobcard_data['borehole_meters']); ?>">
            </div>

            <div style="display: flex; flex-direction: column; width: 100%; align-items: center;">
                <label for="problem_description_label" class="create_details_label" style="width: 100%;">PROBLEM DESCRIPTION : </label>
                <textarea name="problem_description" id="problem_description" rows="5" class="create_details_input" style="font-size: 3em;"><?php echo $jobcard_data['problem_description'] ?></textarea>
            </div>

            <div style="display: flex; flex-direction: column; width: 100%; align-items: center;">
                <label for="problem_solution_label" class="create_details_label" style="width: 100%;">POSSIBLE SOLUTION : </label>
                <input class="create_details_input" id="record_id" name="record_id" value="<?php echo $_GET['record_id']; ?>" hidden>
                <textarea name="problem_solution" id="problem_solution" rows="5" class="create_details_input" style="font-size: 3em;"><?php echo $jobcard_data['problem_solution'] ?></textarea>
            </div><br>

            <?php

                $res_arrival = $db->query("jobcard_timeline", "SELECT * FROM jobcard_timeline WHERE jobcard_id = '{$_GET['jobcard_no']}' ORDER BY record_id DESC LIMIT 1");
                // echo "SELECT * FROM jobcard_timeline WHERE jobcard_id = {$_GET['record_id']} ORDER BY record_id DESC LIMIT 1";

                $record_res = $res_arrival->fetch_assoc();

                if ($record_res['type'] == "ARRIVED") {
                    $next_btn = new button();
                    $next_btn->style("margin-top: 5vw; margin-bottom: 3vw;");
                    $next_btn->value("SAVE");
                    $next_btn->onclick("if (check()) { update_jobcard(); next(); }");
                    $next_btn->add();

                    $update_ajax = new js_ajax();
                    $update_ajax->function_name("update_jobcard");
                    $update_ajax->update("pump_installation");
                    $update_ajax->selected_div(".install_div input , .install_div select, .install_div textarea");
                    $update_ajax->add_column_and_value("record_id={$_GET['record_id']}");
                    $update_ajax->on_success("DATA CAPTURED AND SAVED");

                    $riem_ajax = new js_ajax();
                    $riem_ajax->function_name("next");
                    $riem_ajax->selected_div("install_job_data");
                    $riem_ajax->insert("jobcard_timeline");
                    $riem_ajax->add_column_and_value("jobcard_id={$_GET['jobcard_no']},date_time={$current_date},type=INSTALLING,user_id={$_SESSION['user_id']}");
                    $riem_ajax->redirect("install_actions.php?record_id={$_GET['record_id']}&jobcard_no={$_GET['jobcard_no']}");
                    $riem_ajax->exclude_inputs("['jc_current_status', 'eft_type', 'payment_method']");
                    $riem_ajax->on_success("DATA CAPTURED AND SAVED");

                } elseif ($record_res['type'] == "DEPARTED") {
                    $next_btn = new button();
                    $next_btn->value("DISABLED");
                    $next_btn->style("background-color: #00008045; color: white;");
                    $next_btn->add();
                } else {
                    $next_btn = new button();
                    $next_btn->value("NEXT");
                    $next_btn->onclick("submit_jobcard()");
                    $next_btn->add();

                    $submit_details = new js_ajax();
                    $submit_details->function_name("submit_jobcard");
                    $submit_details->update("pump_installation");
                    $submit_details->selected_div(".install_div input , .install_div select, install_div textarea");
                    $submit_details->redirect("install_actions.php?record_id={$_GET['record_id']}&jobcard_no={$_GET['jobcard_no']}");
                    $submit_details->exclude_inputs("['jc_current_status', 'eft_type', 'payment_method']");
                    $submit_details->on_success("DATA UPDATED");
                }
            ?>
        </div>

        <?php

    } else if ($has_departed) {
        $depart_ajax = new js_ajax();
        $depart_ajax->function_name("team_arrived");
        $depart_ajax->insert("jobcard_timeline");
        $depart_ajax->selected_div("arrival");
        $depart_ajax->add_column_and_value("jobcard_id={$_GET['jobcard_no']},date_time={$current_date},type=ARRIVED,user_id={$_SESSION['user_id']}");
        $depart_ajax->on_success("ARRIVAL CAPTURED");

        ?>

        <div class="form_down" id="arrival">
            <buttton class="process_btn" id="arrival_button" name="arrival_button" onclick="team_arrived()">ARRIVAL</buttton>
            <input class="inputs" value="DEPARTED" id="jc_current_status" name="jc_current_status" onchange="check_status()" readonly />
        </div>

        <?php

    } else {

        $depart_btn = new button();
        $depart_btn->value("DEPARTURE");
        $depart_btn->onclick("team_departed()");
        $depart_btn->id("departure_button");
        $depart_btn->class('process_btn');

        $current_jc_status = new input();
        $current_jc_status->value("START");
        $current_jc_status->readonly();
        $current_jc_status->class("inputs");
        $current_jc_status->type("hidden");
        $current_jc_status->id("jc_current_status");
        $current_jc_status->onchange("check_status()");

        $depart_ajax = new js_ajax();
        $depart_ajax->function_name("team_departed");
        $depart_ajax->insert("jobcard_timeline");
        $depart_ajax->selected_div("departure");
        $depart_ajax->add_column_and_value("jobcard_id={$_GET['jobcard_no']},date_time={$current_date},type=DEPARTURE,user_id={$_SESSION['user_id']}");
        $depart_ajax->on_success("DEPARTURE CAPTURED");

        ?>

        <div class="form_down" id="departure">
            <buttton class="process_btn" id="departure_button" name="departure_button" onclick="team_departed()">DEPARTURE</buttton>
            <input class="inputs" value="DEPARTED" id="jc_current_status" name="jc_current_status" onchange="check_status()" readonly />
        </div>

        <?php
    }
} else {
    ?>
        <script>
            window.location.href = "../pump/install_actions.php?record_id=<?= $_GET['record_id'] ?>&jobcard_no=<?= $_GET['jobcard_no'] ?>";
        </script>
    <?php
}

?>

<script src="https://cdn.jsdelivr.net/npm/signature_pad@2.3.2/dist/signature_pad.min.js"></script>

<script>

    document.addEventListener('DOMContentLoaded', function () {
        const clientCanvas = document.getElementById('client_signature');
        const employeeCanvas = document.getElementById('employee_signature');
        const saveButton = document.getElementById('save_signatures');
        const clearClient = document.getElementById('clear_client_signature');
        const clearEmployee = document.getElementById('clear_employee_signature');
        const record_id = '<?php echo htmlspecialchars($_GET['jobcard_no']); ?>';

        function resizeCanvas(canvas) {
            if (!canvas) return;
            const ratio = Math.max(window.devicePixelRatio || 1, 1);
            // use getBoundingClientRect to respect CSS height/width
            const rect = canvas.getBoundingClientRect();
            canvas.width = rect.width * ratio;
            canvas.height = rect.height * ratio;
            const ctx = canvas.getContext("2d");
            ctx.scale(ratio, ratio);
        }

        resizeCanvas(clientCanvas);
        resizeCanvas(employeeCanvas);

        window.addEventListener("resize", () => {
            resizeCanvas(clientCanvas);
            resizeCanvas(employeeCanvas);
        });

        // Improved SignaturePad options
        const padOptions = {
            minWidth: 0.5,
            maxWidth: 2.5,
            throttle: 0,
            velocityFilterWeight: 0.6,
            penColor: 'black',
            backgroundColor: 'rgba(255,255,255,0)'
        };

        const client_pad = clientCanvas ? new SignaturePad(clientCanvas, padOptions) : null;
        const employee_pad = employeeCanvas ? new SignaturePad(employeeCanvas, padOptions) : null;

        // Prevent scrolling while signing (mobile)
        [clientCanvas, employeeCanvas].forEach(canvas => {
            if (canvas) {
                canvas.addEventListener("touchstart", e => e.preventDefault(), { passive: false });
                canvas.addEventListener("touchmove", e => e.preventDefault(), { passive: false });
            }
        });

        // Clear buttons
        if (clearClient && client_pad) {
            clearClient.addEventListener('click', () => client_pad.clear());
        }

        if (clearEmployee && employee_pad) {
            clearEmployee.addEventListener('click', () => employee_pad.clear());
        }

        // Save button
        if (saveButton) {
            saveButton.addEventListener('click', function () {
                    if ((!client_pad || client_pad.isEmpty()) && (!employee_pad || employee_pad.isEmpty())) {
                        alert("Please provide at least one signature.");
                        return;
                    }

                    saveButton.disabled = true;
                    saveButton.textContent = "Saving...";

                    let uploads = 0;
                    let total = (client_pad && !client_pad.isEmpty() ? 1 : 0) +
                    (employee_pad && !employee_pad.isEmpty() ? 1 : 0);

                    function checkComplete() {
                        uploads++;
                        if (uploads === total) location.reload();
                    }

                    if (client_pad && !client_pad.isEmpty()) uploadSignature(client_pad, 'client', checkComplete);
                    if (employee_pad && !employee_pad.isEmpty()) uploadSignature(employee_pad, 'employee', checkComplete);
                });
        }

            // Upload function
        function uploadSignature(pad, type, callback) {
            const dataURL = pad.toDataURL('image/png');
            const blob = dataURLToBlob(dataURL);
            const formData = new FormData();

            formData.append('file', blob, type + '_signature.png');
            formData.append('record_id', record_id);
            formData.append('type', type);

            const xhr = new XMLHttpRequest();
            xhr.open("POST", "../pump/upload_signature.php", true);
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4) {
                    if (xhr.status === 200 && xhr.responseText === "OK") {
                        console.log(`${type} signature saved successfully.`);
                    } else {
                        const errorMsg = xhr.responseText.replace('ERROR: ', '');
                        alert(`Error saving ${type} signature: ${errorMsg}`);
                    }
                    if (callback) callback();
                }
            };
            xhr.send(formData);
        }

            // Convert Base64 to Blob
        function dataURLToBlob(dataURL) {
            const binary = atob(dataURL.split(',')[1]);
            const array = [];
            for (let i = 0; i < binary.length; i++) {
                array.push(binary.charCodeAt(i));
            }
            return new Blob([new Uint8Array(array)], { type: 'image/png' });
        }
    });


    async function openSlipCamera() {
        const video = document.getElementById("camera_slip");
        const load_camera = document.getElementById("load_camera_slip");
        const open_camera = document.getElementById("open_camera_slip");

        try {

            stream_slip = await navigator.mediaDevices.getUserMedia({
                    video: { facingMode: "environment" },
                    audio: false
                });

            const video = document.getElementById("camera_slip");
            video.srcObject = stream_slip;
            video.style.display = "block";

            load_camera.style.display = "flex";
            open_camera.style.display = "none";

        } catch (error) {
            alert("Error accessing camera: " + error.message);
        }
    }

    function captureSlipPhoto() {
        const video = document.getElementById("camera_slip");
        const canvas = document.getElementById("snapshot_slip");
        const context = canvas.getContext("2d");
        const captured_image = document.getElementById("captured_image_slip");
        const load_camera = document.getElementById("load_camera_slip");
        const jobcard_no = "<?php echo $_GET['jobcard_no']; ?>";

        load_camera.style.display = "none";
        canvas.width = video.videoWidth;
        canvas.height = video.videoHeight;
        context.drawImage(video, 0, 0, canvas.width, canvas.height);

        captured_image.style.display = "none";

        const imageData = canvas.toDataURL("image/png");

        stopSlipCamera();
        saveCapturedSlipImage(imageData, jobcard_no);
    }

    function stopSlipCamera() {
        const open_camera = document.getElementById("open_camera_slip");
        const load_camera = document.getElementById("load_camera_slip");
        const video = document.getElementById("camera_slip");

        video.style.display = "none";
        load_camera.style.display = "none";
        open_camera.style.display = "block";
        if (stream_slip) {
            stream_slip.getTracks().forEach(track => track.stop());
            stream_slip = null;
            document.getElementById("camera_slip").srcObject = null;
        }
    }

    function saveCapturedSlipImage(imageData, jobcard_no) {
        const video = document.getElementById("camera_slip");
        const folder_path = "../pump/slips/";
        const section_name = "slip";

        video.style.display = "none";

        var formData = new FormData();

        formData.append('image', imageData);
        formData.append('jobcard_no', jobcard_no);
        formData.append('folder_path', folder_path);
        formData.append('section_name', section_name);

        const xhr = new XMLHttpRequest();
        xhr.open('POST', '../pump/save_camera.php', true);
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4 && xhr.status == 200) {
                if (xhr.responseText != '0') {
                    console.log('fileName: ' + xhr.responseText);
                    alert('Photo saved successfully!');
                    if ('slip' != '') {
                        document.getElementById('slip_file').style.display = 'block';
                        document.getElementById('slip_file').value = xhr.responseText;
                    }
                } else {
                    alert('Error saving photo!');
                }
            }
        };
        xhr.send(formData);
    }

    function payment_type() {
        var payment = document.getElementById("payment_method").value;

        if (payment == "EFT") {
            document.getElementById("eft").style.display = "flex";
            document.getElementById("cash").style.display = "flex";
        } else if (payment == "CASH") {
            document.getElementById("cash").style.display = "flex";
            document.getElementById("eft").style.display = "none";
        } else {
            document.getElementById("cash").style.display = "none";
            document.getElementById("eft").style.display = "none";
        }
    }

    function complete_payment() {
        var payment = document.getElementById("payment_method").value;
        var eft_type = document.getElementById("eft_type").value;
        var user_id = document.getElementById("user_id").value;
        var record_id = "<?= $_GET['jobcard_no'] ?>";

        if (payment == "") {
            alert("Please select Payment Method");
            return false;
        }

        var amount = document.getElementById("cash_amount").value;
        if (amount.trim() === "" || isNaN(amount) || amount <= 0) {
            alert("Please enter a valid Amount Paid");
            return false;
        }

        var formData = new FormData();
        formData.append('record_id', record_id);
        formData.append('payment_method', payment);
        formData.append('amount', amount);
        formData.append('user_id', user_id);

        if (payment === "EFT") {
            if (eft_type === "CAMERA") {
                var slip_input = document.getElementById("slip_file").value;
                if (slip_input === "" || slip_input.trim() === "") {
                    alert("Please capture Slip Image");
                    return false;
                }
                formData.append('file', slip_input);

            } else if (eft_type === "FILE") {
                var uploaded_filename = document.getElementById("uploaded_file_name");
                if (!uploaded_filename || uploaded_filename.value === "") {
                    alert("Please upload a file first.");
                    return false;
                }
                formData.append('file', uploaded_filename.value);

            } else {
                alert("Please select how you want to provide payment proof.");
                return false;
            }
        }

        // Submit payment
        const xhr = new XMLHttpRequest();
        xhr.open('POST', '../jobcard_payments.ajax.php', true);
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4) {
                if (xhr.status === 200 && xhr.responseText.includes("OK")) {
                    console.log(`PAYMENT SUCCESS: ${xhr.responseText}`);
                    alert('Payment completed successfully!');

                    // Clear all payment fields
                    document.getElementById("cash_amount").value = "";
                    document.getElementById("slip_file").value = "";
                    document.getElementById("payment_proof").value = "";

                    if (document.getElementById("uploaded_file_name")) {
                        document.getElementById("uploaded_file_name").value = "";
                    }

                    // Reset payment options
                    document.getElementById("payment_method").selectedIndex = 0;
                    document.getElementById("eft_type").selectedIndex = 0;
                    document.getElementById("cash").style.display = "none";
                    document.getElementById("eft").style.display = "none";

                    // Clear file inputs
                    var fileInput = document.getElementById("payment_proof");
                    if (fileInput) fileInput.value = "";

                    // Reload payment history
                    loadPaymentHistory();
                } else {
                    console.log(`Error saving PAYMENT: ${xhr.responseText}`);
                    alert('Error completing payment! Try again.');
                    return false;
                }
            }
        };
        xhr.send(formData);
    }

    function upload_file_ajax() {
        var payment_proof = document.getElementById("payment_proof");
        var file = payment_proof.files[0];
        var jobcard_no = "<?php echo $_GET['jobcard_no']; ?>";

        if (file) {
            var formData = new FormData();
            formData.append('file', file);
            formData.append('jobcard_no', jobcard_no);
            formData.append('ajax_type', "lead_payment_slip");
            formData.append('section_name', "slip");
            formData.append('file_save_path', "../jobcards/slips/");

            var xhr = new XMLHttpRequest();
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4) {
                    if (xhr.status === 200 && xhr.responseText.includes("OK")) {
                        console.log(`File uploaded successfully: ${xhr.responseText}`);

                        var response = xhr.responseText;
                        var filename = response.replace('OK | ', '').trim(); // Adjust based on your response format

                        // Store filename in hidden input (create this if it doesn't exist)
                        var uploadedFileInput = document.getElementById('uploaded_file_name');
                        if (!uploadedFileInput) {
                            uploadedFileInput = document.createElement('input');
                            uploadedFileInput.type = 'hidden';
                            uploadedFileInput.id = 'uploaded_file_name';
                            uploadedFileInput.name = 'uploaded_file_name';
                            document.getElementById('file_div').appendChild(uploadedFileInput);
                        }
                        uploadedFileInput.value = filename;

                        alert("File uploaded successfully!");
                    } else {
                        console.log(`Error uploading file: ${xhr.responseText}`);
                        alert('Error uploading file! ,try again.');
                    }
                }
            };
            xhr.open("POST", "../pump/upload_slip.php", true);
            xhr.send(formData);
        }
    }

    function loadPaymentHistory() {
        var jobcard_no = "<?php echo $_GET['jobcard_no']; ?>";

        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4 && xhr.status === 200) {
                document.getElementById("payment_history_table").innerHTML = xhr.responseText;
            }
        };

        xhr.open("POST", "../pump/payment_history.ajax.php", true);
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xhr.send("jobcard_no=" + encodeURIComponent(jobcard_no));
    }

    // Load history on page load
    document.addEventListener("DOMContentLoaded", loadPaymentHistory);

    loadPaymentHistory();

    // jobcard section
    function check_status() {
        var status = document.getElementById("jc_current_status").value.trim();
        var arrivalDiv = document.getElementById("arrival");
        var departureDiv = document.getElementById("departure");

        if (status === "ARRIVED") {
            departureDiv.style.display = "flex";
            arrivalDiv.style.display = "none";
        } else if (status === "DEPARTED") {
            departureDiv.style.display = "flex";
            arrivalDiv.style.display = "none";
        } else if (status === "DEPARTED AND ARRIVED") {
            departureDiv.style.display = "none";
            arrivalDiv.style.display = "flex";
        }
    }

    // error handler for submit
    function check() {
        var installed_by = document.getElementById("installed_by").value;
        var problem_solution = document.getElementById("problem_solution").value;
        var pack_no = document.getElementById("pack_no").value;
        var cable_meters = document.getElementById("cable_meters").value;
        var hdpe_meters = document.getElementById("hdpe_meters").value
        var pump_no = document.getElementById("pump_no").value;

        if (installed_by == "") {
            alert("Please enter Pump Installer Name");
            return false;
        }

        if (cable_meters == "") {
            alert("Please enter the cable meters");
            return false;
        }

        if (hdpe_meters == "") {
            alert("Please enter the HDPE pipe meters");
            return false;
        }

        if (pack_no == "") {
            alert("Please select the pack number");
            return false;
        }

        if (pump_no == "") {
            alert("Please enter the pump number");
            return false;
        }

        if (problem_solution == "") {
            alert("Please enter a problem solution");
            return false;
        }
        return true;
    }

    // notes section
    function open_notesPopup() {
        event.preventDefault ? event.preventDefault() : (event.returnValue = false, event.stopPropagation());
        document.getElementById("notes_popup").style.display = "block";
    }

    function close_notesPopup() {
        document.getElementById("notes_popup").style.display = "none";
    }

</script>
