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

$date_time = date("Y-m-d H:i", strtotime("+2 hours"));

?>

<div class="form_down">
    <!-- <h1>CURRENT PROCESS</h1> -->
    <link rel="manifest" href="manifest.json">

    <style>
        #connection-banner {
            position: fixed;
            top: 5px;
            left: 0;
            right: 3vw;
            background-color: red;
            color: white;
            text-align: center;
            padding: 10px;
            font-weight: bold;
            z-index: 1000;
            display: none;
        }

        #connection-banner.online {
            background-color: green;
        }
    </style>

    <div id="connection-banner">🔴 YOU ARE OFFLINE</div>

    <?php

    $record_res = $db->query("jobcards", "SELECT * FROM jobcards WHERE record_id = {$_GET['record_id']}");
    $record = $record_res->fetch_assoc();

    $res_data = $db->query("jobcard_timeline", "SELECT * FROM jobcard_timeline WHERE jobcard_id = {$record['record_id']} AND type != 'CASING_START' AND type != 'CASING_STOP' ORDER BY record_id DESC LIMIT 1");
    $data = $res_data->fetch_assoc();

    $record_id = new input();
    $record_id->class("inputs");
    $record_id->type("hidden");
    $record_id->readonly();
    $record_id->name("record_id");
    $record_id->id("record_id");
    $record_id->value($record['record_id']);
    $record_id->add();

    $status = new input();
    $status->value(1);
    $status->id("status");
    $status->name("status");
    $status->type("hidden");

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

    $riem = new button();
    $riem->value("RIEMING");

    $drilling = new button();
    $drilling->value("DRILLING");

    $blasting = new button();
    $blasting->value("BLASTING");

    $jobcard_done = new button();
    $jobcard_done->value("COMPLETE");

    $make_note = new button();
    $make_note->value("MAKE NOTE");
    $make_note->onclick("open_notesPopup()");
    $make_note->id("make_note");

    if ($data['type'] == "RIEMING_START") {
        ?>
        <h1>CURRENT PROCESS</h1>
        <?php
        $make_note->add();
        ?>

        <button type="submit" class="submit_btn" onclick="reiming()">RIEMING</button>

        <?php
        $reaming_ajax = new js_ajax();
        $reaming_ajax->function_name("reiming");
        $reaming_ajax->insert("jobcard_timeline");
        $reaming_ajax->selected_div("timeline");
        $reaming_ajax->add_column_and_value("jobcard_id={$_GET['record_id']},date_time=" . $date_time . ",type=RIEMING,user_id={$_SESSION['user_id']}");
        $reaming_ajax->on_success("RIEMING");
        $reaming_ajax->redirect("../jobcards/rieming.php?record_id={$record['record_id']}&jc_no={$_GET['jobcard_id']}");

    } else if ($data['type'] == "DRILLING_START") {
        ?>
            <h1>CURRENT PROCESS</h1>
            <?php
            $make_note->add();

            ?>
            <div id="floating-block">
                <?php
                $last_meters = $db->query("jobcard_timeline", "SELECT * FROM jobcard_timeline WHERE jobcard_id={$_GET['record_id']} ORDER BY record_id DESC");

                // echo "SELECT * FROM jobcard_timeline WHERE jobcard_id={$_GET['record_id']} ORDER BY record_id DESC";
            
                $riem_meters = 0;
                $drilling_meters = 0;
                $casing_meters = 0;
                $blasting_meters = 0;

                while ($meters_data = $last_meters->fetch_assoc()) {
                    if ($meters_data['type'] == "RIEM_STOP" || $meters_data['type'] == "RIEMING_STOP" || $meters_data['type'] == "RIEMING_PAUSED") {
                        $riem_meters += $meters_data['meters'];
                    }

                    if ($meters_data['type'] == "DRILLING_STOP" || $meters_data['type'] == "DRILLING_PAUSE") {
                        $drilling_meters += $meters_data['meters'];
                    }

                    if ($meters_data['type'] == "CASING_STOP" || $meters_data['type'] == "CASING_PAUSE") {
                        $casing_meters += $meters_data['meters'];
                    }

                    if ($meters_data['type'] == "BLASTING_START" || $meters_data['type'] == "BLASTING_STOP") {
                        $blasting_meters += $meters_data['meters'];
                    }
                }

                ?>
                <div>
                    <h3>CURRENT TOTAL METERS: </h3>
                    <h3>TOTAL RIEMING: <?php echo $riem_meters; ?> METERS</h3>
                    <h3>TOTAL DRILLING: <?php echo $drilling_meters; ?> METERS</h3>
                    <h3>TOTAL CASING: <?php echo $casing_meters; ?> METERS</h3>
                    <h3>TOTAL BLASTING: <?php echo $blasting_meters; ?> METERS</h3>
                </div>

            </div>

            <button type="submit" class="submit_btn" onclick="drilling()">DRILLING</button>

            <?php
            $drilling_ajax = new js_ajax();
            $drilling_ajax->function_name("drilling");
            $drilling_ajax->insert("jobcard_timeline");
            $drilling_ajax->selected_div("timeline");
            $drilling_ajax->add_column_and_value("jobcard_id={$_GET['record_id']},date_time=" . $date_time . ",type=DRILLING,user_id={$_SESSION['user_id']}");
            $drilling_ajax->on_success("DRILLING");
            $drilling_ajax->redirect("../jobcards/drilling.php?record_id={$record['record_id']}&jc_no={$_GET['jobcard_id']}");
            ?>

        <?php
    } else if ($data['type'] == "BLASTING_START") {
        ?>
                <h1>CURRENT PROCESS</h1>
            <?php
            $make_note->add();

            ?>
                <div id="floating-block">
                <?php
                $last_meters = $db->query("jobcard_timeline", "SELECT * FROM jobcard_timeline WHERE jobcard_id={$_GET['record_id']} ORDER BY record_id DESC");

                // echo "SELECT * FROM jobcard_timeline WHERE jobcard_id={$_GET['record_id']} ORDER BY record_id DESC";
            
                $riem_meters = 0;
                $drilling_meters = 0;
                $casing_meters = 0;
                $blasting_meters = 0;

                while ($meters_data = $last_meters->fetch_assoc()) {
                    if ($meters_data['type'] == "RIEM_STOP" || $meters_data['type'] == "RIEMING_STOP" || $meters_data['type'] == "RIEMING_PAUSED") {
                        $riem_meters += $meters_data['meters'];
                    }

                    if ($meters_data['type'] == "DRILLING_STOP" || $meters_data['type'] == "DRILLING_PAUSE") {
                        $drilling_meters += $meters_data['meters'];
                    }

                    if ($meters_data['type'] == "CASING_STOP" || $meters_data['type'] == "CASING_PAUSE") {
                        $casing_meters += $meters_data['meters'];
                    }

                    if ($meters_data['type'] == "BLASTING_START" || $meters_data['type'] == "BLASTING_STOP") {
                        $blasting_meters += $meters_data['meters'];
                    }
                }

                ?>
                    <div>
                        <h3>CURRENT TOTAL METERS: </h3>
                        <h3>TOTAL RIEMING: <?php echo $riem_meters; ?> METERS</h3>
                        <h3>TOTAL DRILLING: <?php echo $drilling_meters; ?> METERS</h3>
                        <h3>TOTAL CASING: <?php echo $casing_meters; ?> METERS</h3>
                        <h3>TOTAL BLASTING: <?php echo $blasting_meters; ?> METERS</h3>
                    </div>

                </div>

                <button type="submit" class="submit_btn" onclick="blasting()">BLASTING</button>
            <?php
            $blasting_ajax = new js_ajax();
            $blasting_ajax->function_name("blasting");
            $blasting_ajax->insert("jobcard_timeline");
            $blasting_ajax->selected_div("timeline");
            $blasting_ajax->add_column_and_value("jobcard_id={$_GET['record_id']},date_time=" . $date_time . ",type=BLASTING,user_id={$_SESSION['user_id']}");
            $blasting_ajax->on_success("BLASTING");
            $blasting_ajax->redirect("../jobcards/processing.php?record_id={$record['record_id']}&jc_no={$_GET['jobcard_id']}");
            ?>
        <?php
    } else if ($data['type'] == "CASING_START") {
        ?>
                    <h1>CURRENT PROCESS</h1>
            <?php
            $make_note->add();

            ?>

                    <div id="floating-block">
                <?php
                $last_meters = $db->query("jobcard_timeline", "SELECT * FROM jobcard_timeline WHERE jobcard_id={$_GET['record_id']} ORDER BY record_id DESC");

                // echo "SELECT * FROM jobcard_timeline WHERE jobcard_id={$_GET['record_id']} ORDER BY record_id DESC";
            
                $riem_meters = 0;
                $drilling_meters = 0;
                $casing_meters = 0;
                $blasting_meters = 0;

                while ($meters_data = $last_meters->fetch_assoc()) {
                    if ($meters_data['type'] == "RIEM_STOP" || $meters_data['type'] == "RIEMING_STOP" || $meters_data['type'] == "RIEMING_PAUSED") {
                        $riem_meters += $meters_data['meters'];
                    }

                    if ($meters_data['type'] == "DRILLING_STOP" || $meters_data['type'] == "DRILLING_PAUSE") {
                        $drilling_meters += $meters_data['meters'];
                    }

                    if ($meters_data['type'] == "CASING_STOP" || $meters_data['type'] == "CASING_PAUSE") {
                        $casing_meters += $meters_data['meters'];
                    }

                    if ($meters_data['type'] == "BLASTING_START" || $meters_data['type'] == "BLASTING_STOP") {
                        $blasting_meters += $meters_data['meters'];
                    }
                }

                ?>
                        <div>
                            <h3>CURRENT TOTAL METERS: </h3>
                            <h3>TOTAL RIEMING: <?php echo $riem_meters; ?> METERS</h3>
                            <h3>TOTAL DRILLING: <?php echo $drilling_meters; ?> METERS</h3>
                            <h3>TOTAL CASING: <?php echo $casing_meters; ?> METERS</h3>
                            <h3>TOTAL BLASTING: <?php echo $blasting_meters; ?> METERS</h3>
                        </div>

                    </div>

                    <button type="submit" class="submit_btn" onclick="casing()">CASING</button>

            <?php
            $casing_ajax = new js_ajax();
            $casing_ajax->function_name("casing");
            $casing_ajax->insert("jobcard_timeline");
            $casing_ajax->selected_div("timeline");
            $casing_ajax->add_column_and_value("jobcard_id={$_GET['record_id']},date_time=" . $date_time . ",type=CASING,user_id={$_SESSION['user_id']}");
            $casing_ajax->on_success("CASING");
            $casing_ajax->redirect("../jobcards/casing.php?record_id={$record['record_id']}&jc_no={$_GET['jobcard_id']}");


    } else if ($data['type'] == "COMPLETE") {

        $riem->disabled();
        $riem->style("background-color: #00008045; color: white;");

        $drilling->disabled();
        $drilling->style("background-color: #00008045; color: white;");

        $blasting->disabled();
        $blasting->style("background-color: #00008045; color: white;");

        $diesel_stop = new input();
        $diesel_stop->id("diesel_stop");
        $diesel_stop->name("diesel_stop");
        $diesel_stop->class("inputs");
        $diesel_stop->placeholder("Diesel Stop");

        $compressor_hours = new input();
        $compressor_hours->id("compressor_hours");
        $compressor_hours->name("compressor_hours");
        $compressor_hours->class("inputs");
        $compressor_hours->placeholder("Compressor Hours");

        $water_strike = new input();
        $water_strike->id("water_strike");
        $water_strike->name("water_strike");
        $water_strike->class("inputs");
        $water_strike->placeholder("Water Strike");

        $water_flow = new input();
        $water_flow->id("water_flow");
        $water_flow->name("water_flow");
        $water_flow->class("inputs");
        $water_flow->placeholder("Water Flow");

        $interested_in_pump = new select();
        $interested_in_pump->id("interested_in_pump");
        $interested_in_pump->name("interested_in_pump");
        $interested_in_pump->class("inputs");
        $interested_in_pump->add_option("", "Interested in Pump");
        $interested_in_pump->add_option("Yes", "Yes");
        $interested_in_pump->add_option("No", "No");

        $break_found_one = new input();
        $break_found_one->type("number");
        $break_found_one->id("break_found_on");
        $break_found_one->name("break_found_on");
        $break_found_one->class("inputs");
        $break_found_one->placeholder("Break Found On");

        $payment_label = new label();
        $payment_label->for("payment");
        $payment_label->value("PAYMENT TYPE");
        $payment_label->addAttribute("style", "font-size: 1.5em;");

        $payment_method = new select();
        $payment_method->class("inputs");
        $payment_method->name("payment_method");
        $payment_method->id("payment_method");
        $payment_method->onchange("payment_type()");
        $payment_method->add_option("", "Payment Method");
        $payment_method->add_option("CASH", "CASH");
        $payment_method->add_option("EFT", "EFT");

        $amount_label = new label();
        $amount_label->for("amount");
        $amount_label->value("Amount");
        $amount_label->addAttribute("style", "font-size: 1.5em;");

        $amount = new input();
        $amount->type("number");
        $amount->class("inputs");
        $amount->placeholder("Amount");
        $amount->name("cash_amount");
        $amount->id("cash_amount");

        $sample_label = new label();
        $sample_label->for("sample_image_label");
        $sample_label->value("Sample Image");
        $sample_label->addAttribute("style", "font-size: 1.5em;");

        $client_merch_label = new label();
        $client_merch_label->for("client_merch_image_label");
        $client_merch_label->value("Client Merch Image");
        $client_merch_label->addAttribute("style", "font-size: 1.5em;");

        $complete = new button();
        $complete->value("COMPLETE");
        $complete->id("complete");
        $complete->style("width:25vw;");

        $clear_btn = new Button();
        $clear_btn->class("sign_btn");
        $clear_btn->value("CLEAR");
        $clear_btn->style("margin-bottom:10vh;");
        $clear_btn->onclick("client_pad.clear()");

        $save_btn = new Button();
        $save_btn->value("SAVE");
        $save_btn->class("sign_btn");
        $save_btn->id("save_signatures");

        $clear_btn1 = new Button();
        $clear_btn1->value("CLEAR");
        $clear_btn1->class("sign_btn");
        $clear_btn1->style("margin-bottom:10vh;");

        $clear_btn1->onclick("employee_pad.clear()");

        ?>
                        <div style="display: flex; flex-direction: column;">
                            <h1>CURRENT PROCESS</h1>

                            <div class="jobcard_work">
                    <?php
                    $riem->add();
                    $drilling->add();
                    $blasting->add();
                    ?>
                            </div>
                            <div class="down_form" id="signatures" style="padding: 4vw; margin-top: 3vw;">
                                <h1 class="sign_h1">SIGNATURES</h1>
                                <div class="list_inputs">
                                    Please Note: Savuki Drilling Mpumalanga
                                    <ul>
                                        <li>1. Cannot be held responsible for any damage or borehole collapse.</li>
                                        <li>2. Steel casings must be installed on the recommendation of the drill team.</li>
                                        <li>3. Will not be held liable for any damage on property.</li>
                                        <li>4. No water is guaranteed even if Savuki Drilling surveyed.</li>
                                        <li>5. Client pays for service of drilling, not water.</li>
                                    </ul>
                                    <b><i>SAFETY PRECAUTION - <br> CUSTOMER IS RESPONSIBLE FOR COVERING OF BOREHOLE AFTER DRILLING.<br>
                                            SAVUKI
                                            DRILLING MPUMALANGA WILL NOT BE LIABLE FOR ANY ACCIDENTS CAUSED BY ANY UNCOVERED
                                            BOREHOLES.</i></b>
                                </div>

                                <div class='div_signatures'>
                                    <div class="sub_down">

                                        <script src="https://cdn.jsdelivr.net/npm/signature_pad@2.3.2/dist/signature_pad.min.js"></script>

                            <?php
                            // EMPLOYEE SIGNATURE
                            if (file_exists("../jobcards/signatures/employee-jc" . $record['jc_no'] . "-" . $_SESSION['user_id'] . "-signature.png")) {
                                ?>
                                            <div class='jobcard_work_signature' style='margin-bottom:1vw;'>
                                                <h2>EMPLOYEE SIGNATURE</h2>
                                                <input type='image'
                                                    src='../jobcards/signatures/employee-jc<?php echo $record['jc_no']; ?>-<?php echo $_SESSION['user_id']; ?>-signature.png'
                                                    alt='employee signature' class="signature_image">
                                            </div>
                            <?php
                            } else {
                                ?>
                                            <div class='jobcard_work_signature' style='margin-bottom:1vw;'>
                                                <h2>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
                            if (file_exists("../jobcards/signatures/client-jc" . $record['jc_no'] . "-" . $_SESSION['user_id'] . "-signature.png")) {
                                ?>
                                            <div class='jobcard_work_signature' style='margin-bottom:1vw;'>
                                                <h2>CLIENT SIGNATURE</h2>
                                                <input type="image"
                                                    src="../jobcards/signatures/client-jc<?php echo $record['jc_no']; ?>-<?php echo $_SESSION['user_id']; ?>-signature.png"
                                                    alt="client signature" class="signature_image">
                                            </div>
                            <?php
                            } else {
                                ?>
                                            <div class='jobcard_work_signature' style='margin-bottom:1vw;'>
                                                <h2>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
                            }
                            ?>

                                        <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 = document.getElementById("jobcard_id")?.value;

                                                function resizeCanvas(canvas) {
                                                    if (!canvas) return;
                                                    const ratio = Math.max(window.devicePixelRatio || 1, 1);
                                                    // use getBoundingClientRect to respect CSS height/width
                                                    const rect = canvas.getBoundingClientRect();
                                                    canvas.width = rect.width * ratio;
                                                    canvas.height = rect.height * ratio;
                                                    const ctx = canvas.getContext("2d");
                                                    ctx.scale(ratio, ratio);
                                                }

                                                resizeCanvas(clientCanvas);
                                                resizeCanvas(employeeCanvas);

                                                window.addEventListener("resize", () => {
                                                    resizeCanvas(clientCanvas);
                                                    resizeCanvas(employeeCanvas);
                                                });

                                                // Improved SignaturePad options
                                                const padOptions = {
                                                    minWidth: 0.5,
                                                    maxWidth: 2.5,
                                                    throttle: 0,
                                                    velocityFilterWeight: 0.6,
                                                    penColor: 'black',
                                                    backgroundColor: 'rgba(255,255,255,0)'
                                                };

                                                const client_pad = clientCanvas ? new SignaturePad(clientCanvas, padOptions) : null;
                                                const employee_pad = employeeCanvas ? new SignaturePad(employeeCanvas, padOptions) : null;

                                                // Prevent scrolling while signing (mobile)
                                                [clientCanvas, employeeCanvas].forEach(canvas => {
                                                    if (canvas) {
                                                        canvas.addEventListener("touchstart", e => e.preventDefault(), { passive: false });
                                                        canvas.addEventListener("touchmove", e => e.preventDefault(), { passive: false });
                                                    }
                                                });

                                                // Clear buttons
                                                if (clearClient && client_pad) {
                                                    clearClient.addEventListener('click', () => client_pad.clear());
                                                }

                                                if (clearEmployee && employee_pad) {
                                                    clearEmployee.addEventListener('click', () => employee_pad.clear());
                                                }

                                                // Save button
                                                if (saveButton) {
                                                    saveButton.addEventListener('click', function () {
                                                        if ((!client_pad || client_pad.isEmpty()) && (!employee_pad || employee_pad.isEmpty())) {
                                                            alert("Please provide at least one signature.");
                                                            return;
                                                        }

                                                        saveButton.disabled = true;
                                                        saveButton.textContent = "Saving...";

                                                        let uploads = 0;
                                                        let total = (client_pad && !client_pad.isEmpty() ? 1 : 0) +
                                                            (employee_pad && !employee_pad.isEmpty() ? 1 : 0);

                                                        function checkComplete() {
                                                            uploads++;
                                                            if (uploads === total) location.reload();
                                                        }

                                                        if (client_pad && !client_pad.isEmpty()) uploadSignature(client_pad, 'client', checkComplete);
                                                        if (employee_pad && !employee_pad.isEmpty()) uploadSignature(employee_pad, 'employee', checkComplete);
                                                    });
                                                }

                                                // Upload function
                                                function uploadSignature(pad, type, callback) {
                                                    const dataURL = pad.toDataURL('image/png');
                                                    const blob = dataURLToBlob(dataURL);
                                                    const formData = new FormData();

                                                    formData.append('file', blob, type + '_signature.png');
                                                    formData.append('record_id', record_id);
                                                    formData.append('type', type);

                                                    const xhr = new XMLHttpRequest();
                                                    xhr.open("POST", "../jobcards/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}`);
                                                            }
                                                            if (callback) callback();
                                                        }
                                                    };
                                                    xhr.send(formData);
                                                }

                                                // Convert Base64 to Blob
                                                function dataURLToBlob(dataURL) {
                                                    const binary = atob(dataURL.split(',')[1]);
                                                    const array = [];
                                                    for (let i = 0; i < binary.length; i++) array.push(binary.charCodeAt(i));
                                                    return new Blob([new Uint8Array(array)], { type: 'image/png' });
                                                }
                                            });
                                        </script>
                                    </div>

                                    <div>
                            <?php
                            if (
                                !file_exists("../jobcards/signatures/employee-jc" . $record['jc_no'] . "-" . $_SESSION['user_id'] . "-signature.png") ||
                                !file_exists("../jobcards/signatures/client-jc" . $record['jc_no'] . "-" . $_SESSION['user_id'] . "-signature.png")
                            ) {
                                ?>
                                            <button type="button" id="save_signatures" class="sign_btn">SAVE</button>
                            <?php
                            }
                            ?>
                                    </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 $_GET['record_id']; ?>

                                    function resizeCanvas(canvas) {
                                        if (!canvas) return;
                                        const ratio = Math.max(window.devicePixelRatio || 1, 1);
                                        // use getBoundingClientRect to respect CSS height/width
                                        const rect = canvas.getBoundingClientRect();
                                        canvas.width = rect.width * ratio;
                                        canvas.height = rect.height * ratio;
                                        const ctx = canvas.getContext("2d");
                                        ctx.scale(ratio, ratio);
                                    }

                                    resizeCanvas(clientCanvas);
                                    resizeCanvas(employeeCanvas);

                                    window.addEventListener("resize", () => {
                                        resizeCanvas(clientCanvas);
                                        resizeCanvas(employeeCanvas);
                                    });

                                    // Improved SignaturePad options
                                    const padOptions = {
                                        minWidth: 0.5,
                                        maxWidth: 2.5,
                                        throttle: 0,
                                        velocityFilterWeight: 0.6,
                                        penColor: 'black',
                                        backgroundColor: 'rgba(255,255,255,0)'
                                    };

                                    const client_pad = clientCanvas ? new SignaturePad(clientCanvas, padOptions) : null;
                                    const employee_pad = employeeCanvas ? new SignaturePad(employeeCanvas, padOptions) : null;

                                    // Prevent scrolling while signing (mobile)
                                    [clientCanvas, employeeCanvas].forEach(canvas => {
                                        if (canvas) {
                                            canvas.addEventListener("touchstart", e => e.preventDefault(), { passive: false });
                                            canvas.addEventListener("touchmove", e => e.preventDefault(), { passive: false });
                                        }
                                    });

                                    // Clear buttons
                                    if (clearClient && client_pad) {
                                        clearClient.addEventListener('click', () => client_pad.clear());
                                    }

                                    if (clearEmployee && employee_pad) {
                                        clearEmployee.addEventListener('click', () => employee_pad.clear());
                                    }

                                    // Save button
                                    if (saveButton) {
                                        saveButton.addEventListener('click', function () {
                                            if ((!client_pad || client_pad.isEmpty()) && (!employee_pad || employee_pad.isEmpty())) {
                                                alert("Please provide at least one signature.");
                                                return;
                                            }

                                            saveButton.disabled = true;
                                            saveButton.textContent = "Saving...";

                                            let uploads = 0;
                                            let total = (client_pad && !client_pad.isEmpty() ? 1 : 0) +
                                                (employee_pad && !employee_pad.isEmpty() ? 1 : 0);

                                            function checkComplete() {
                                                uploads++;
                                                if (uploads === total) location.reload();
                                            }

                                            if (client_pad && !client_pad.isEmpty()) uploadSignature(client_pad, 'client', checkComplete);
                                            if (employee_pad && !employee_pad.isEmpty()) uploadSignature(employee_pad, 'employee', checkComplete);
                                        });
                                    }

                                    // Upload function
                                    function uploadSignature(pad, type, callback) {
                                        const dataURL = pad.toDataURL('image/png');
                                        const blob = dataURLToBlob(dataURL);
                                        const formData = new FormData();

                                        formData.append('file', blob, type + '_signature.png');
                                        formData.append('record_id', record_id);
                                        formData.append('type', type);

                                        const xhr = new XMLHttpRequest();
                                        xhr.open("POST", "../jobcards/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}`);
                                                }
                                                if (callback) callback();
                                            }
                                        };
                                        xhr.send(formData);
                                    }

                                    // Convert Base64 to Blob
                                    function dataURLToBlob(dataURL) {
                                        const binary = atob(dataURL.split(',')[1]);
                                        const array = [];
                                        for (let i = 0; i < binary.length; i++) array.push(binary.charCodeAt(i));
                                        return new Blob([new Uint8Array(array)], { type: 'image/png' });
                                    }
                                });
                            </script>
                            <br><br>
                            <div class="search_form" style="height: auto;">

                    <?php
                    $status->add();
                    $record_id->add();
                    ?>
                                <input type="hidden" name="date_time_closed" id="date_time_closed" onsubmit="getTime()">

                                <div style='display: flex; width: 90%; flex-wrap: wrap;'>
                                    <div style="display: flex; flex-direction: column;flex-wrap: wrap; width: 100%;">
                                        <div style="display: flex; flex-direction: column;">
                                            <label for="" style="width: 100%; font-size: 2em;">Diesel Stop</label>
                                <?php
                                $diesel_stop->add();

                                ?>
                                        </div>
                                        <div style="display: flex; flex-direction: column;">
                                            <label for="" style="width: 100%; font-size: 2em;">Compressor Hours</label>
                                <?php
                                $compressor_hours->add();

                                ?>
                                        </div>
                                        <div style="display: flex; flex-direction: column;">
                                            <label for="" style="width: 100%; font-size: 2em;">Water Strike</label>
                                <?php
                                $water_strike->add();

                                ?>
                                        </div>

                                        <div style="display: flex; flex-direction: column;">
                                            <label for="" style="width: 100%; font-size: 2em;">Water Flow</label>
                                <?php
                                $water_flow->add();

                                ?>
                                        </div>
                                        <div style="display: flex; flex-direction: column;">
                                            <label for="" style="width: 100%; font-size: 2em;">Break Found</label>
                                <?php
                                $break_found_one->add();

                                ?>
                                        </div>
                                        <div style="display: flex; flex-direction: column;">
                                            <label for="" style="width: 100%; font-size: 2em;">Interested In Pump</label>
                                <?php
                                $interested_in_pump->add();

                                ?>
                                        </div>
                                    </div>
                        <?php

                        $jobcard_id_data_res = $db->query("jobcards", "SELECT * FROM jobcards WHERE record_id = {$_GET['record_id']}");
                        $jobcard_id_data = $jobcard_id_data_res->fetch_assoc();
                        ?>
                                </div>
                                <div style='display: flex; width: 100%; flex-wrap: wrap;'>

                                    <div style="padding: 2vw; background-color: navy; width: 95%;max-height: 50vw; overflow-y: scroll;">
                                        <h2 style="color:white;">PAYMENTS</h2>
                                        <div style="width: 100%; display: flex; flex-direction: column;">
                                            <div id="payment_history_table"
                                                style="display: flex; flex-direction: column;width: 95%;justify-content: center; padding: 1vw; background-color: whitesmoke;">
                                            </div>

                                            <div id="payments"
                                                style='display:flex; flex-direction: column; width: 95%; align-items: center; background-color: whitesmoke; padding: 1vw;'>

                                    <?php
                                    $payment_label->add();
                                    $payment_method->add();

                                    ?>
                                                <div id='eft' style='display: none; flex-direction: column; align-items: center;'>
                                                    <label for="eft_type">TYPE</label>
                                                    <select name="eft_type" id="eft_type" onchange="eft_option()" class="inputs">
                                                        <option value=""></option>
                                                        <option value="FILE">ATTACH FILE</option>
                                                        <option value="CAMERA">OPEN CAMERA</option>
                                                    </select>
                                                    <div id="file_div" style="display:none; flex-direction: column; align-items: center;">
                                                        <input type="file" name="payment_proof" id="payment_proof" class="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['record_id']; ?>";

                                                                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 = "../jobcards/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', '../jobcards/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;" 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" style="font-size: 2em;">AMOUNT</label>
                                        <?php
                                        $amount->add();

                                        $send_payement = new button();
                                        $send_payement->value("SEND PAYMENT");
                                        $send_payement->onclick("complete_payment()");
                                        $send_payement->add();
                                        ?>

                                                </div>

                                                <script>
                                                    function payment_type() {
                                                        var payment = document.getElementById("payment_method").value;
                                                        if (payment == "EFT") {
                                                            document.getElementById("eft").style.display = "flex";
                                                            document.getElementById("cash").style.display = "flex";
                                                        } else if (payment == "CASH") {
                                                            document.getElementById("cash").style.display = "flex";
                                                            document.getElementById("eft").style.display = "none";
                                                        } else {
                                                            document.getElementById("cash").style.display = "none";
                                                            document.getElementById("eft").style.display = "none";
                                                        }
                                                    }

                                                    function eft_option() {
                                                        var select = document.getElementById("eft_type");
                                                        var file_div = document.getElementById("file_div");
                                                        var camera_div = document.getElementById("camera_div");

                                                        if (select.value === "FILE") {
                                                            file_div.style.display = "flex";
                                                            camera_div.style.display = "none";
                                                        } else if (select.value === "CAMERA") {
                                                            file_div.style.display = "none";
                                                            camera_div.style.display = "flex";
                                                        } else {
                                                            file_div.style.display = "none";
                                                            camera_div.style.display = "none";
                                                        }
                                                    }

                                                    function complete_payment() {
                                                        var payment = document.getElementById("payment_method").value;
                                                        var eft_type = document.getElementById("eft_type").value;

                                                        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_data['jc_no'] ?>');
                                                        formData.append('payment_method', payment);
                                                        formData.append('amount', amount);
                                                        formData.append('user_id', '<?= $_SESSION['user_id'] ?>');

                                                        if (payment === "EFT") {
                                                            // FIXED: Changed "CAMARA" to "CAMERA"
                                                            if (eft_type === "CAMERA") {
                                                                var slip_input = document.getElementById("slip_file").value;

                                                                // FIXED: Check for empty string, not space
                                                                if (slip_input === "" || slip_input.trim() === "") {
                                                                    alert("Please capture Slip Image");
                                                                    return false;
                                                                }

                                                                formData.append('file', slip_input);
                                                            } else if (eft_type === "FILE") {
                                                                // CHANGED: Get the stored filename instead of the file object
                                                                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', '../jobcards/jobcard_payments.ajax.php', true);
                                                        xhr.onreadystatechange = function () {

                                                            if (xhr.readyState === 4) {
                                                                if (xhr.status === 200 && xhr.responseText.includes("OK")) {
                                                                    console.log(`PAYMENYT SUCCESS: ${xhr.responseText}`);
                                                                    alert('Payment completed successfully!');

                                                                    //clear all payment fields
                                                                    document.getElementById("cash_amount").value = "";
                                                                    document.getElementById("slip_file").value = "";

                                                                    // change the payment option to the first one
                                                                    document.getElementById("payment_method").selectedIndex = 0;
                                                                    document.getElementById("cash").style.display = "none";
                                                                    document.getElementById("eft").style.display = "none";

                                                                    var fileInput = document.getElementById("payment_proof");
                                                                    if (fileInput) fileInput.value = "";

                                                                    //update payment history
                                                                    loadPaymentHistory();

                                                                    // Hide sections
                                                                    // payment_option();
                                                                } else {
                                                                    console.log(`Error saving PAYMENT: ${xhr.responseText}`);
                                                                    alert('Error completing payment! ,try again.');
                                                                    return false;
                                                                }
                                                            }
                                                        };
                                                        xhr.send(formData);
                                                    }

                                                    function upload_file_ajax() {
                                                        var payment_proof = document.getElementById("payment_proof");
                                                        var file = payment_proof.files[0];
                                                        var jobcard_no = "<?php echo $jobcard_no ?>";

                                                        if (file) {
                                                            var formData = new FormData();
                                                            formData.append('file', file);
                                                            formData.append('jobcard_no', jobcard_no);
                                                            formData.append('ajax_type', "lead_payment_slip");
                                                            formData.append('section_name', "slip");
                                                            formData.append('file_save_path', "../jobcards/slips/");

                                                            var xhr = new XMLHttpRequest();
                                                            xhr.onreadystatechange = function () {
                                                                if (xhr.readyState === 4) {
                                                                    if (xhr.status === 200 && xhr.responseText.includes("OK")) {
                                                                        console.log(`File uploaded successfully: ${xhr.responseText}`);

                                                                        var response = xhr.responseText;
                                                                        var filename = response.replace('OK | ', '').trim(); // Adjust based on your response format

                                                                        // Store filename in hidden input (create this if it doesn't exist)
                                                                        var uploadedFileInput = document.getElementById('uploaded_file_name');
                                                                        if (!uploadedFileInput) {
                                                                            uploadedFileInput = document.createElement('input');
                                                                            uploadedFileInput.type = 'hidden';
                                                                            uploadedFileInput.id = 'uploaded_file_name';
                                                                            uploadedFileInput.name = 'uploaded_file_name';
                                                                            document.getElementById('file_div').appendChild(uploadedFileInput);
                                                                        }
                                                                        uploadedFileInput.value = filename;

                                                                        alert("File uploaded successfully!");
                                                                    } else {
                                                                        console.log(`Error uploading file: ${xhr.responseText}`);
                                                                        alert('Error uploading file! ,try again.');
                                                                    }
                                                                }
                                                            };
                                                            xhr.open("POST", "../jobcards/upload.php", true);
                                                            xhr.send(formData);
                                                        }
                                                    }

                                                    function loadPaymentHistory() {
                                                        var jobcard_no = "<?php echo $jobcard_id_data['jc_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", "../jobcards/payment_history.ajax.php", true);
                                                        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                                                        xhr.send("jobcard_no=" + encodeURIComponent(jobcard_no));
                                                    }

                                                    // Load history on page load
                                                    document.addEventListener("DOMContentLoaded", loadPaymentHistory);

                                                    loadPaymentHistory();

                                                </script>
                                            </div>
                                        </div>
                                    </div>


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

                            <?php
                            $sample_label->add();

                            ?>

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

                                        <button id="open_camera_samples" class="submit_btn" onclick="openCamera()">Open
                                            Camera</button>

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

                                        <div id="captured_image_samples" style="display:none">
                                            <h3>Captured Image:</h3>
                                            <canvas id="snapshot_sample"></canvas>
                                        </div>

                                        <script>
                                            let stream_samples;

                                            async function openCamera() {
                                                const video = document.getElementById("camera_samples");
                                                const load_camera = document.getElementById("load_camera_samples");
                                                const open_camera = document.getElementById("open_camera_samples");

                                                try {

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

                                                    const video = document.getElementById("camera_samples");
                                                    video.srcObject = stream_samples;
                                                    video.style.display = "block";

                                                    load_camera.style.display = "flex";
                                                    open_camera.style.display = "none";


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

                                            function captureSamplesPhoto() {
                                                const video = document.getElementById("camera_samples");
                                                const canvas = document.getElementById("snapshot_sample");
                                                const context = canvas.getContext("2d");
                                                const captured_image = document.getElementById("captured_image_samples");
                                                const load_camera = document.getElementById("load_camera_samples");
                                                const jobcard_no = "<?php echo $_GET['record_id']; ?>";

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

                                                stopSamplesCamera();
                                                saveCapturedImage(imageData, jobcard_no);
                                            }

                                            function stopSamplesCamera() {
                                                const open_camera = document.getElementById("open_camera_samples");
                                                const load_camera = document.getElementById("load_camera_samples");
                                                const video = document.getElementById("camera_samples");

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

                                            function saveCapturedImage(imageData, jobcard_no) {
                                                const video = document.getElementById("camera_samples");
                                                const folder_path = "../jobcards/samples/";
                                                const section_name = "samples";

                                                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', '../jobcards/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 ('sample' != '') {

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

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

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

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

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

                                        <img src="" id="sample_preview" style="display:none;" />
                                        <input type='text' style="display: none;" class="inputs" id='samples_image' name='samples_image'>
                                    </div>
                                    <div style='display:flex; flex-direction: column; width: 100%; align-items: center;'>

                            <?php
                            $client_merch_label->add();

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

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

                                        <button id="open_camera_client" class="submit_btn" onclick="openclientCamera()">Open
                                            Camera</button>

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

                                        <div id="captured_image_client" style="display:none">
                                            <h3>Captured Image:</h3>
                                            <canvas id="snapshot_client"></canvas>
                                        </div>

                                        <script>
                                            let stream_client_merch;

                                            async function openclientCamera() {
                                                const video = document.getElementById("camera_client_merch");
                                                const load_camera = document.getElementById("load_camera_client");
                                                const open_camera = document.getElementById("open_camera_client");

                                                try {

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

                                                    const video = document.getElementById("camera_client_merch");
                                                    video.srcObject = stream_client_merch;
                                                    video.style.display = "block";

                                                    load_camera.style.display = "flex";
                                                    open_camera.style.display = "none";


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

                                            function captureClientPhoto() {
                                                const video = document.getElementById("camera_client_merch");
                                                const canvas = document.getElementById("snapshot_client");
                                                const context = canvas.getContext("2d");
                                                const captured_image = document.getElementById("captured_image_client");
                                                const load_camera = document.getElementById("load_camera_client");
                                                const jobcard_no = "<?php echo $_GET['record_id']; ?>";

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

                                                stopClientCamera();
                                                saveCapturedClientImage(imageData, jobcard_no);
                                            }

                                            function stopClientCamera() {
                                                const open_camera = document.getElementById("open_camera_client");
                                                const load_camera = document.getElementById("load_camera_client");
                                                const video = document.getElementById("camera_client_merch");

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

                                            function saveCapturedClientImage(imageData, jobcard_no) {
                                                const video = document.getElementById("camera_client_merch");
                                                const folder_path = "../jobcards/client_merch/";
                                                const section_name = "client_merch";

                                                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', '../jobcards/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 ('client_merch_image' != '') {

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

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

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

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

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

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

                                </div>
                    <?php
                    if (file_exists("../jobcards/signatures/employee-jc" . $record['jc_no'] . "-" . $_SESSION['user_id'] . "-signature.png") && file_exists("../jobcards/signatures/client-jc" . $record['jc_no'] . "-" . $_SESSION['user_id'] . "-signature.png")) {
                        $complete->onclick("mark_as_complete()");
                        $complete->style("width: 100%;");
                        $complete->add();
                    } else {
                        $complete->disabled();
                        $complete->style("background-color: #00008045; color: white;");
                        $complete->add();
                    }

                    $complete_ajax = new js_ajax();
                    $complete_ajax->function_name("mark_as_complete");
                    $complete_ajax->update("jobcards");
                    $complete_ajax->selected_div(".search_form input, .search_form select");
                    $complete_ajax->on_success("JOBCARD COMPLETED");
                    $complete_ajax->redirect('../jobcards/jobcard_summary.php?record_id=' . $record['record_id'] . '&jc_no=' . $_GET['jc_no']);
                    ?>

                                <script>
                                    function payment_type() {
                                        var payment = document.getElementById("payment_method").value;
                                        if (payment == "EFT") {
                                            document.getElementById("eft").style.display = "flex";
                                            document.getElementById("cash").style.display = "flex";
                                        } else if (payment == "CASH") {
                                            document.getElementById("cash").style.display = "flex";
                                            document.getElementById("eft").style.display = "none";
                                        } else {
                                            document.getElementById("cash").style.display = "none";
                                            document.getElementById("eft").style.display = "none";
                                        }
                                    }

                                    function complete_payment() {
                                        var payment = document.getElementById("payment_method").value;
                                        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', '<?= $_GET['record_id'] ?>');
                                        formData.append('payment_method', payment);
                                        formData.append('amount', amount);
                                        formData.append('user_id', '<?= $_SESSION['user_id'] ?>');

                                        if (payment === "EFT") {
                                            var slip_input = document.getElementById("slip_file").value;

                                            if (slip_input == " ") {
                                                alert("Please capture Slip Image");
                                                return false;
                                            }

                                            formData.append('file', slip_input);
                                        }

                                        const xhr = new XMLHttpRequest();
                                        xhr.open('POST', '../jobcards/jobcard_payments.ajax.php', true);
                                        xhr.onreadystatechange = function () {

                                            if (xhr.readyState === 4) {
                                                if (xhr.status === 200 && xhr.responseText.includes("OK")) {
                                                    console.log(`PAYMENYT SUCCESS: ${xhr.responseText}`);
                                                    alert('Payment completed successfully!');
                                                    //clear all payment fields
                                                    document.getElementById("cash_amount").value = "";
                                                    document.getElementById("slip_file").value = "";

                                                    // change the payment option to the first one
                                                    document.getElementById("payment_method").selectedIndex = 0;
                                                    document.getElementById("eft").style.display = "none";
                                                    document.getElementById("cash").style.display = "none";

                                                    // window.location.reload();
                                                } else {
                                                    console.log(`Error saving PAYMENT: ${xhr.responseText}`);
                                                    alert('Error completing payment! ,try again.');
                                                    return false;
                                                }
                                            }
                                        };
                                        xhr.send(formData);
                                    }
                                </script>
                            </div>
                        </div>
        <?php
    } else {

        ?>
                        <h1>CURRENT PROCESS</h1>


            <?php

            if ($data['type'] == "RIEMING") {
                ?>
                            <button type="submit" class="submit_btn"
                                onclick="window.location.href = '../jobcards/rieming.php?record_id=<?php echo $record['record_id']; ?>&jc_no=<?php echo $_GET['jobcard_id']; ?>'">RIEMING</button>
            <?php
            } else {
                ?>
                            <button type="submit" class="submit_btn" onclick="reiming()">RIEMING</button>

                <?php

                $reaming_ajax = new js_ajax();
                $reaming_ajax->function_name("reiming");
                $reaming_ajax->insert("jobcard_timeline");
                $reaming_ajax->selected_div("timeline");
                $reaming_ajax->add_column_and_value("jobcard_id={$_GET['record_id']},date_time=" . $date_time . ",type=RIEMING,user_id={$_SESSION['user_id']}");
                $reaming_ajax->on_success("RIEMING");
                $reaming_ajax->redirect("../jobcards/rieming.php?record_id={$record['record_id']}&jc_no={$_GET['jobcard_id']}");
            }

            if ($data['type'] == "DRILLING") {
                ?>
                            <button type="submit" class="submit_btn"
                                onclick="window.location.href = '../jobcards/drilling.php?record_id=<?php echo $record['record_id']; ?>&jc_no=<?php echo $_GET['jobcard_id']; ?>'">DRILLING</button>
            <?php
            } else {
                ?>
                            <button type="submit" class="submit_btn" onclick="drilling()">DRILLING</button>
                <?php
                $drilling_ajax = new js_ajax();
                $drilling_ajax->function_name("drilling");
                $drilling_ajax->insert("jobcard_timeline");
                $drilling_ajax->selected_div("timeline");
                $drilling_ajax->add_column_and_value("jobcard_id={$_GET['record_id']},date_time=" . $date_time . ",type=DRILLING,user_id={$_SESSION['user_id']}");
                $drilling_ajax->on_success("DRILLING");
                $drilling_ajax->redirect("../jobcards/drilling.php?record_id={$record['record_id']}&jc_no={$_GET['jobcard_id']}");
            }

            ?>

                        <button type="submit" class="submit_btn"
                            onclick="window.location.href = '../jobcards/casing.php?record_id=<?php echo $record['record_id']; ?>&jc_no=<?php echo $_GET['jobcard_id']; ?>'">CASING</button>


                        <button type="submit" class="submit_btn"
                            onclick="window.location.href = '../jobcards/processing.php?record_id=<?php echo $record['record_id']; ?>&jc_no=<?php echo $_GET['jobcard_id']; ?>'">BLASTING</button>

            <?php

            $jobcard_done->onclick("complete()");
            $jobcard_done->add();

            $complete_ajax = new js_ajax();
            $complete_ajax->function_name("complete");
            $complete_ajax->insert("jobcard_timeline");
            $complete_ajax->selected_div("timeline");
            $complete_ajax->add_column_and_value("jobcard_id={$_GET['record_id']},date_time=" . $date_time . ",type=COMPLETE,user_id={$_SESSION['user_id']},status=1");
            $complete_ajax->on_success("COMPLETE");
    }

    ?>

    <style>
        table {
            width: 95%;
            border-collapse: collapse;
        }

        th,
        td {
            padding: 10px;
            border: 3px solid black;
            text-align: left;
            background-color: white;
        }
    </style>

    <script>

        function getTime() {
            const now = new Date();
            const year = now.getFullYear();
            const month = String(now.getMonth() + 1).padStart(2, '0');
            const day = String(now.getDate()).padStart(2, '0');
            const hours = String(now.getHours()).padStart(2, '0');
            const minutes = String(now.getMinutes()).padStart(2, '0');
            const seconds = String(now.getSeconds()).padStart(2, '0');

            const formatted = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
            document.getElementById("date_time_closed").value = formatted;
        }
    </script>

    <script src="app.js"></script>