<?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>

    <h1>CURRENT PROCESS</h1>

    <?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");
    $make_note->add();

    if ($data['type'] == "RIEMING_START") {
        ?>

        <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") {
        ?>
            <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") {
        ?>
                <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") {
        ?>

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

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

        // $save_btn1 = new Button();
        // $save_btn1->value("SAVE");
        // $save_btn1->class("sign_btn");
        // $save_btn1->id("save_employee_signature");
    
        ?>
                        <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">
                                <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>
                                            SAVUKIDRILLING MPUMALANGA WILL NOT BE LIABLE FOR ANY ACCIDENTS CAUSED BY ANYUNCOVERED
                                            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

                            if (file_exists("../jobcards/signatures/employee-jc" . $record['jc_no'] . "-" . $_SESSION['user_id'] . "-signature.png")) {

                                ?>
                                            <div class='jobcard_work_signature' style='margin-bottom:1vw;margin-top:1vh;'>
                                                <h2>EMPLOYEE SIGNATURE</h2>
                                                <br>
                                                <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">

                                        <?php
                                        $clear_btn1->add();
                                        ?>
                                                    <br><br><br>
                                                    <div style="width:50%; height:10%;margin-top:10vh"> </div>
                                                </div>
                                            </div>
                            <?php
                            }

                            if (file_exists("../jobcards/signatures/client-jc" . $record['jc_no'] . "-" . $_SESSION['user_id'] . "-signature.png")) {
                                ?>

                                            <br><br>
                                            <div class='jobcard_work_signature' style="margin-bottom:1vw;margin-top:1vh;">
                                                <h2>CLIENT SIGNATURE</h2>
                                                <br><br>
                                                <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;margin-top:1vh;'>
                                                <h2>CLIENT SIGNATURE</h2>
                                                <canvas id="client_signature" class="signature-pad"></canvas>
                                                <div style="display:flex">
                                        <?php
                                        $clear_btn->add();
                                        ?>
                                                    <br><br><br>
                                                    <div style="width:50%; height:10%;margin-top:10vh"> </div>
                                                </div>
                                            </div>

                            <?php
                            }
                            ?>


                                    </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")) {

                            } else {
                                $save_btn->add();
                            }
                            ?>
                                    </div>
                                </div>
                            </div>

                            <script>

                                // Initialize both signature pads
                                var client_pad = new SignaturePad(document.getElementById('client_signature'));
                                var employee_pad = new SignaturePad(document.getElementById('employee_signature'));

                                var record_id = document.getElementById("record_id").value;

                                // One Save button for both signatures
                                document.getElementById('save_signatures').addEventListener('click', function () {
                                    // Check if both are empty
                                    if (client_pad.isEmpty() && employee_pad.isEmpty()) {
                                        alert("Please provide at least one signature.");
                                        return;
                                    }

                                    // Upload client signature if available
                                    if (!client_pad.isEmpty()) {
                                        uploadSignature(client_pad, 'client');
                                    }

                                    // Upload employee signature if available
                                    if (!employee_pad.isEmpty()) {
                                        uploadSignature(employee_pad, 'employee');
                                    }
                                });

                                // Function to upload one signature
                                function uploadSignature(pad, type) {
                                    var dataURL = pad.toDataURL('image/png');
                                    var blob = dataURLToBlob(dataURL);
                                    var formData = new FormData();

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

                                    var xhr = new XMLHttpRequest();
                                    xhr.open("POST", "../jobcards/upload_signature.php", true);
                                    xhr.onreadystatechange = function () {
                                        if (xhr.readyState === 4 && xhr.status === 200) {
                                            if (xhr.responseText.indexOf("OK") > 1) {
                                                console.log(type + " signature saved successfully.");
                                                location.reload();
                                            } else {
                                                alert("Error saving " + type + " signature: " + xhr.responseText);
                                            }
                                        }
                                    };
                                    xhr.send(formData);
                                }

                                function dataURLToBlob(dataURL) {
                                    var binary = atob(dataURL.split(',')[1]);
                                    var array = [];
                                    for (var i = 0; i < binary.length; i++) {
                                        array.push(binary.charCodeAt(i));
                                    }
                                    return new Blob([new Uint8Array(array)], {
                                        type: dataURL.split(',')[0].split(':')[1].split(';')[0]
                                    });
                                }

                            </script>
                            <br><br>
                            <div class="search_form">

                    <?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;'>
                        <?php
                        $diesel_stop->add();
                        $compressor_hours->add();
                        $water_strike->add();
                        $water_flow->add();
                        $break_found_one->add();
                        $interested_in_pump->add();
                        ?>
                                </div>
                                <div style='display: flex; width: 90%; flex-wrap: wrap;'>
                                    <div style='display:flex; flex-direction: column; width: 100%;'>

                            <?php
                            $payment_label->add();
                            $payment_method->add();
                            ?>
                                        <div id='cash' style='display: none; flex-direction: column; align-items: center;'>
                                <?php
                                $amount_label->add();
                                $amount->add();
                                ?>
                                        </div>
                                        <div id='eft' style='display: none; flex-direction: column; align-items: center;'>
                                <?php

                                // new camera('slip_file', $_GET['record_id'], '../jobcards/slips/', 'slip');
                            
                                ?>
                                            <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'>
                                <?php
                                $amount->add();

                                ?>
                                        </div>
                                    </div>
                                    <div style="display: flex; justify-content: space-between; width: 100%;">
                                        <div style='display:flex; flex-direction: column; width: 100%; align-items: center;'>

                                <?php
                                $sample_label->add();


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

                                            <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' != '') {
                                                                    document.getElementById('samples_image').style.display = 'block';
                                                                    document.getElementById('samples_image').value = xhr.responseText;
                                                                }
                                                            } else {
                                                                alert('Error saving photo!');

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

                                            <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' != '') {
                                                                    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>

                                            <input type='text' style="display: none;" class="inputs" id='client_merch_image'
                                                name='client_merch_image'>
                                        </div>
                                    </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->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 = "none";
                                        } 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";
                                        }
                                    }
                                </script>
                            </div>
                        </div>
        <?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']}");
            ?>

                        <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']}");
            $complete_ajax->on_success("COMPLETE");
    }

    ?>

    <style>
        .notes_popup {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
        }

        .notes_content {
            background: linear-gradient(90deg, #110151, #3331e7);
            margin: 3% auto;
            padding: 20px;
            border-radius: 10px;
            width: 80%;
            height: 85%;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
            position: relative;
            overflow-y: scroll;
        }

        .notes_images {
            width: 10vw;
            height: 10vw;
        }

        .close-btn {
            position: absolute;
            top: 10px;
            right: 15px;
            font-weight: bolder;
            font-size: 5vw;
            cursor: pointer;
            color: white;
        }

        table {
            width: 95%;
            border-collapse: collapse;
        }

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

        @media all and (min-width: 651px) and (max-width: 1050px) {

            .notes_content {
                width: 90%;
                height: 95%;
            }

            .close-btn {
                top: 0px;
                font-size: 15vw;
            }
        }
    </style>

    <div id="notes_popup" class="notes_popup">
        <div class="notes_content">
            <span class="close-btn" onclick="close_notesPopup()">&times;</span>

            <?php
            $res_data = $db->query("jobcard_timeline", "SELECT * FROM jobcard_timeline WHERE jobcard_id = {$_GET['record_id']} ORDER BY record_id DESC LIMIT 1");
            $data = $res_data->fetch_assoc();

            $jobcard_id = new input();
            $jobcard_id->type("hidden");
            $jobcard_id->name("jobcard_id");
            $jobcard_id->id("jobcard_id");
            $jobcard_id->value($_GET['record_id']);

            $date_time = new input();
            $date_time->type("hidden");
            $date_time->name("date_time");
            $date_time->id("date_time");
            $date_time->value($current_date_time);

            $reasons_label = new label();
            $reasons_label->for("reasons");
            $reasons_label->value("REASONS");
            $reasons_label->addAttribute("style", "font-size: 1.5vw; color: white;");

            $reasons = new select();
            $reasons->class("inputs");
            $reasons->name("reason");
            $reasons->id("reason");
            $reasons->onchange("casing_option()");
            // $reasons->addAttribute("style", "width: 20%;");
            $reasons->add_option("ARRIVED AT LOCATION", "ARRIVED AT LOCATION");
            $reasons->add_option("WAITING FOR CLIENT", "WAITING FOR CLIENT");
            $reasons->add_option("TRAVELING TO SITE", "TRAVELING TO SITE");
            $reasons->add_option("ARRIVED ON SITE", "ARRIVED ON SITE");
            $reasons->add_option("TALKING TO CLIENT", "TALKING TO CLIENT");
            $reasons->add_option("FETCHING MONEY", "FETCHING MONEY");
            $reasons->add_option("BRAKING", "BRAKING");
            $reasons->add_option("CASING", "CASING");
            $reasons->add_option("CHANGING RIEMER", "CHANGING RIEMER");
            $reasons->add_option("STOP", "STOP");
            $reasons->add_option("PENDING", "PENDING");
            $reasons->add_option("START", "START");
            $reasons->add_option("INSTALLING", "INSTALLING");
            $reasons->add_option("RECEIVED", "RECEIVED");
            $reasons->add_option("BACK TO WORKSHOP", "BACK TO WORKSHOP");
            $reasons->add_option("OTHER", "OTHER");

            $notes_label = new label();
            $notes_label->for("notes");
            $notes_label->value("NOTES");
            $notes_label->addAttribute("style", "font-size: 4vw; color: white; margin:1px;");

            $notes = new input();
            $notes->class("inputs");
            $notes->type("text");
            $notes->placeholder("NOTES");
            $notes->name("note");
            $notes->id("note");
            $notes->addAttribute("style", "width: 50%;");

            $add_notes = new button();
            $add_notes->value("ADD NOTES");
            $add_notes->onclick("add_notes()");
            $add_notes->style("width: 100%;");
            $add_notes->id("notes_btn");

            $casing_label = new label();
            $casing_label->for("casing");
            $casing_label->value("CASING METERS");
            $casing_label->addAttribute("style", "font-size: 1.5vw; color: white;");

            $casing_meters = new input();
            $casing_meters->type("number");
            $casing_meters->placeholder("METERS");
            $casing_meters->name("meters");
            $casing_meters->id("meters");
            $casing_meters->class("jobcard_inputs");

            $casing_start = new button();
            $casing_start->value("START");
            $casing_start->onclick("casing_start()");

            $casing_stop = new button();
            $casing_stop->value("STOP");
            $casing_stop->onclick("casing_stop()");

            $ajax = new js_ajax();
            $ajax->function_name("add_notes");
            $ajax->insert("notes");
            $ajax->selected_div(".notes_content input , .notes_content select ");
            $ajax->submit_btn_id("notes_btn");
            $ajax->on_success("NOTE SAVED");

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

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

            if ($data['type'] == "CASING_START") {
                $casing_stop = new button();
                $casing_stop->value("STOP");
                $casing_stop->onclick("casing_stop()");
                ?>

                <div style="display: flex; flex-direction: column; align-items: center;">
                    <?php
                    $reasons_label->add();
                    ?>

                    <select name="reason" id="reason" readonly disabled class="inputs" style="width: 20%;">
                        <option value="CASING" selected>CASING</option>
                    </select>

                </div>

                <br><br>

                <div id="casing_data" style="display: flex; flex-direction: column; align-items: center;">
                    <?php
                    $casing_label->add();
                    $casing_meters->add();
                    echo "<br>";

                    $casing_stop->add();
                    ?>
                </div>

                <?php

                $casing_stop_ajax = new js_ajax();
                $casing_stop_ajax->function_name("casing_stop");
                $casing_stop_ajax->insert("jobcard_timeline");
                $casing_stop_ajax->selected_div(".casing_data input");
                $casing_stop_ajax->add_column_and_value("jobcard_id={$_GET['record_id']},date_time=" . $current_date_time . ",type=CASING_STOP,user_id={$_SESSION['user_id']}");
                $casing_stop_ajax->on_success("CASING STOPPED");

            } else {
                ?>

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

                <div id="normal_section" style="display: flex; flex-direction: column;align-items: center;">
                    <?php
                    $notes->add();

                    new camera('image', $_GET['record_id'], "../jobcards/notes/", "notes_images");
                    ?>
                    <input type="text" style="display: none;" id="image" name="image">

                    <?php
                    $add_notes->add();

                    $notes_ajax = new js_ajax();
                    $notes_ajax->function_name("add_notes");
                    $notes_ajax->insert("notes");
                    $notes_ajax->selected_div(".notes_content input , .notes_content select ");
                    $notes_ajax->submit_btn_id("notes_btn");
                    $notes_ajax->on_success("NOTE SAVED");
                    ?>


                    <?php

                    $notes_res = $db->query("notes", "SELECT * FROM notes WHERE jobcard_id = {$_GET['record_id']}");

                    if ($notes_res->num_rows > 0) {
                        while ($row = $notes_res->fetch_assoc()) {
                            $table_data = $table_data . "<tr>
                <td>" . $row['reason'] . "</td>
                <td>" . $row['note'] . "</td>
                <td>" . $row['image'] . "</td>
                <td>" . $row['date_time'] . "</td>
                </tr>";
                        }
                        $notes = $notes_res->fetch_assoc();

                    } else {
                        $table_data = $table_data . "<tr><td></td>
            <td>NO NOTES RECORDED</td><td></td><td></td>
            </tr><br>";

                    }
                    ?>

                    <div style="background-color: white;padding-left: 2vw;padding-top: 2vw;">
                        <table>
                            <tr>
                                <th>REASON</th>
                                <th>NOTE</th>
                                <th>IMAGE</th>
                                <th>DATE TIME</th>
                            </tr>
                            <?php echo $table_data; ?>
                        </table>
                        <br>
                    </div>
                </div>

                <div id="casing_section" style="display: none; flex-direction: column;align-items: center;">
                    <?php
                    $res_data = $db->query("jobcard_timeline", "SELECT * FROM jobcard_timeline WHERE jobcard_id = {$_GET['record_id']} ORDER BY record_id DESC LIMIT 1");
                    $data = $res_data->fetch_assoc();

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

                    <div class="casing_data"
                        style="display: flex; flex-direction: column; align-items: center; width: 100%;">
                        <?php
                        $jobcard_id->add();

                        $date_time->add();

                        if ($data['type'] == "CASING_START") {
                            $casing_label->add();
                            $casing_stop->add();
                            $casing_meters->add();

                            $casing_start_ajax = new js_ajax();
                            $casing_start_ajax->function_name("casing_start");
                            $casing_start_ajax->insert("jobcard_timeline");
                            $casing_start_ajax->selected_div(".casing_data input");
                            $casing_start_ajax->add_column_and_value("jobcard_id={$_GET['record_id']},date_time=" . $current_date_time . ",type=CASING_START,user_id={$_SESSION['user_id']}");
                            $casing_start_ajax->on_success("CASING STARTED");

                        } elseif ($data['type'] == "CASING_STOP") {

                            $casing_label->add();
                            $casing_start->add();
                            $casing_meters->add();

                            $casing_stop_ajax = new js_ajax();
                            $casing_stop_ajax->function_name("casing_stop");
                            $casing_stop_ajax->insert("jobcard_timeline");
                            $casing_stop_ajax->selected_div(".casing_data input");
                            $casing_stop_ajax->add_column_and_value("jobcard_id={$_GET['record_id']},date_time=" . $current_date_time . ",type=CASING_STOP,user_id={$_SESSION['user_id']}");
                            $casing_stop_ajax->on_success("CASING STOPPED");

                        } else {
                            $casing_label->add();
                            $casing_start->add();
                            $casing_meters->add();

                            $casing_start_ajax = new js_ajax();
                            $casing_start_ajax->function_name("casing_start");
                            $casing_start_ajax->insert("jobcard_timeline");
                            $casing_start_ajax->selected_div(".casing_data input");
                            $casing_start_ajax->add_column_and_value("jobcard_id={$_GET['record_id']},date_time=" . $current_date_time . ",type=CASING_START,user_id={$_SESSION['user_id']}");
                            $casing_start_ajax->on_success("CASING STARTED");

                        }

            }
            ?>

                </div>
            </div>

        </div>
        <br><br>

        <script>
            function casing_option() {
                var casing = document.getElementById("casing_section");
                var reasons = document.getElementById("reason").value;
                var normal_reasons = document.getElementById("normal_section");

                if (reasons === "CASING") {
                    casing.style.display = "flex";
                    normal_reasons.style.display = "none";
                } else {
                    casing.style.display = "none";
                    normal_reasons.style.display = "flex";
                }
            }
        </script>
    </div>

    <script>
        function open_notesPopup() {
            document.getElementById("notes_popup").style.display = "block";
        }

        function close_notesPopup() {
            document.getElementById("notes_popup").style.display = "none";
        }

        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>