<?php include "../../../root.class.php";
$html = new html();
$html->add_styles_page();
$db = new db_safeguard();
session_start();

$repair_data_res = $db->query("pump_repair", "SELECT * FROM pump_repair WHERE record_id = '{$_GET['record_id']}'");
// echo "SELECT * FROM pump_installation WHERE record_id = '{$_GET['record_id']}'";
$repair_data = $repair_data_res->fetch_assoc();

$jobcard_data_res = $db->query("pump_installation", "SELECT * FROM pump_installation WHERE record_id = '{$repair_data['installation_id']}'");
// echo "SELECT * FROM pump_repair WHERE record_id = '{$repair_data['installation_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']}'");
$users = $user_res->fetch_assoc();

$current_date_time = date("Y-m-d H:i", strtotime("+2 Hours"));

/////////////////////////////// NOTES POPUP SECTION ////////////////////////////////////////////////

$jobcard_id = new input();
$jobcard_id->type("hidden");
$jobcard_id->name("jobcard_id");
$jobcard_id->id("jobcard_id");
$jobcard_id->value($_GET['record_id']);

$date_time = new input();
$date_time->type("hidden");
$date_time->name("date_time");
$date_time->id("date_time");
$date_time->value($current_date_time);

$reasons_label = new label();
$reasons_label->class("big_labels");
$reasons_label->for("reasons");
$reasons_label->value("REASONS");
$reasons_label->addAttribute("style", " color: white;");

$reasons = new select();
$reasons->class("big_inputs");
$reasons->addAttribute("style", "width: 90%;");
$reasons->name("reason");
$reasons->id("reason");
$reasons->add_option("ARRIVED AT LOCATION", "ARRIVED AT LOCATION");
$reasons->add_option("WAITING FOR CLIENT", "WAITING FOR CLIENT");
$reasons->add_option("TRAVELING TO SITE", "TRAVELING TO SITE");
$reasons->add_option("ARRIVED ON SITE", "ARRIVED ON SITE");
$reasons->add_option("TALKING TO CLIENT", "TALKING TO CLIENT");
$reasons->add_option("FETCHING MONEY", "FETCHING MONEY");
$reasons->add_option("BRAKING", "BRAKING");
$reasons->add_option("CHANGING RIEMER", "CHANGING RIEMER");
$reasons->add_option("STOP", "STOP");
$reasons->add_option("PENDING", "PENDING");
$reasons->add_option("START", "START");
$reasons->add_option("INSTALLING", "INSTALLING");
$reasons->add_option("RECEIVED", "RECEIVED");
$reasons->add_option("BACK TO WORKSHOP", "BACK TO WORKSHOP");
$reasons->add_option("OTHER", "OTHER");

$notes_label = new label();
$notes_label->class("notes_heading");
$notes_label->for("notes");
$notes_label->value("NOTES");
$notes_label->addAttribute("style", "color: white; margin:1px;");

$pump_slip_label = new label();
$pump_slip_label->class("big_labels");
$pump_slip_label->for("pump_slip");
$pump_slip_label->value("PUMP SLIP");

$notes_sub_label = new label();
$notes_sub_label->class("big_labels");
$notes_sub_label->for("notes");
$notes_sub_label->value("NOTES");
$notes_sub_label->addAttribute("style", " color: white;");

$notes_image_label = new label();
$notes_image_label->class("big_labels");
$notes_image_label->for("notes");
$notes_image_label->value("NOTE IMAGE");
$notes_image_label->addAttribute("style", " color: white;");

$add_notes = new button();
$add_notes->value("ADD NOTES");
$add_notes->onclick("add_notes()");
$add_notes->style("width: 100%;");
$add_notes->id("notes_btn");

$notes_ajax = new js_ajax();
$notes_ajax->function_name("add_notes");
$notes_ajax->insert("notes");
$notes_ajax->selected_div(".notes_content input , .notes_content select, .notes_content textarea");
$notes_ajax->submit_btn_id("notes_btn");
$notes_ajax->on_success("NOTE SAVED");

$make_notes_btn = new button();
$make_notes_btn->value("MAKE NOTES");
$make_notes_btn->onclick("open_notesPopup()");
?>

<style>
    @media all and (max-width: 650px) {

        .main_div {
            display: flex;
            flex-direction: column;
            align-items: center;
            background: white;
            flex-wrap: wrap;
            align-content: space-around;
            border-radius: 3vw;
            margin: 1vw;
            padding: 4vw;
        }

        .close-btn {
            position: absolute;
            right: 15px;
            font-weight: bolder;
            font-size: 15vw;
            cursor: pointer;
            color: white;
        }

    }

    .main_div {
        display: flex;
        flex-direction: column;
        align-items: center;
        background: white;
        flex-wrap: wrap;
        align-content: space-around;
        border-radius: 3vw;
        margin: 1vw;
        padding: 4vw;
    }

    .sub_div {
        display: flex;
        flex-direction: column;
        align-items: center;
        background: white;
        flex-wrap: wrap;
        align-content: space-around;
        border-radius: 3vw;
        margin: 1vw;
        padding: 4vw;
    }

    .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;
        }
    }
</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>

<div id="signatures"
style="display: flex; flex-direction: column; background-color: white; border-radius: 3vw; padding: 4vw; margin-top: 3vw;">
    <h1 class="sign_h1">SIGNATURES</h1>

    <div style="text-align: left; font-size: 3.5vw;">
    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>

    <div style="display: flex; flex-direction: column;">
    <div style="display: flex; flex-direction: column; justify-content: center; flex-wrap: wrap;">

    <script src="https://cdn.jsdelivr.net/npm/signature_pad@2.3.2/dist/signature_pad.min.js"></script>

    <?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 style='display: flex; flex-direction: column;align-items: center;'>
        <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 style='display: flex; flex-direction: column;align-items: center;'>
        <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";

    // echo $client_file;
    if (file_exists($client_file)) {
        ?>
        <div style='display: flex; flex-direction: column;align-items: center;'>
        <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 style='display: flex; flex-direction: column;align-items: center;'>
        <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>

    <div>
    <?php
    if (
        !file_exists($client_file) ||
        !file_exists($employee_flie)
    ) {
        echo "<button type='button' id='save_signatures' class='save_sign_btn' >SAVED</button>";
    } else {

    }
    ?>
    </div>
    </div>
</div>

<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']); ?>';

        // Resize canvas to match CSS dimensions for crisp drawing
        function resizeCanvas(canvas) {
            if (!canvas) return;
            const ratio = Math.max(window.devicePixelRatio || 1, 1);
            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);
            });

        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 page scrolling while signing on 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 () {
                    const hasClient = client_pad && !client_pad.isEmpty();
                    const hasEmployee = employee_pad && !employee_pad.isEmpty();

                    if (!hasClient && !hasEmployee) {
                        alert("Please provide at least one signature before saving.");
                        return;
                    }

                    saveButton.disabled = true;
                    saveButton.textContent = "Saving...";

                    let uploads = 0;
                    const total = (hasClient ? 1 : 0) + (hasEmployee ? 1 : 0);

                    function checkComplete() {
                        uploads++;
                        if (uploads === total) {
                            location.reload();
                        }
                    }

                    if (hasClient) uploadSignature(client_pad, 'client', checkComplete);
                    if (hasEmployee) uploadSignature(employee_pad, 'employee', checkComplete);
                });
        }

        // Upload a signature pad image to the server
        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.includes("OK")) {
                        console.log(`${type} signature saved successfully.`);
                    } else {
                        alert(`Error saving ${type} signature: ${xhr.responseText}`);
                        // Re-enable save button on error
                        if (saveButton) {
                            saveButton.disabled = false;
                            saveButton.textContent = "SAVE";
                        }
                    }
                    if (callback) callback();
                }
            };

            xhr.send(formData);
        }

        // Convert Base64 data URL to Blob for upload
        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' });
        }
    });
</script>

<div class="sub_div" style="width: 90%; max-width: none; margin: 3vw 2vw;">
    <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>

                    <script>
                            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";
                                }
                            }

                            function complete_payment() {
                                var payment = document.getElementById("payment_method").value;
                                var eft_type = document.getElementById("eft_type").value;
                                var user_id = "<?= $_SESSION['user_id'] ?>";

                                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', '<= $jobcard_id['jc_no'] ?>');
                                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);
                            }
                    </script>

                    <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()">
                    </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>

                <script>
                    function getJobcardNo() {
                        const params = new URLSearchParams(window.location.search);
                        const jc = params.get('jobcard_no');
                        if (!jc) {
                            alert("❌ Job card number missing from URL. Cannot save.");
                            return null;
                        }
                        return jc;
                    }

                    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";
                        }
                    }

                    function complete_payment() {
                        var payment = document.getElementById("payment_method").value;
                        var eft_type = document.getElementById("eft_type").value;
                        var record_id = "<?= $_GET['jobcard_no'] ?>";
                        var user_id = "<?= $_SESSION['user_id'] ?>";

                        if (payment === "" || payment === "Payment Method") {
                            alert("Please select Payment Method");
                            return false;
                        }

                        var amount = document.getElementById("cash_amount").value;
                        if (amount.trim() === "" || isNaN(amount) || parseFloat(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;
                            }
                        }

                        const xhr = new XMLHttpRequest();
                        xhr.open('POST', '../pump/jobcard_payments.ajax.php', true);
                        xhr.onreadystatechange = function () {
                            if (xhr.readyState === 4) {
                                if (xhr.status === 200 && xhr.responseText.includes("OK")) {
                                    alert('Payment completed successfully!');

                                    document.getElementById("cash_amount").value = "";
                                    document.getElementById("slip_file").value = "";

                                    // Null-check before clearing optional elements
                                    var paymentProof = document.getElementById("payment_proof");
                                    if (paymentProof) paymentProof.value = "";

                                    var uploadedFileName = document.getElementById("uploaded_file_name");
                                    if (uploadedFileName) uploadedFileName.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 {
                                    alert('Error completing payment! Try again.');
                                }
                            }
                        };
                        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', "../pump/slips/");

                            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;
                                        alert("File uploaded successfully!");
                                    } else {
                                        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));
                    }

                    document.addEventListener("DOMContentLoaded", loadPaymentHistory);
                </script>
            </div>
        </div>
    </div>
</div>

<div class="sub_div" style="width: 90%; max-width: none;">

    <div id="response"></div>

    <div id="install_cameras_container" style=""></div>

    <button class="submit_btn" id="install_btn" onclick="addInstallCamera()">Add Camera</button>

    <script>
        let capturedImages = {};
        let installIndex = 0;
        let streams = {};

        function addInstallCamera() {
            installIndex++;
            const i = installIndex;

            const html = `
                <div class="install_camera_block" style="display:flex; flex-direction:column; align-items:center;" id="install_block_${i}">
                <hr>
                <video style="display:none;" id="camera_install_${i}" autoplay playsinline></video>
                <br>
                <button id="open_camera_install_${i}" class="submit_btn" onclick="openInstallCamera(${i})">
                    Open Camera ${i}
                </button>
                <div id="load_camera_install_${i}" style="display:none; width:100%; justify-content:center;">
                    <button class="submit_btn" onclick="captureInstallPhoto(${i})">Capture Photo</button>
                    <button class="submit_btn" onclick="stopInstallCamera(${i})">Stop Camera</button>
                </div>
                <div id="preview_block_${i}" style="display:none; flex-direction:column; align-items:center; width:100%;">
                    <h3>Captured Image:</h3>
                    <canvas id="snapshot_install_${i}" style="width:80%; border-radius:8px;"></canvas>
                    <label style="color:black; margin-top:10px;" class="create_details_label">DESCRIPTION</label>
                    <textarea
                        id="install_${i}_description"
                        rows="5" cols="70"
                        placeholder="Enter image description..."
                        class="inputs"
                        style="width:100%; margin-top:5px; font-size:2em;">
                    </textarea>
                    <div style="display:flex; gap:10px; margin-top:10px;">
                        <button class="submit_btn" onclick="saveInstallImage(${i})">Save Image</button>
                        <button class="submit_btn" onclick="retakeInstallPhoto(${i})">Retake</button>
                    </div>
                    <div id="save_response_${i}" style="margin-top:8px; font-weight:bold;"></div>
                </div>
                <img src="" id="install_${i}_preview" style="display:none; width:80%; margin-top:10px; border-radius:8px;" />
                <input type="hidden" id="install_${i}_image" name="install_${i}_image">
                </div>
            `;

            document.getElementById("install_cameras_container").insertAdjacentHTML("beforeend", html);
        }

        async function openInstallCamera(i) {
            const video   = document.getElementById(`camera_install_${i}`);
            const load    = document.getElementById(`load_camera_install_${i}`);
            const openBtn = document.getElementById(`open_camera_install_${i}`);

            try {
                streams[i] = await navigator.mediaDevices.getUserMedia({
                    video: { facingMode: "environment" },
                    audio: false
                });
                video.srcObject = streams[i];
                video.style.display = "block";
                load.style.display  = "flex";
                openBtn.style.display = "none";
            } catch (err) {
                alert("Camera error: " + err.message);
            }
        }

        function captureInstallPhoto(i) {
            const video  = document.getElementById(`camera_install_${i}`);
            const canvas = document.getElementById(`snapshot_install_${i}`);
            const ctx    = canvas.getContext("2d");
            const load   = document.getElementById(`load_camera_install_${i}`);

            canvas.width  = video.videoWidth;
            canvas.height = video.videoHeight;
            ctx.drawImage(video, 0, 0);

            capturedImages[i] = canvas.toDataURL("image/png");

            stopInstallCamera(i);
            load.style.display = "none";
            document.getElementById(`preview_block_${i}`).style.display = "flex";
            document.getElementById(`save_response_${i}`).innerHTML = "";
        }

        function stopInstallCamera(i) {
            const video   = document.getElementById(`camera_install_${i}`);
            const load    = document.getElementById(`load_camera_install_${i}`);
            const openBtn = document.getElementById(`open_camera_install_${i}`);

            video.style.display   = "none";
            load.style.display    = "none";
            openBtn.style.display = "block";

            if (streams[i]) {
                streams[i].getTracks().forEach(t => t.stop());
                streams[i]      = null;
                video.srcObject = null;
            }
        }

        function retakeInstallPhoto(i) {
            capturedImages[i] = null;
            document.getElementById(`preview_block_${i}`).style.display    = "none";
            document.getElementById(`install_${i}_description`).value      = "";
            document.getElementById(`save_response_${i}`).innerHTML        = "";
            openInstallCamera(i);
        }

        function saveInstallImage(i) {
            const jobcard_no  = getJobcardNo();
            const imageData   = capturedImages[i];
            const description = document.getElementById(`install_${i}_description`).value.trim();
            const responseDiv = document.getElementById(`save_response_${i}`);

            // ✅ Guard jobcard_no first
            if (!jobcard_no) return;

            if (!imageData) {
                alert("No image captured. Please take a photo first.");
                return;
            }

            if (description === '') {
                alert("Please add a description before saving.");
                return;
            }

            responseDiv.innerHTML  = "⏳ Saving...";
            responseDiv.style.color = "orange";

            const formData = new FormData();
            formData.append("image",        imageData);
            formData.append("jobcard_no",   jobcard_no);
            formData.append("section_name", "repair");
            formData.append("description",  description);

            const xhr = new XMLHttpRequest();
            xhr.timeout = 15000;
            xhr.open("POST", "save_cam_image.php", true);

            xhr.onload = function () {
                if (xhr.status === 200) {
                    const file_desc = xhr.responseText.trim();

                    if (file_desc !== '0' && file_desc !== '') {
                        const parts    = file_desc.split(' _ ');
                        const fileName = parts[0];

                        const preview = document.getElementById(`install_${i}_preview`);
                        preview.src   = '/app/jobcards/pump/repair_images/' + fileName;
                        preview.style.display = "block";

                        document.getElementById(`install_${i}_image`).value         = fileName;
                        document.getElementById(`install_${i}_description`).value   = '';
                        capturedImages[i] = null;

                        // ✅ Show success BEFORE hiding the block so user sees it
                        responseDiv.innerHTML  = "✔ Saved successfully!";
                        responseDiv.style.color = "lightgreen";

                        // ✅ Small delay so success message is visible before block hides
                        setTimeout(function () {
                            document.getElementById(`preview_block_${i}`).style.display = "none";
                        }, 1500);

                        // ✅ Reload grid now that image is confirmed saved
                        loadImageHistory();

                    } else {
                        responseDiv.innerHTML  = "✘ Error saving image. Try again.";
                        responseDiv.style.color = "red";
                    }
                } else {
                    responseDiv.innerHTML  = `✘ Server error (${xhr.status}). Try again.`;
                    responseDiv.style.color = "red";
                }
            };

            xhr.onerror = function () {
                responseDiv.innerHTML  = "✘ Network error. Try again.";
                responseDiv.style.color = "red";
            };

            xhr.ontimeout = function () {
                responseDiv.innerHTML  = "✘ Request timed out. Try again.";
                responseDiv.style.color = "red";
            };

            xhr.send(formData);
        }

        function loadImageHistory() {
            const jobcard_no = getJobcardNo();
            if (!jobcard_no) return; // ✅ guard added — was missing before

            const grid = document.getElementById("image_history_grid");
            grid.innerHTML = "<p style='color:white; text-align:center;'>⏳ Loading images...</p>";

            const xhr = new XMLHttpRequest();
            xhr.timeout = 15000;
            xhr.open("POST", "get_install_images.php", true);
            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

            xhr.onload = function () {
                if (xhr.status === 200) {
                    const response = xhr.responseText.trim();
                    if (response === '' || response === '0') {
                        grid.innerHTML = "<p style='color:white; text-align:center;'>NO IMAGES FOUND</p>";
                    } else {
                        grid.innerHTML = response;
                    }
                } else {
                    grid.innerHTML = `<p style='color:red; text-align:center;'>✘ Server error (${xhr.status}). Please try again.</p>`;
                }
            };

            xhr.onerror = function () {
                grid.innerHTML = "<p style='color:red; text-align:center;'>✘ Network error. Check your connection.</p>";
            };

            xhr.ontimeout = function () {
                grid.innerHTML = "<p style='color:red; text-align:center;'>✘ Request timed out. Please try again.</p>";
            };

            xhr.send("jobcard_no=" + encodeURIComponent(jobcard_no));
        }

        function deleteInstallImage(record_id, btn) {
            if (!confirm("Are you sure you want to delete this image?")) return;

            btn.disabled        = true;
            btn.textContent     = "Deleting...";

            const formData = new FormData();
            formData.append("record_id", record_id);

            const xhr = new XMLHttpRequest();
            xhr.timeout = 15000;
            xhr.open("POST", "delete_install_image.php", true);

            xhr.onload = function () {
                if (xhr.status === 200 && xhr.responseText.trim() === '1') {
                    // ✅ Remove card from DOM instantly — no full reload needed
                    btn.closest('.install_image_card').remove();
                } else {
                    alert("Error deleting image.");
                    btn.disabled    = false;
                    btn.textContent = "🗑 Delete Image";
                }
            };

            xhr.onerror = function () {
                alert("Network error. Could not delete image.");
                btn.disabled    = false;
                btn.textContent = "🗑 Delete Image";
            };

            xhr.send(formData);
        }

        function saveNote() {
            const jobcard_no  = getJobcardNo();
            if (!jobcard_no) return;

            const reason      = document.getElementById('reason').value.trim();
            const note        = document.getElementById('note').value.trim();
            const image       = document.getElementById('image').value.trim();
            const responseDiv = document.getElementById('note_save_response');

            if (reason === '') { alert("Please select a reason."); return; }
            if (note   === '') { alert("Please enter a note.");    return; }

            const formData = new FormData();
            formData.append("jobcard_no", jobcard_no);
            formData.append("reason",     reason);
            formData.append("note",       note);
            formData.append("image",      image);

            const xhr = new XMLHttpRequest();
            xhr.timeout = 15000;
            xhr.open("POST", "save_note.php", true);

            xhr.onload = function () {
                if (xhr.status === 200) {
                    if (xhr.responseText.trim() === '1') {
                        responseDiv.innerHTML  = "✔ NOTE SAVED";
                        responseDiv.style.color = "lightgreen";
                        document.getElementById('note').value  = '';
                        document.getElementById('image').value = '';
                        loadNotesTable();
                    } else {
                        responseDiv.innerHTML  = "✘ ERROR SAVING NOTE";
                        responseDiv.style.color = "red";
                    }
                } else {
                    responseDiv.innerHTML  = `✘ Server error (${xhr.status}).`;
                    responseDiv.style.color = "red";
                }
            };

            xhr.onerror   = function () { responseDiv.innerHTML = "✘ Network error.";   responseDiv.style.color = "red"; };
            xhr.ontimeout = function () { responseDiv.innerHTML = "✘ Request timed out."; responseDiv.style.color = "red"; };

            xhr.send(formData);
        }

        function loadNotesTable() {
            const jobcard_no = getJobcardNo();
            if (!jobcard_no) return;

            const xhr = new XMLHttpRequest();
            xhr.timeout = 15000;
            xhr.open("POST", "get_notes.php", true);
            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

            xhr.onload = function () {
                if (xhr.status === 200) {
                    const res   = xhr.responseText.trim();
                    const table = document.getElementById('notes_table');

                    const headerRow = table.querySelector('tr');
                    table.innerHTML = '';
                    table.appendChild(headerRow);

                    if (res === '0' || res === '') {
                        table.innerHTML += `<tr><td colspan="4">NO NOTES RECORDED</td></tr>`;
                        return;
                    }

                    try {
                        const rows = JSON.parse(res);
                        rows.forEach(function (row) {
                            const imageCell = row.image
                                ? `<img src="/app/jobcards/pump/notes/${row.image}" style="width:80px;">`
                                : '';
                            table.innerHTML += `
                                <tr>
                                    <td>${row.reason}</td>
                                    <td>${row.note}</td>
                                    <td>${imageCell}</td>
                                    <td>${row.date_time}</td>
                                </tr>`;
                        });
                    } catch (e) {
                        table.innerHTML += `<tr><td colspan="4">Error loading notes.</td></tr>`;
                    }
                }
            };

            xhr.onerror   = function () { console.error("loadNotesTable network error"); };
            xhr.ontimeout = function () { console.error("loadNotesTable timed out"); };

            xhr.send("jobcard_no=" + encodeURIComponent(jobcard_no));
        }

        function openLightbox(src) {
            document.getElementById("lightbox_img").src         = src;
            document.getElementById("lightbox").style.display   = "flex";
        }

        function closeLightbox() {
            document.getElementById("lightbox").style.display   = "none";
            document.getElementById("lightbox_img").src         = "";
        }

        window.onload = function () {
            loadImageHistory();
        };
    </script>

    <div style="width:100%; margin-top:20px;">
        <h2 style="text-align:center;" class="create_h2">IMAGE HISTORY</h2>
        <div id="image_history_grid" style="display:flex; flex-direction: column; gap:15px; padding:10px;"></div>
    </div>

        <!-- LIGHTBOX -->
    <div id="lightbox" onclick="closeLightbox()" style="display:none; position:fixed; z-index:9999; top:0; left:0; width:100%; height:100%;
        background:rgba(0,0,0,0.9); justify-content:center; align-items:center;">
        <img id="lightbox_img" src="" style="max-width:90%; max-height:90%; border-radius:10px;" />
    </div>

</div><br>

<div class="sub_div" style="width: 90%; max-width: none;">
    <h2 class="create_h2">REPLACED ITEMS</h2>

    <div id="options_container" style="width: 95%;"></div>

    <button type="button" onclick="add_option()" class="submit_btn add_btn">
        + ADD ITEM
    </button>

    <style>
        .sub_div{
            width: 100%;
            max-width: 600px;
            margin: auto;
            padding: 20px;
        }

        .create_h2{
            text-align: center;
            margin-bottom: 20px;
        }

        /* Row styling */
        .option_row{
            display: flex;
            gap: 10px;
            margin-bottom: 12px;
            align-items: center;
            background: #f9f9f9;
            padding: 10px;
            border-radius: 8px;
            border: 1px solid #ddd;
        }

        /* Select */
        .create_inputs{
            flex: 1;
            padding: 8px;
            border-radius: 6px;
            border: 1px solid #ccc;
        }

        /* Buttons */
        button{
            padding: 7px 12px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 13px;
        }

        .add_btn{
            width: 100%;
            margin-top: 10px;
            background: #007bff;
            color: white;
        }

        .add_btn:hover{
            background: #0056b3;
        }

        .save_btn{
            background: #28a745;
            color: white;
        }

        .save_btn:hover{
            background: #1e7e34;
        }

        .remove_btn{
            background: #dc3545;
            color: white;
        }

        .remove_btn:hover{
            background: #a71d2a;
        }
    </style>

    <script>
        function add_option(){

            let container = document.getElementById("options_container");

            let new_option = document.createElement("div");
            new_option.className = "option_row";

            new_option.innerHTML = `
                <select class="create_inputs replaced_item">
                    <option value="">--SELECT ITEM--</option>
                    <option value="CABLE JOINT">CABLE JOINT</option>
                    <option value="WET END">WET END</option>
                    <option value="MOTOR">MOTOR</option>
                    <option value="CONTROL BOX">CONTROL BOX</option>
                    <option value="HDPE PIPE">HDPE PIPE</option>
                    <option value="SKI ROPE">SKI ROPE</option>
                    <option value="BASE PLATE">BASE PLATE</option>
                    <option value="ELECTRIC CABLE">ELECTRIC CABLE</option>
                    <option value="PUMP">PUMP</option>
                </select>

                <button type="button" style="font-size: 4vw;" class="save_btn" onclick="save_replaced_items(this)">SAVE</button>

                <button type="button" style="font-size: 4vw;" class="remove_btn" onclick="remove_option(this)">✖</button>
            `;

            container.appendChild(new_option);
        }

        function remove_option(btn){
            btn.parentElement.remove();
        }

        function save_replaced_items(btn){

            const jobcard_no = "<?php echo $_GET['jobcard_no']; ?>";

            const row = btn.parentElement;
            const replaced_item = row.querySelector('.replaced_item').value;

            if (replaced_item === '') {
                alert("Please select an item.");
                return;
            }

            btn.innerHTML = "Saving...";
            btn.disabled = true;

            const formData = new FormData();
            formData.append("jobcard_no", jobcard_no);
            formData.append("replaced_item", replaced_item);

            const xhr = new XMLHttpRequest();
            xhr.open("POST", "save_replaced_item.php", true);

            xhr.onload = function () {
                if (xhr.status == 200) {
                    console.log(xhr.responseText.trim());
                    if (xhr.responseText.trim() === '1') {
                        btn.innerHTML = "✔ Saved";
                        btn.style.background = "#6c757d"; // grey after save
                        loadReplacedTable(); // reload table
                    } else {
                        alert("✘ Error saving item");
                        btn.innerHTML = "SAVE";
                        btn.disabled = false;
                    }

                }
            };

            xhr.send(formData);
        }

        function loadReplacedTable(){

            const jobcard_no = "<?php echo $_GET['jobcard_no']; ?>";

            const xhr = new XMLHttpRequest();
            xhr.open("POST", "load_replaced_items.php", true);
            xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

            xhr.onload = function(){
                if(xhr.status === 200){
                    document.getElementById("options_container").innerHTML = xhr.responseText;
                }
            };

            xhr.send("jobcard_no=" + encodeURIComponent(jobcard_no));
        }

        window.onload = function(){
            loadReplacedTable();
        };

        function delete_item(record_id){

            if(!confirm("Remove this item?")) return;

            const xhr = new XMLHttpRequest();
            xhr.open("POST", "delete_replaced_item.php", true);
            xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

            xhr.onload = function(){
                if(xhr.status === 200){
                    if(xhr.responseText.trim() === '1'){
                        loadReplacedTable();
                    } else {
                        alert("Error deleting item");
                    }
                }
            };

            xhr.send("record_id=" + record_id);
        }
    </script>
</div>

<div class="main_div" id="main_div">
    <h2 class="create_h2">JOCARD</h2>

    <?php $make_notes_btn->add(); ?>
    <br>

    <div style="display:flex; flex-direction: column; width: 100%; align-items: center;">

        <label class="big_labels">PUMP SLIP</label>

        <!-- TYPE SELECT -->
        <select id="pump_slip_type" onchange="togglePumpSlipType()" class="big_inputs">
            <option value="">TYPE</option>
            <option value="ATTACH_FILE">ATTACH FILE</option>
            <option value="CAMERA">CAMERA</option>
        </select>

        <!-- ================= CAMERA SECTION ================= -->
        <div id="camera_section" style="display:none; flex-direction: column; align-items:center; width:100%;">

            <video id="camera_pump_slip" autoplay playsinline style="display:none;"></video>

            <button type="button" id="open_camera_pump_slip" class="submit_btn" onclick="openPumpSlipCamera()">
                Open Camera
            </button>

            <div id="load_camera_pump_slip" style="display:none;">
                <button type="button" class="submit_btn" onclick="captureSlipPhoto()">Capture Photo</button>
                <button type="button" class="submit_btn" onclick="stopSlipCamera()">Stop Camera</button>
            </div>

            <canvas id="snapshot_pump_slip" style="display:none;"></canvas>
        </div>

        <!-- ================= FILE UPLOAD SECTION ================= -->
        <div id="file_section" style="display:none; flex-direction: column; align-items:center; width:100%;">
            <input type="file" class="big_inputs" id="pump_slip_file" accept="image/*,.pdf" onchange="uploadPumpSlipFile()">
        </div>

        <!-- PREVIEW -->
        <img id="pump_slip_preview" style="display:none; width:80%; margin-top:10px;" />

        <!-- HIDDEN VALUE -->
        <input type="text" id="pump_slip" name="pump_slip" style="display:none;">

    </div>

    <script>
        let stream_pump_slip;

        /* ================= TOGGLE TYPE ================= */
        function togglePumpSlipType(){
            const type = document.getElementById("pump_slip_type").value;

            document.getElementById("camera_section").style.display = "none";
            document.getElementById("file_section").style.display = "none";

            if(type === "CAMERA"){
                document.getElementById("camera_section").style.display = "flex";
            }

            if(type === "ATTACH_FILE"){
                document.getElementById("file_section").style.display = "flex";
            }
        }

        /* ================= CAMERA ================= */
        async function openPumpSlipCamera() {
            const video = document.getElementById("camera_pump_slip");

            try {
                stream_pump_slip = await navigator.mediaDevices.getUserMedia({
                    video: { facingMode: "environment" },
                    audio: false
                });

                video.srcObject = stream_pump_slip;
                video.style.display = "block";

                document.getElementById("load_camera_pump_slip").style.display = "flex";
                document.getElementById("open_camera_pump_slip").style.display = "none";

            } catch (error) {
                alert("Camera error: " + error.message);
            }
        }

        function capturePumpSlipPhoto() {
            const video = document.getElementById("camera_pump_slip");
            const canvas = document.getElementById("snapshot_pump_slip");
            const context = canvas.getContext("2d");

            canvas.width = video.videoWidth;
            canvas.height = video.videoHeight;

            context.drawImage(video, 0, 0);

            const imageData = canvas.toDataURL("image/png");

            stopPumpSlipCamera();
            saveCapturedPumpSlipImage(imageData);
        }

        function stopPumpSlipCamera() {
            const video = document.getElementById("camera_pump_slip");

            video.style.display = "none";
            document.getElementById("load_camera_pump_slip").style.display = "none";
            document.getElementById("open_camera_pump_slip").style.display = "block";

            if (stream_pump_slip) {
                stream_pump_slip.getTracks().forEach(track => track.stop());
                stream_pump_slip = null;
                video.srcObject = null;
            }
        }

        /* ================= SAVE CAMERA IMAGE ================= */
        function saveCapturedPumpSlipImage(imageData) {

            const jobcard_no = "<?php echo $_GET['jobcard_no']; ?>";
            const folder_path = "/app/jobcards/pump/pump_slip/";
            const section_name = "pump_slip";

            let 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", "/app/jobcards/pump/save_notes_camera.php", true);

            xhr.onload = function () {
                if (xhr.status === 200 && xhr.responseText !== "0") {

                    const fileName = xhr.responseText.trim();
                    const imagePath = folder_path + fileName;

                    document.getElementById("pump_slip_preview").src = imagePath;
                    document.getElementById("pump_slip_preview").style.display = "block";

                    document.getElementById("pump_slip").value = fileName;

                    alert("Photo saved!");

                } else {
                    alert("Error saving photo");
                }
            };

            xhr.send(formData);
        }

        /* ================= FILE UPLOAD ================= */
        function uploadPumpSlipFile(){

            const fileInput = document.getElementById("pump_slip_file");
            const file = fileInput.files[0];

            if(!file) return;

            const jobcard_no = "<?php echo $_GET['jobcard_no']; ?>";
            const folder_path = "/app/jobcards/pump/pump_slip/";
            const section_name = "pump_slip";

            let formData = new FormData();
            formData.append("file", file);
            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", "/app/jobcards/pump/save_file_upload.php", true);

            xhr.onload = function () {
                if (xhr.status === 200 && xhr.responseText !== "0") {

                    const fileName = xhr.responseText.trim();
                    const filePath = folder_path + fileName;

                    // preview if image
                    if(file.type.startsWith("image")){
                        document.getElementById("pump_slip_preview").src = filePath;
                        document.getElementById("pump_slip_preview").style.display = "block";
                    }

                    document.getElementById("pump_slip").value = fileName;

                    alert("File uploaded!");

                } else {
                    alert("Upload failed");
                }
            };

            xhr.send(formData);
        }
    </script>

    <div style="display: flex; flex-direction: column; width: 100%; align-items: center;">
        <label for="" 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 htmlspecialchars($repair_data['problem_description']); ?></textarea>
    </div>

    <div style="display: flex; flex-direction: column; width: 100%; align-items: center;">
        <label for="" class="create_details_label" style="width: 100%;">SOLUTION</label>
        <textarea name="problem_solution" id="problem_solution" rows="5" class="create_details_input"
        style="font-size: 3em;"><?php echo htmlspecialchars($repair_data['problem_solution']); ?></textarea>
    </div>

    <div style="display: flex; flex-direction: column; width: 100%; align-items: center;">
        <label for="" class="create_details_label" style="width: 100%;">REPAIRED BY</label>
        <input type="text" name="repaired_by" id="repaired_by" class="create_details_input"
        value="<?php echo htmlspecialchars($repair_data['repaired_by']); ?>">
        <input type="text" name="status" id="status" class="create_details_input" value="1" hidden>
        <input type="text" name="record_id" id="record_id" class="create_details_input"
        value="<?php echo $_GET['record_id']; ?>" hidden>

        <input type="text" name="date_time_finished" id="date_time_finished" class="create_details_input"
        value="<?php echo date("Y-m-d H:i", strtotime("+2 hours")); ?>" hidden>
    </div>

<?php

    $complete_jobcard = new button();
    $complete_jobcard->value('COMPLETE');
    $complete_jobcard->onclick('submit_jobcard()');
    $complete_jobcard->add();

    $submit_details = new js_ajax();
    $submit_details->function_name("submit_jobcard");
    $submit_details->update("pump_repair");
    $submit_details->selected_div(".main_div input , .main_div select");
    $submit_details->exclude_inputs("['pump_slip_type']");
    $submit_details->redirect('../pump/repair_summary.php?record_id=' . $_GET['record_id'] . '&jobcard_no=' . $_GET['jobcard_no']);
    $submit_details->on_success("JOBCARD COMPLETE");

?>
</div>

<script>
    function check_empty() {
        var attended_by = document.getElementById('attended_by').value;
        var problem_description = document.getElementById('problem_description').value;
        var problem_solution = document.getElementById('problem_solution').value;

        if (attended_by == "") {
            alert("Please fill in all fields");
            return false;
        } else if (problem_description == "") {
            alert("Problem description field cannot be empty");
            return false;
        } else if (problem_solution == "") {
            alert("Problem solution field cannot be empty");
            return false;
        } else {
            return true;
        }
    }

    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>
