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

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

?>

<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']} 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");
// $riem->class("process_btn");

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

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

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

/////////////////////////////// NOTES POPUP SECTION ////////////////////////////////////////////////

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

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

$reasons_label = new label();
$reasons_label->class("big_labels");
$reasons_label->for("reasons");
$reasons_label->value("REASONS");
$reasons_label->addAttribute("style", " color: white;");

$reasons = new select();
$reasons->class("big_inputs");
$reasons->name("reason");
$reasons->id("reason");
$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("CHANGING RIEMER", "CHANGING RIEMER");
$reasons->add_option("STOP", "STOP");
$reasons->add_option("PENDING", "PENDING");
$reasons->add_option("START", "START");
$reasons->add_option("INSTALLING", "INSTALLING");
$reasons->add_option("RECEIVED", "RECEIVED");
$reasons->add_option("BACK TO WORKSHOP", "BACK TO WORKSHOP");
$reasons->add_option("OTHER", "OTHER");

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

$notes_sub_label = new label();
$notes_sub_label->class("big_labels");
$notes_sub_label->for("notes");
$notes_sub_label->value("NOTES");
$notes_sub_label->addAttribute("style", " color: white;");

$notes = new input();
$notes->class("big_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");

$image = new file_upload();
$image->file_save_path("../jobcards/notes/");
$image->file_type("png, jpg, jpeg");
$image->name("image");
$image->id("image");
$image->class("inputs");
$image->style("width: 50%;");

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

/////////////////////////////////////////////////////////////////////////////////////////////////////

$make_note = new button();
// $make_note->class("make_notes_btn");
$make_note->value("MAKE NOTE");
$make_note->onclick("open_notesPopup()");
$make_note->id("make_note");
$make_note->style("margin: 2vw; width: 60vw; height: 15vw;");

if ($data['type'] == "RIEMING_START" || $data['type'] == "RIEMING_RESUMED" || $data['type'] == "RIEMING_PAUSED") {
    ?>
    <div class="form_down">

        <div>
            <h1 class="heading_h1">CURRENT PROCESS</h1>
            <?php
            $make_note->add();
            ?>

            <br><br>

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

        </div>

        <div>
            <h1 style="color: red; font-size: 3em;">REIMING IN PROGRESS</h1>
            <h1 style="color: red; font-size: 3em;">STOP RIEMING TO CONTINUE</h1>
        </div>

        <div id="floating-block" class="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>
    </div>
    <?php
} else if ($data['type'] == "DRILLING_START" || $data['type'] == "DRILLING_RESUMED" || $data['type'] == "DRILLING_PAUSED") {
    ?>
        <div class="form_down">

            <div>
                <h1 class="heading_h1">CURRENT PROCESS</h1>
                <?php
                $make_note->add();
                ?>
                <button type="submit" class="process_btn"
                    onclick="window.location.href = '../jobcards/drilling.php?record_id=<?php echo $record['record_id']; ?>&jc_no=<?php echo $_GET['jobcard_id']; ?>'">DRILLING</button>
                <br><br>
                <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>

            </div>
            <div>
                <h1 style="color: red; font-size: 3em;">DRILLING IN PROGRESS</h1>
                <h1 style="color: red; font-size: 3em;">STOP DRILLING TO CONTINUE</h1>
            </div>
        </div>

    <?php
} else if ($data['type'] == "BLASTING_START" || $data['type'] == "BLASTING_RESUMED" || $data['type'] == "BLASTING_PAUSED") {
    ?>
            <div class="form_down">

                <div>
                    <h1 class="heading_h1">CURRENT PROCESS</h1>
                <?php
                $make_note->add();
                ?>
                    <button type="submit" class="process_btn"
                        onclick="window.location.href = '../jobcards/processing.php?record_id=<?php echo $record['record_id']; ?>&jc_no=<?php echo $_GET['jobcard_id']; ?>'">BLASTING</button>
                </div>

                <div style="margin-top: -3vw;">
                    <h1 style="color: red; font-size: 3em;">BLASTING IN PROGRESS</h1>
                    <h1 style="color: red; font-size: 3em;">STOP BLASTING TO CONTINUE</h1>
                </div>

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

            </div>

    <?php
} else if ($data['type'] == "CASING_START" || $data['type'] == "CASING_RESUMED" || $data['type'] == "CASING_PAUSED") {
    ?>
                <div class="form_down">

                    <h1 class="heading_h1">CURRENT PROCESS</h1>
            <?php
            $make_note->add();

            ?>

                    <div>
                        <button type="submit" class="process_btn"
                            onclick="window.location.href = '../jobcards/casing.php?record_id=<?php echo $record['record_id']; ?>&jc_no=<?php echo $_GET['jobcard_id']; ?>'">CASING</button>
                    </div>
                    <div>
                        <h1 style="color: red; font-size: 3em;">CASING IN PROGRESS</h1>
                        <h1 style="color: red; font-size: 3em;">STOP CASING TO CONTINUE</h1>
                    </div>
                    <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>
                </div>
    <?php
} 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("big_inputs");
    $diesel_stop->placeholder("Diesel Stop");

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

    $water_strike = new input();
    $water_strike->class("big_inputs");
    $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("big_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("big_inputs");
    $interested_in_pump->add_option("", "Interested in Pump");
    $interested_in_pump->add_option("Yes", "Yes");
    $interested_in_pump->add_option("No", "No");
    $interested_in_pump->onchange("pump_interest()");

    $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("big_inputs");
    $break_found_one->placeholder("Break Found On");

    $payment_label = new label();
    $payment_label->class("big_labels");
    $payment_label->for("payment");
    $payment_label->value("PAYMENT TYPE");

    $payment_method = new select();
    $payment_method->class("big_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->class("big_labels");
    $amount_label->for("amount");
    $amount_label->value("Amount");

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

    $sample_label = new label();
    $sample_label->class("big_labels");
    $sample_label->for("sample_image_label");
    $sample_label->value("Sample Image");

    $client_merch_label = new label();
    $client_merch_label->class("big_labels");
    $client_merch_label->for("client_merch_image_label");
    $client_merch_label->value("Client Merch Image");

    $casing_report_label = new label();
    $casing_report_label->class("big_labels");
    $casing_report_label->for("casing_report_image_label");
    $casing_report_label->value("Casing Report Image");

    $bytel_report_label = new label();
    $bytel_report_label->class("big_labels");
    $bytel_report_label->for("bytel_report_image_label");
    $bytel_report_label->value("Bytel Report Image");

    $board_label = new label();
    $board_label->class("big_labels");
    $board_label->for("board_image_label");
    $board_label->value("Board Report Image");

    $complete = new button();
    $complete->class("process_btn");
    $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; width: 35vw;");
    $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; width: 35vw;");

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

    ?>

                    <div style="display: flex; flex-direction: column; ">
                        <div class="signature_form" id="signatures" style="padding: 4vw; margin-top: 3vw;height: 120vh;">
                            <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 style="font-size: 3em;">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 style="font-size: 3em;">EMPLOYEE SIGNATURE</h2>
                                            <canvas id="employee_signature" class="signature-pad"></canvas>
                                            <div style="display:flex;gap:10px;">
                                                <button type="button" id="clear_employee_signature" class="sign_btn">CLEAR</button>
                                            </div>
                                        </div>
                        <?php
                        }

                        // CLIENT SIGNATURE
                        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 style="font-size: 3em;">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 style="font-size: 3em;">CLIENT SIGNATURE</h2>
                                            <canvas id="client_signature" class="signature-pad"></canvas>
                                            <div style="display:flex;gap:10px;">
                                                <button type="button" id="clear_client_signature" class="sign_btn">CLEAR</button>
                                            </div>
                                        </div>
                        <?php
                        }
                        ?>

                                    <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('record_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 style="margin-top: 40vw;">
                        <?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="save_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 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" || $meters_data['type'] == "CASING_RESUME") {
                        $casing_meters += $meters_data['meters'];
                    }

                    if ($meters_data['type'] == "BLASTING_START" || $meters_data['type'] == "BLASTING_STOP" || $meters_data['type'] == "CASING_RESUME") {
                        $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>
                        <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;" class="big_label">Diesel Stop</label>
                            <?php
                            $diesel_stop->add();

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

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

                            ?>
                                    </div>

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

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

                            ?>
                                    </div>
                                    <div id="interested" style="display: none; flex-direction: column;">
                                        <label for="" style="width: 100%; font-size: 2em;" class="big_label">Pump Payment</label>
                                    </div>
                                    <div style="display: flex; flex-direction: column;">
                                        <label for="" style="width: 100%; font-size: 2em;" class="big_label">Break Found</label>
                            <?php
                            $break_found_one->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: 98%; flex-wrap: wrap;'>

                                <div style="padding: 2vw; background-color: navy; width: 100%;">
                                    <h2 style="color:white;" class="heading_h2">PAYMENTS</h2>
                                    <div style="width: 100%; display: flex; flex-direction: column;">
                                        <div id="payment_history_table"
                                            style="display: flex; flex-direction: column;width: 98%;justify-content: center; padding: 1vw; background-color: whitesmoke;">
                                        </div>

                                        <div id="payments"
                                            style='display:flex; flex-direction: column; width: 98%; 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" class="big_labels">TYPE</label>
                                                <select name="eft_type" id="eft_type" onchange="eft_option()" class="big_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;">
                                                    <label for="proof" class="big_labels">Insert Payment Proof</label>
                                                    <input type="file" name="payment_proof" id="payment_proof" class="big_inputs"
                                                        onchange="upload_file_ajax()">
                                                </div>
                                                <div id="camera_div" style="display:none; flex-direction: column; align-items: center;">
                                                    <style>
                                                        video,
                                                        canvas {
                                                            width: 400px;
                                                            height: 300px;
                                                            border: 3px solid #ccc;
                                                            border-radius: 2vw;
                                                            margin-top: 10px;
                                                        }

                                                        @media all and (max-width: 600px) {

                                                            video,
                                                            canvas {
                                                                width: 600px;
                                                                height: 450px;
                                                                margin-top: -5vw;
                                                            }
                                                        }
                                                    </style>

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

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

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

                                                    <div id="captured_image_slip" style="display:none">
                                                        <h3>Captured Image:</h3>
                                                        <canvas id="snapshot_slip"></canvas>
                                                    </div>

                                        <?php

                                        $jobcard_id_data_res = $db->query("jobcards", "SELECT * FROM jobcards WHERE record_id = {$_GET['record_id']}");
                                        // echo "SELECT * FROM jobcards WHERE record_id = {$_GET['record_id']}";
                                        $jobcard_id_data = $jobcard_id_data_res->fetch_assoc();
                                        ?>

                                                    <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 $jobcard_id_data['jc_no']; ?>";
                                                            alert(jobcard_no);

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

                                                            captured_image.style.display = "none";

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

                                                            stopSlipCamera();
                                                            saveCapturedSlipImage(imageData, jobcard_no);
                                                        }

                                                        function stopSlipCamera() {
                                                            const open_camera = document.getElementById("open_camera_slip");
                                                            const load_camera = document.getElementById("load_camera_slip");
                                                            const video = document.getElementById("camera_slip");

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

                                                        function saveCapturedSlipImage(imageData, jobcard_no) {
                                                            const video = document.getElementById("camera_slip");
                                                            const folder_path = "../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;width: 90%;" class="inputs" id='slip_file'
                                                        name='slip_file'>
                                                </div>

                                            </div>
                                            <div id='cash' style='display: none; flex-direction: column; align-items: center;'>
                                                <label for="amount" class="big_labels">AMOUNT</label>
                                    <?php
                                    $amount->add();

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

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

                                            </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', '<?php echo $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;
                                                        }
                                                    }

                                                    // alert(jc_no)
                                                    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_type").selectedIndex = 0;
                                                                document.getElementById("cash").style.display = "none";
                                                                document.getElementById("eft").style.display = "none";
                                                                document.getElementById("uploaded_file_name").innerHTML = " ";
                                                                document.getElementById("payment_proof").innerHTML = " ";

                                                                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_id['jc_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 style='display:flex; flex-direction: column; width: 100%; align-items: center;'>

                        <?php
                        $casing_report_label->add();

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

                                    <video style="display: none;" id="camera_casing_report" 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_casing_report;

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

                                            try {

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

                                                const video = document.getElementById("camera_casing_report");
                                                video.srcObject = stream_casing_report;
                                                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_casing_report");
                                            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_casing_report");

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

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

                                            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 ('casing_report_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('casing_report_image').style.display = 'block';
                                                            document.getElementById('casing_report_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='casing_report_image'
                                        name='casing_report_image'>
                                </div>
                                <div style='display:flex; flex-direction: column; width: 100%; align-items: center;'>

                        <?php
                        $bytel_report_label->add();

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

                                    <video style="display: none;" id="camera_bytel_report" 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_bytel_report;

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

                                            try {

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

                                                const video = document.getElementById("camera_bytel_report");
                                                video.srcObject = stream_bytel_report;
                                                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_bytel_report");
                                            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_bytel_report");

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

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

                                            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 ('bytel_report_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('bytel_report_image').style.display = 'block';
                                                            document.getElementById('bytel_report_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='bytel_report_image'
                                        name='bytel_report_image'>
                                </div>
                                <div style='display:flex; flex-direction: column; width: 100%; align-items: center;'>

                        <?php
                        $board_label->add();

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

                                    <video style="display: none;" id="camera_board" 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_board;

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

                                            try {

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

                                                const video = document.getElementById("camera_board");
                                                video.srcObject = stream_board;
                                                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_board");
                                            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_board");

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

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

                                            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 ('board_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('board_image').style.display = 'block';
                                                            document.getElementById('board_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='board_image' name='board_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']);
                $complete_ajax->exclude_inputs("['eft_type','payment_proof','uploaded_file_name']");
                ?>

                            <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', '<?php echo $jobcard_id_data['jc_no'] ?>');
                                    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 = "";
                                                document.getElementById("payment_proof").value = "";
                                                if (document.getElementById("uploaded_file_name")) {
                                                    document.getElementById("uploaded_file_name").value = "";
                                                }

                                                // change the payment option to the first one
                                                document.getElementById("payment_method").selectedIndex = 0;
                                                document.getElementById("eft_type").selectedIndex = 0;
                                                document.getElementById("cash").style.display = "none";
                                                document.getElementById("eft").style.display = "none";
                                                if (document.getElementById("uploaded_file_name")) {
                                                    document.getElementById("uploaded_file_name").style.display = "none";
                                                }
                                                var fileInput = document.getElementById("payment_proof");
                                                if (fileInput) fileInput.value = "";

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

                                                loadPaymentHistory();

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

    ?>
                    <div style="display: flex; flex-direction: column;">
                        <div class="form_down">
                            <div style="margin-bottom: 30vw;">
                                <h1 class="heading_h1">CURRENT PROCESS</h1>


                    <?php

                    if ($data['type'] == "RIEMING") {
                        ?>
                                    <button type="submit" class="process_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="process_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=" . $current_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="process_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="process_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=" . $current_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="process_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="process_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=" . $current_date_time . ",type=COMPLETE,user_id={$_SESSION['user_id']},status=1");
                    $complete_ajax->on_success("COMPLETE");
                    ?>
                            </div>
                        </div>


                        <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" || $meters_data['type'] == "CASING_RESUME") {
                        $casing_meters += $meters_data['meters'];
                    }

                    if ($meters_data['type'] == "BLASTING_START" || $meters_data['type'] == "BLASTING_STOP" || $meters_data['type'] == "CASING_RESUME") {
                        $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>
                    </div>

    <?php

}

?>

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

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

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

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

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

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

        @media all and (min-width: 651px) and (max-width: 1050px) {
            font-size: 1.5em;
        }
    }

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

        @media all and (min-width: 651px) and (max-width: 1050px) {
            font-size: 1.5em;
        }
    }
</style>

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

        <?php
        $res_data = $db->query("jobcard_timeline", "SELECT * FROM jobcard_timeline WHERE jobcard_id = {$_GET['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();

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

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

        <div id="normal_section" style="display: flex; flex-direction: column;align-items: center;">
            <textarea name="note" id="note" class="inputs" style="width: 70vw" rows="5"></textarea>


            <?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_content textarea");
            $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']} AND reason NOT LIKE '%BIT%'");

            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 colspan='4'>NO NOTES RECORDED</td>
            </tr><br>";

            }
            ?>

            <div style="background-color: white;padding-left: 2vw;padding-top: 2vw; width: 100%;">
                <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>
    <br><br>
</div>


<script>

    function pump_interest() {
        var pump_interest = document.getElementById("interested_in_pump").value;

        if (pump_interest == "YES") {
            document.getElementById("interested").style.display = flex;
        } else {
            document.getElementById("interested").style.display = none;
        }
    }

    function open_notesPopup() {
        event.preventDefault ? event.preventDefault() : (event.returnValue = false, event.stopPropagation());
        document.getElementById("notes_popup").style.display = "block";

    }

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

    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>