<?php include "../../../root.class.php";
$html = new html();
$html->add_styles_page();
$db = new db_safeguard();
session_start();

$jobcard_data_res = $db->query("pump_installation", "SELECT * FROM pump_installation WHERE record_id = '{$_GET['record_id']}'");
$jobcard_data = $jobcard_data_res->fetch_assoc();

$jobcard_history_res = $db->query("jobcards", "SELECT * FROM jobcards WHERE jc_no = '{$jobcard_data['drilling_invoice']}'");
$jobcard_history = $jobcard_history_res->fetch_assoc();

$user_res = $db->query("users", "SELECT * FROM users WHERE record_id = '{$_SESSION['user_id']}'");
$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;
    }

    td {
        padding: 10px;
        border: 3px solid black;
        text-align: left;
        background-color: white;
    }
</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();

        $data_type = new input();
        $data_type->class("inputs");
        $data_type->type("hidden");
        $data_type->readonly();
        $data_type->value($data['type']);
        $data_type->add();

        $date_time->add();
        $notes_label->add();
        ?>

        <div style="display: flex; flex-direction: column;">
            <?php
            $reasons_label->add();
            $reasons->add();
            $notes_sub_label->add();
            ?>
        </div>

        <input type="text" id="jobcard_id" name="jobcard_id" value="<?php echo $_GET['jc_no']; ?>" hidden>
        <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>

            <?php
            // new camera('notes_image', $_GET['jc_no'], "../jobcards/pump/notes/", "notes_images");
            ?>

            <div style='display:flex; flex-direction: column; width: 100%; align-items: center;'>

                <?php
                $notes_image_label->add();

                // new camera('notes_image_image', $_GET['record_id'], '../jobcards/notes_image/', 'notes_image');
                
                ?>

                <video style="display: none; width: 90%;" id="camera_notes_image" autoplay playsinline></video>
                <br>

                <button id="open_camera_notes_image" class="submit_btn" onclick="openNotesCamera()">Open
                    Camera</button>

                <div id="load_camera_notes_image" style="display: none; width: 100%; justify-content: center;">
                    <button class="submit_btn" onclick="captureNotesPhoto()">Capture Photo</button>
                    <button class="submit_btn" onclick="stopNotesCamera()">Stop Camera</button>
                </div>

                <div id="captured_image_notes_image" style="display:none">
                    <h3>Captured Image:</h3>
                    <canvas id="snapshot_notes_image"></canvas>
                </div>

                <script>
                    let stream_notes_image;

                    async function openNotesCamera() {
                        const video = document.getElementById("camera_notes_image");
                        const load_camera = document.getElementById("load_camera_notes_image");
                        const open_camera = document.getElementById("open_camera_notes_image");

                        try {
                            stream_notes_image = await navigator.mediaDevices.getUserMedia({
                                video: { facingMode: "environment" },
                                audio: false
                            });

                            video.srcObject = stream_notes_image;
                            video.style.display = "block";
                            load_camera.style.display = "flex";
                            open_camera.style.display = "none";

                        } catch (error) {
                            alert("Error accessing camera: " + error.message);
                        }
                    }

                    function captureNotesPhoto() {
                        const video = document.getElementById("camera_notes_image");
                        const canvas = document.getElementById("snapshot_notes_image");
                        const context = canvas.getContext("2d");
                        const load_camera = document.getElementById("load_camera_notes_image");
                        const record_id = "<?php echo htmlspecialchars($_GET['record_id']); ?>";

                        // DEBUG: confirm record_id has a value
                        console.log("Capturing photo for jobcard:", record_id);

                        load_camera.style.display = "none";
                        canvas.width = video.videoWidth;
                        canvas.height = video.videoHeight;
                        context.drawImage(video, 0, 0, canvas.width, canvas.height);

                        const imageData = canvas.toDataURL("image/png");

                        // DEBUG: confirm image data was captured
                        console.log("Image data length:", imageData.length);

                        stopNotesCamera();
                        saveCapturedNotesImage(imageData, record_id);
                    }

                    function stopNotesCamera() {
                        const open_camera = document.getElementById("open_camera_notes_image");
                        const load_camera = document.getElementById("load_camera_notes_image");
                        const video = document.getElementById("camera_notes_image");

                        video.style.display = "none";
                        load_camera.style.display = "none";
                        open_camera.style.display = "block";

                        if (stream_notes_image) {
                            stream_notes_image.getTracks().forEach(track => track.stop());
                            stream_notes_image = null;
                            video.srcObject = null;
                        }
                    }

                    function saveCapturedNotesImage(imageData, record_id) {
                        const folder_path = "../jobcards/pump/notes/";
                        const section_name = "notes_image";

                        // DEBUG: confirm values before sending
                        console.log("Saving image | record_id:", record_id, "| folder:", folder_path);

                        var formData = new FormData();
                        formData.append('image', imageData);
                        formData.append('record_id', record_id);
                        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.onreadystatechange = function () {
                            if (xhr.readyState == 4) {
                                console.log("Server response status:", xhr.status);
                                console.log("Server response text:", xhr.responseText);

                                if (xhr.status == 200) {
                                    const response = xhr.responseText.trim();

                                    if (response !== '0' && response !== '') {
                                        const fileName = response;
                                        const imagePath = folder_path + fileName;

                                        // Show image preview
                                        const preview = document.getElementById('notes_image_preview');
                                        preview.src = imagePath;
                                        preview.style.display = 'block';
                                        preview.style.width = '80%';
                                        preview.style.marginTop = '10px';

                                        // Store filename in hidden input
                                        document.getElementById('image').value = fileName;

                                        alert('Photo saved successfully: ' + fileName);
                                    } else {
                                        alert('Error saving photo. Server said: ' + response);
                                    }
                                } else {
                                    alert('HTTP error: ' + xhr.status);
                                }
                            }
                        };

                        xhr.send(formData);
                    }

                </script>

                <img src="" id="notes_image_preview" style="display:none;" />
                <!-- <input type='text' style="display: none;" class="inputs" id='image' name='image'> -->
            </div>

            <input type="text" style="display: flex;" id="image" name="image">

            <!-- SAVE NOTE BUTTON -->
            <?php
            $add_notes->add();
            ?>

            <div id="note_save_response" style="color:white; margin-top:10px; font-weight:bold;"></div>

            <!-- NOTES HISTORY TABLE -->
            <div
                style="background-color: white; padding-left: 2vw; padding-top: 2vw; width: 100%; margin-top:20px; overflow-x: auto; box-sizing: border-box;">
                <table id="notes_table"
                    style="width: 100%; table-layout: fixed; border-collapse: collapse; word-wrap: break-word;">
                    <colgroup>
                        <col style="width: 20%;">
                        <col style="width: 40%;">
                        <col style="width: 20%;">
                        <col style="width: 20%;">
                    </colgroup>
                    <tr>
                        <th>REASON</th>
                        <th>NOTE</th>
                        <th>IMAGE</th>
                        <th>DATE TIME</th>
                    </tr>
                    <?php
                    $table_data = "";
                    $notes_res = $db->query("notes", "SELECT * FROM notes WHERE jobcard_id = '{$_GET['jc_no']}' AND reason NOT LIKE '%BIT%' AND reason NOT LIKE '%INSTALL%'");

                    if ($notes_res->num_rows > 0) {
                        while ($row = $notes_res->fetch_assoc()) {
                            $image_cell = $row['image'] ? "<img src='/app/jobcards/pump/notes/" . htmlspecialchars($row['image']) . "' style='width:100px; height:auto;'>" : '';
                            $table_data .= "<tr>
                    <td style='word-break: break-word; padding: 6px;'>" . htmlspecialchars($row['reason']) . "</td>
                    <td style='word-break: break-word; padding: 6px;'>" . htmlspecialchars($row['note']) . "</td>
                    <td style='padding: 6px;'>" . $image_cell . "</td>
                    <td style='word-break: break-word; padding: 6px;'>" . htmlspecialchars($row['date_time']) . "</td>
                </tr>";
                        }
                    } else {
                        $table_data = "<tr><td colspan='4' style='padding: 6px;'>NO NOTES RECORDED</td></tr>";
                    }
                    echo $table_data;
                    ?>
                </table>
                <br>
            </div>
        </div>
    </div>
    <br><br>
</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['jc_no'] . "-" . $_SESSION['user_id'] . "-signature.png";
            $employee_url = $target_url . "employee-jc_" . $_GET['jc_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['jc_no'] . "-" . $_SESSION['user_id'] . "-signature.png";
            $client_url = $target_url . "client-jc_" . $_GET['jc_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("../jobcards/pump/signatures/employee-jc_" . $_GET['jc_no'] . "-" . $_SESSION['user_id'] . "-signature.png") ||
                !file_exists("../jobcards/pump/signatures/client-jc_" . $_GET['jc_no'] . "-" . $_SESSION['user_id'] . "-signature.png")
            ) {

            } else {
                echo "<button type='button' id='save_signatures' class='save_sign_btn' >SAVED</button>";
            }
            ?>
        </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['jc_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">

    <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 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="captured_image_install_${i}" style="display:none">
                        <h3>Captured Image:</h3>
                        <canvas id="snapshot_install_${i}"></canvas>
                    </div>
                    // <img src="" id="install_${i}_preview" style="display:none; width:80%; margin-top:10px;" />
                    <label style="color:black; margin-top:10px;" class="create_details_label">DESCRIPTION</label>
                    <textarea 
                        id="install_${i}_description" 
                        name="install_${i}_description"
                        rows="5" cols="70"
                        placeholder="Enter image description..."
                        class="inputs"
                        style="width:100%; margin-top:5px; font-size:2em;">
                    </textarea>
                    <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}`);
            const jobcard_no = "<?php echo $_GET['jc_no']; ?>";

            canvas.width = video.videoWidth;
            canvas.height = video.videoHeight;
            ctx.drawImage(video, 0, 0);

            load.style.display = "none";

            const imageData = canvas.toDataURL("image/png");

            stopInstallCamera(i);
            saveCapturedImage(imageData, jobcard_no, i);
        }

        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 saveCapturedImage(imageData, jobcard_no, i) {
            const folder_path = "";
            const description = document.getElementById(`install_${i}_description`).value.trim();
            const record_id = "<?php echo $_GET['record_id']; ?>";

            if (description === '') {
                alert("Please add a description before saving.");
                return;
            }

            var formData = new FormData();
            formData.append("image", imageData);
            formData.append("jobcard_no", jobcard_no);
            formData.append("folder_path", folder_path);
            formData.append("section_name", "install");
            formData.append("description", description);
            formData.append("record_id", record_id);

            const xhr = new XMLHttpRequest();
            xhr.open("POST", "save_cam_image.php", true);
            xhr.onload = function () {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    const fileName = xhr.responseText.trim();
                    if (fileName != '0' && fileName != '') {
                        const preview = document.getElementById(`install_${i}_preview`);
                        preview.src = "/app/jobcards/pump/install_images/" + fileName;
                        preview.style.display = "block";

                        document.getElementById(`install_${i}_image`).value = fileName;
                        document.getElementById(`install_${i}_description`).value = '';

                        alert('Photo saved successfully!');
                        loadImageHistory();
                    } else {
                        alert("Error saving image");
                    }
                }
            };
            xhr.send(formData);
        }

        function loadImageHistory() {
            const jobcard_no = "<?php echo $_GET['jc_no']; ?>";

            const xhr = new XMLHttpRequest();
            xhr.open("POST", "get_install_images.php", true);
            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            xhr.onload = function () {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    document.getElementById("image_history_grid").innerHTML = xhr.responseText;
                }
            };
            xhr.send("jobcard_no=" + encodeURIComponent(jobcard_no));
        }

        function saveNote() {
            const jobcard_no = "<?php echo $_GET['jc_no']; ?>";
            const reason = document.getElementById('reason').value.trim();
            const note = document.getElementById('note').value.trim();
            const image = document.getElementById('image').value.trim();
            const date_time = "<?php echo $current_date_time; ?>";
            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);
            formData.append("date_time", date_time);

            const xhr = new XMLHttpRequest();
            xhr.open("POST", "save_note.php", true);
            xhr.onload = function () {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    const res = xhr.responseText.trim();
                    if (res === '1') {
                        responseDiv.innerHTML = "✔ NOTE SAVED";
                        responseDiv.style.color = "lightgreen";

                        // clear fields
                        document.getElementById('note').value = '';
                        document.getElementById('image').value = '';

                        // reload table
                        loadNotesTable();
                    } else {
                        responseDiv.innerHTML = "✘ ERROR SAVING NOTE";
                        responseDiv.style.color = "red";
                    }
                }
            };
            xhr.send(formData);
        }

        function loadNotesTable() {
            const jobcard_no = "<?php echo $_GET['jc_no']; ?>";

            const xhr = new XMLHttpRequest();
            xhr.open("POST", "get_notes.php", true);
            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            xhr.onload = function () {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    const res = xhr.responseText.trim();
                    const table = document.getElementById('notes_table');

                    // replace everything after the header row
                    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;
                    }

                    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>
                        `;
                    });
                }
            };
            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="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 for="" class="create_details_label" style="width: 100%;">CLIENT NAME</label>
        <input type="text" name="client_name" id="client_name" class="create_details_input"
            value="<?php echo $jobcard_history['client_name']; ?>">
    </div>

    <div style="display: flex; flex-direction: column; width: 100%; align-items: center;">
        <label for="" class="create_details_label" style="width: 100%;">AREA</label>
        <input type="text" name="area" id="area" class="create_details_input"
            value="<?php echo $jobcard_history['address']; ?>">
    </div>

    <div style="display: flex; flex-direction: column; width: 100%; align-items: center;">
        <label for="" class="create_details_label" style="width: 100%;">CONTACT NUMBER</label>
        <input type="text" name="contact_number" id="contact_number" class="create_details_input"
            value="<?php echo $jobcard_history['contact_number']; ?>">
    </div>

    <div style="display: flex; flex-direction: column; width: 100%; align-items: center;">
        <label for="" class="create_details_label" style="width: 100%;">ATTENDED BY</label>
        <input type="text" name="attended_by" id="attended_by" class="create_details_input"
            value="<?php echo htmlspecialchars($jobcard_data['attended_by']); ?>">
    </div>

    <div style="display: flex; flex-direction: column; width: 100%; align-items: center;">
        <label for="" class="create_details_label" style="width: 100%;">CRACK</label>
        <input type="text" name="crack" id="crack" class="create_details_input"
            value="<?php echo htmlspecialchars($jobcard_data['crack']); ?>">
    </div>

    <div style="display: flex; flex-direction: column; width: 100%; align-items: center;">
        <label for="" class="create_details_label" style="width: 100%;">METERS DRILLED</label>
        <input type="text" name="meters_drilled" id="meters_drilled" class="create_details_input"
            value="<?php echo htmlspecialchars($jobcard_data['meters_drilled']); ?>">
    </div>

    <div style="display: flex; flex-direction: column; width: 100%; align-items: center;">
        <label for="" class="create_details_label" style="width: 100%;">PUMP DEPTH</label>
        <input type="text" name="pump_depth" id="pump_depth" class="create_details_input"
            value="<?php echo htmlspecialchars($jobcard_data['pump_depth']); ?>">
    </div>

    <div style='display:flex; flex-direction: column; width: 100%; align-items: center;'>

        <?php
        $pump_slip_label->add();

        // new camera('pump_slip_image', $_GET['record_id'], '../jobcards/pump_slip/', 'pump_slip');
        
        ?>

        <video style="display: none;" id="camera_pump_slip" autoplay playsinline></video>
        <br>

        <button id="open_camera_pump_slip" class="submit_btn" onclick="openSlipCamera()">Open
            Camera</button>

        <div id="load_camera_pump_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_pump_slip" style="display:none">
            <h3>Captured Image:</h3>
            <canvas id="snapshot_pump_slip"></canvas>
        </div>

        <script>
            let stream_pump_slip;

            async function openSlipCamera() {
                const video = document.getElementById("camera_pump_slip");
                const load_camera = document.getElementById("load_camera_pump_slip");
                const open_camera = document.getElementById("open_camera_pump_slip");

                try {

                    stream_pump_slip = await navigator.mediaDevices.getUserMedia({
                        video: { facingMode: "environment" },
                        audio: false
                    });

                    const video = document.getElementById("camera_pump_slip");
                    video.srcObject = stream_pump_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_pump_slip");
                const canvas = document.getElementById("snapshot_pump_slip");
                const context = canvas.getContext("2d");
                const captured_image = document.getElementById("captured_image_pump_slip");
                const load_camera = document.getElementById("load_camera_pump_slip");
                const jobcard_no = "<?php echo $_GET['jc_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_pump_slip");
                const load_camera = document.getElementById("load_camera_pump_slip");
                const video = document.getElementById("camera_pump_slip");

                video.style.display = "none";
                load_camera.style.display = "none";
                open_camera.style.display = "block";
                if (stream_pump_slip) {
                    stream_pump_slip.getTracks().forEach(track => track.stop());
                    stream_pump_slip = null;
                    document.getElementById("camera_pump_slip").srcObject = null;
                }
            }

            function saveCapturedSlipImage(imageData, jobcard_no) {
                const video = document.getElementById("camera_pump_slip");
                const folder_path = "/app/jobcards/pump/pump_slip/";
                const section_name = "pump_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', '/app/jobcards/pump/save_notes_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 ('pump_slip' != '') {

                                const fileName = xhr.responseText.trim();
                                const imagePath = folder_path + fileName;

                                // show image preview
                                const preview = document.getElementById('pump_slip_preview');
                                preview.src = imagePath;
                                preview.style.display = 'block';
                                preview.style.width = '80%';
                                preview.style.marginTop = '10px';

                                // store filename in hidden input
                                document.getElementById('pump_slip').value = fileName;

                                document.getElementById('pump_slip').style.display = 'block';
                                document.getElementById('pump_slip').value = xhr.responseText;
                            }
                        } else {
                            alert('Error saving photo!');

                        }
                    }
                };
                xhr.send(formData);
            }
        </script>

        <img src="" id="pump_slip_preview" style="display:none;" />
        <input type='text' style="display: none;" class="inputs" id='pump_slip' name='pump_slip'>
    </div>

    <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($jobcard_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($jobcard_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%;">INSTALLED BY</label>
        <input type="text" name="installed_by" id="installed_by" class="create_details_input"
            value="<?php echo htmlspecialchars($users['username']); ?>">
        <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('finish_installation()');
    $complete_jobcard->add();

    $complete_ajax = new js_ajax();
    $complete_ajax->function_name("finish_installation");
    $complete_ajax->update("pump_installation");
    $complete_ajax->selected_div(".main_div input, .main_div select, .main_div textarea");
    $complete_ajax->on_success("JOBCARD COMPLETED");
    $complete_ajax->redirect('../pump/install_summary.php?record_id=' . $_GET['record_id'] . '&jobcard_no=' . $_GET['jobcard_no']);
    ?>
</div>

<script>
    function check_empty() {
        var attended_by = document.getElementById('attended_by').value;
        var crack = document.getElementById('crack').value;
        var cable_meters = document.getElementById('cable_meters').value;
        var hdpe_meters = document.getElementById('hdpe_meters').value;
        var borehole_meters = document.getElementById('borehole_meters').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 {
            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>