<?php include "../../root.class.php";
$html = new html();
$html->add_styles_page();
$db = new db_safeguard();

//get the current date and time
$current_date_time = date("Y-m-d H:i", strtotime("+2 hours"));

$arrived = 0;


/////////////////////////////// DEPARTURE SECTION ///////////////////////////////////////////////////

$client_name_lable = new label();
$client_name_lable->for("client_name_label");
$client_name_lable->value("CLIENT NAME");

$contact_name_label = new label();
$contact_name_label->for("contact_name_label");
$contact_name_label->value("CONTACT NAME");

$jc_no_label = new label();
$jc_no_label->for("jc_no_label");
$jc_no_label->value("JOBCARD NUMBER");

$phone_label = new label();
$phone_label->for("phone");
$phone_label->value("PHONE NUMBER");

$contact_number_label = new label();
$contact_number_label->for("contact_number_label");
$contact_number_label->value("CONTACT NUMBER");

$other_number_label = new label();
$other_number_label->for("other_number_label");
$other_number_label->value("OTHER NUMBER");

$alternate_number_label = new label();
$alternate_number_label->for("alternate_number_label");
$alternate_number_label->value("ALTERNATE NUMBER");

$address_label = new label();
$address_label->for("address_label");
$address_label->value("AREA");

$jc_no = new input();
$jc_no->class("inputs");
$jc_no->type("text");
$jc_no->readonly();
$jc_no->name("jc_no");
$jc_no->id("jc_no");
$jc_no->value_from_db("jobcards", "jc_no", "record_id = {$_GET['record_id']}");

$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($_GET['record_id']);

$not_empty_res = $db->query("jobcards", "SELECT * FROM jobcards WHERE record_id = {$_GET['record_id']}");
while ($not_empty = $not_empty_res->fetch_assoc()) {

    $client_name = new input();
    $client_name->class("inputs");
    $client_name->type("text");
    $client_name->placeholder("CLIENT NAME");
    $client_name->name("client_name");
    $client_name->id("client_name");
    $client_name->value_from_db("jobcards", "client_name", "record_id = {$_GET['record_id']}");


    $contact_name = new input();
    $contact_name->class("inputs");
    $contact_name->type("text");
    $contact_name->placeholder("CONTACT NAME");
    $contact_name->name("contact_name");
    $contact_name->id("contact_name");
    if (!empty(trim($not_empty['contact_name']))) {
        $contact_name->value_from_db("jobcards", "contact_name", "record_id = {$_GET['record_id']}");
    }

    $phone = new input();
    $phone->class("inputs");
    $phone->type("text");
    $phone->placeholder("PHONE NUMBER");
    $phone->name("contact_number");
    $phone->id("contact_number");
    if (!empty(trim($not_empty['contact_number']))) {
        $phone->value_from_db("jobcards", "contact_number", "record_id = {$_GET['record_id']}");
    }

    $other_number = new input();
    $other_number->class("inputs");
    $other_number->type("text");
    $other_number->placeholder("OTHER NUMBER");
    $other_number->name("other_number");
    $other_number->id("other_number");
    if (!empty(trim($not_empty['other_number']))) {
        $other_number->value_from_db("jobcards", "other_number", "record_id = {$_GET['record_id']}");
    }

    $alternate_number = new input();
    $alternate_number->class("inputs");
    $alternate_number->type("text");
    $alternate_number->placeholder("ALTERNATE NUMBER");
    $alternate_number->name("alternate_number");
    $alternate_number->id("alternate_number");
    if (!empty(trim($not_empty['alternate_number']))) {
        $alternate_number->value_from_db("jobcards", "alternate_number", "record_id = {$_GET['record_id']}");
    }

    $address = new input();
    $address->class("inputs");
    $address->type("text");
    $address->placeholder("ADDRESS");
    $address->name("address");
    $address->id("address");
    $address->addAttribute("style", "width: 60%;");
    if (!empty(trim($not_empty['address']))) {
        $address->value_from_db("jobcards", "address", "record_id = {$_GET['record_id']}");
    }

}

$make_notes_btn = new button();
$make_notes_btn->value("MAKE NOTES");
$make_notes_btn->onclick("open_notesPopup()");

/////////////////////////////////////////////////////////////////////////////////////////////////////


/////////////////////////////// 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->for("reasons");
$reasons_label->value("REASONS");
$reasons_label->addAttribute("style", "font-size: 1.5vw; color: white;");

$reasons = new select();
$reasons->class("inputs");
$reasons->name("reason");
$reasons->id("reason");
$reasons->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->for("notes");
$notes_label->value("NOTES");
$notes_label->addAttribute("style", "font-size: 4vw; color: white; margin:1px;");

$notes = new input();
$notes->class("inputs");
$notes->type("text");
$notes->placeholder("NOTES");
$notes->name("note");
$notes->id("note");
$notes->addAttribute("style", "width: 50%;");

$add_notes = new button();
$add_notes->value("ADD NOTES");
$add_notes->onclick("add_notes()");
$add_notes->style("width: 100%;");
$add_notes->id("notes_btn");

$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");

/////////////////////////////////////////////////////////////////////////////////////////////////////


/////////////////////////////// ARRIVED SECTION /////////////////////////////////////////////////////

$check_empty_res = $db->query("jobcards", "SELECT * FROM jobcards WHERE record_id = {$_GET['record_id']}");

while ($check_empty = $check_empty_res->fetch_assoc()) {

    $pin = new input();
    $pin->class("inputs");
    $pin->type("text");
    $pin->placeholder("PIN");
    $pin->name("drill_co_ordinates");
    $pin->id("drill_co_ordinates");
    $pin->addAttribute("style", "width: 30%;");

    if (!empty(trim($check_empty['drill_co_ordinates']))) {
        $pin->value_from_db("jobcards", "drill_co_ordinates", "record_id = {$_GET['record_id']}");
    }

    $diesel_start = new input();
    $diesel_start->class("inputs");
    $diesel_start->type("text");
    $diesel_start->placeholder("DIESEL START");
    $diesel_start->name("diesel_start");
    $diesel_start->id("diesel_start");

    if (!empty(trim($check_empty['diesel_start']))) {
        $diesel_start->value_from_db("jobcards", "diesel_start", "record_id = {$_GET['record_id']}");
    }

    $amount = new input();
    $amount->class("inputs");
    $amount->type("text");
    $amount->placeholder("AMOUNT");
    $amount->name("cash_amount");
    $amount->id("cash_amount");

    if (!empty(trim($check_empty['cash_amount']))) {
        $amount->value_from_db("jobcards", "cash_amount", "record_id = {$_GET['record_id']}");
    }

}

$getLocation = new button();
$getLocation->value("GET LOCATION");
$getLocation->onclick("getLocation()");

$amount_label = new label();
$amount_label->for("amount");
$amount_label->value("AMOUNT");

$current_slip_label = new label();
$current_slip_label->for("slip_file");
$current_slip_label->value("CURRENT SLIP");

$slip_file = new file_upload();
$slip_file->file_save_path("../jobcards/slips/");
$slip_file->file_type("png, jpg, jpeg");
$slip_file->name("slip_file");
$slip_file->id("slip_file");
$slip_file->class("inputs");
$slip_file->style("width: 100%;");

$image = new file_upload();
$image->file_save_path("../jobcards/slips/");
$image->file_type("png, jpg, jpeg");
$image->name("image");
$image->id("image");
$image->class("inputs");
$image->style("width: 50%;");

$clear_btn = new Button();
$clear_btn->class("sign_btn");
$clear_btn->value("CLEAR");
$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->onclick("employee_pad.clear()");


/////////////////////////////////////////////////////////////////////////////////////////////////////

?>

<style>
    .notes_popup {
        display: none;
        position: fixed;
        z-index: 1000;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.5);
    }

    .notes_content {
        background: linear-gradient(90deg, #110151, #3331e7);
        margin: 3% auto;
        padding: 20px;
        border-radius: 10px;
        width: 80%;
        height: 85%;
        box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
        position: relative;
        overflow-y: scroll;
    }

    .notes_images {
        width: 10vw;
        height: 10vw;
    }

    .close-btn {
        position: absolute;
        top: 10px;
        right: 15px;
        font-weight: bolder;
        font-size: 5vw;
        cursor: pointer;
        color: white;
    }

    table {
        width: 95%;
        border-collapse: collapse;
    }

    th,
    td {
        padding: 10px;
        border: 3px solid black;
        text-align: left;
        background-color: white;
    }
</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();
            ?>
        </div>

        <div id="normal_section" style="display: flex; flex-direction: column;align-items: center;">
            <?php
            $notes->add();

            new camera('image', $_GET['record_id'], "../jobcards/notes/", "notes_images");
            ?>
            <input type="text" style="display: none;" id="image" name="image">

            <?php
            $add_notes->add();

            $notes_ajax = new js_ajax();
            $notes_ajax->function_name("add_notes");
            $notes_ajax->insert("notes");
            $notes_ajax->selected_div(".notes_content input , .notes_content select ");
            $notes_ajax->submit_btn_id("notes_btn");
            $notes_ajax->on_success("NOTE SAVED");
            ?>


            <?php

            $notes_res = $db->query("notes", "SELECT * FROM notes WHERE jobcard_id = {$_GET['record_id']}");

            if ($notes_res->num_rows > 0) {
                while ($row = $notes_res->fetch_assoc()) {
                    $table_data = $table_data . "<tr>
                <td>" . $row['reason'] . "</td>
                <td>" . $row['note'] . "</td>
                <td>" . $row['image'] . "</td>
                <td>" . $row['date_time'] . "</td>
                </tr>";
                }
                $notes = $notes_res->fetch_assoc();

            } else {
                $table_data = $table_data . "<tr><td></td>
            <td>NO NOTES RECORDED</td><td></td><td></td>
            </tr><br>";

            }
            ?>

            <div style="background-color: white;padding-left: 2vw;padding-top: 2vw;">
                <table>
                    <tr>
                        <th>REASON</th>
                        <th>NOTE</th>
                        <th>IMAGE</th>
                        <th>DATE TIME</th>
                    </tr>
                    <?php echo $table_data; ?>
                </table>
                <br>
            </div>
        </div>
    </div>
    <br><br>
</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();

if ($data['type'] == "RIEMING_START" || $data['type'] == "RIEMING_PAUSED") {
    ?>
    <script>
        window.location.href = "../jobcards/rieming.php?record_id=<?= $record['record_id'] ?>&jc_no=<?= $_GET['record_id'] ?>";
    </script>
    <?php
} else if ($data['type'] == "DRILLING_START" || $data['type'] == "DRILLING_PAUSE") {
    ?>
        <script>
            window.location.href = "../jobcards/drilling.php?record_id=<?= $record['record_id'] ?>&jc_no=<?= $_GET['record_id'] ?>";
        </script>
    <?php
} else if ($data['type'] == "CASING_START" || $data['type'] == "CASING_PAUSED") {
    ?>
            <script>
                window.location.href = "../jobcards/casing.php?record_id=<?= $record['record_id'] ?>&jc_no=<?= $_GET['record_id'] ?>";
            </script>
    <?php
} else if ($data['type'] == "BLASTING_START" || $data['type'] == "BLASTING_PAUSED") {
    ?>
                <script>
                    window.location.href = "../jobcards/processing.php?record_id=<?= $record['record_id'] ?>&jc_no=<?= $_GET['record_id'] ?>";
                </script>
    <?php
} else if ($data['type'] == "COMPLETE" || $res_data->num_rows == 0 || $data['type'] == "DEPARTURE" || $data['type'] == "ARRIVED") {


    $res_arrival = $db->query("jobcard_timeline", "SELECT * FROM jobcard_timeline WHERE jobcard_id = {$_GET['record_id']} ORDER BY record_id DESC");

    $has_departed = false;
    $has_arrived = false;

    if ($res_arrival->num_rows > 0) {
        while ($current_status = $res_arrival->fetch_assoc()) {

            if ($current_status['type'] == "DEPARTURE") {
                $has_departed = true;
            }

            if ($current_status['type'] == "ARRIVED") {
                $has_arrived = true;
            }
        }
    }

    if ($has_departed && $has_arrived) {

        $record_res = $db->query("jobcards", "SELECT * FROM jobcards WHERE record_id = {$_GET['record_id']}");
        $record = $record_res->fetch_assoc();

        $record_id->add();
        $jobcard_id->add();

        ?>
                        <div class="down_form" id="signatures">
                            <h1 class="sign_h1">SIGNATURES</h1>
                            <div class="list_inputs">
                                Please Note: Savuki Drilling Mpumalanga
                                <ul>
                                    <li>1. Cannot be held responsible for any damage or borehole collapse.</li>
                                    <li>2. Steel casings must be installed on the recommendation of the drill team.</li>
                                    <li>3. Will not be held liable for any damage on property.</li>
                                    <li>4. No water is guaranteed even if Savuki Drilling surveyed.</li>
                                    <li>5. Client pays for service of drilling, not water.</li>
                                </ul>
                                <b><i>SAFETY PRECAUTION - <br> CUSTOMER IS RESPONSIBLE FOR COVERING OF BOREHOLE AFTER DRILLING.<br> SAVUKI
                                        DRILLING MPUMALANGA WILL NOT BE LIABLE FOR ANY ACCIDENTS CAUSED BY ANY UNCOVERED BOREHOLES.</i></b>
                            </div>

                            <div class='div_signatures'>
                                <div class="sub_down">

                                    <script src="https://cdn.jsdelivr.net/npm/signature_pad@2.3.2/dist/signature_pad.min.js"></script>

                        <?php
                        // EMPLOYEE SIGNATURE
                        if (file_exists("../jobcards/signatures/employee-jc" . $record['jc_no'] . "-" . $_SESSION['user_id'] . "-signature.png")) {
                            ?>
                                        <div class='jobcard_work_signature' style='margin-bottom:1vw;'>
                                            <h2>EMPLOYEE SIGNATURE</h2>
                                            <input type='image'
                                                src='../jobcards/signatures/employee-jc<?php echo $record['jc_no']; ?>-<?php echo $_SESSION['user_id']; ?>-signature.png'
                                                alt='employee signature' class="signature_image">
                                        </div>
                        <?php
                        } else {
                            ?>
                                        <div class='jobcard_work_signature' style='margin-bottom:1vw;'>
                                            <h2>EMPLOYEE SIGNATURE</h2>
                                            <canvas id="employee_signature" class="signature-pad"></canvas>
                                            <div style="display:flex;gap:10px;">
                                                <button type="button" id="clear_employee_signature" class="sign_btn">CLEAR</button>
                                            </div>
                                        </div>
                        <?php
                        }

                        // CLIENT SIGNATURE
                        if (file_exists("../jobcards/signatures/client-jc" . $record['jc_no'] . "-" . $_SESSION['user_id'] . "-signature.png")) {
                            ?>
                                        <div class='jobcard_work_signature' style='margin-bottom:1vw;'>
                                            <h2>CLIENT SIGNATURE</h2>
                                            <input type="image"
                                                src="../jobcards/signatures/client-jc<?php echo $record['jc_no']; ?>-<?php echo $_SESSION['user_id']; ?>-signature.png"
                                                alt="client signature" class="signature_image">
                                        </div>
                        <?php
                        } else {
                            ?>
                                        <div class='jobcard_work_signature' style='margin-bottom:1vw;'>
                                            <h2>CLIENT SIGNATURE</h2>
                                            <canvas id="client_signature" class="signature-pad"></canvas>
                                            <div style="display:flex;gap:10px;">
                                                <button type="button" id="clear_client_signature" class="sign_btn">CLEAR</button>
                                            </div>
                                        </div>
                        <?php
                        }
                        ?>

                                    <script>
                                        document.addEventListener('DOMContentLoaded', function () {
                                            const clientCanvas = document.getElementById('client_signature');
                                            const employeeCanvas = document.getElementById('employee_signature');
                                            const saveButton = document.getElementById('save_signatures');
                                            const clearClient = document.getElementById('clear_client_signature');
                                            const clearEmployee = document.getElementById('clear_employee_signature');
                                            const record_id = document.getElementById("jobcard_id")?.value;

                                            function resizeCanvas(canvas) {
                                                if (!canvas) return;
                                                const ratio = Math.max(window.devicePixelRatio || 1, 1);
                                                // use getBoundingClientRect to respect CSS height/width
                                                const rect = canvas.getBoundingClientRect();
                                                canvas.width = rect.width * ratio;
                                                canvas.height = rect.height * ratio;
                                                const ctx = canvas.getContext("2d");
                                                ctx.scale(ratio, ratio);
                                            }

                                            resizeCanvas(clientCanvas);
                                            resizeCanvas(employeeCanvas);

                                            window.addEventListener("resize", () => {
                                                resizeCanvas(clientCanvas);
                                                resizeCanvas(employeeCanvas);
                                            });

                                            // Improved SignaturePad options
                                            const padOptions = {
                                                minWidth: 0.5,
                                                maxWidth: 2.5,
                                                throttle: 0,
                                                velocityFilterWeight: 0.6,
                                                penColor: 'black',
                                                backgroundColor: 'rgba(255,255,255,0)'
                                            };

                                            const client_pad = clientCanvas ? new SignaturePad(clientCanvas, padOptions) : null;
                                            const employee_pad = employeeCanvas ? new SignaturePad(employeeCanvas, padOptions) : null;

                                            // Prevent scrolling while signing (mobile)
                                            [clientCanvas, employeeCanvas].forEach(canvas => {
                                                if (canvas) {
                                                    canvas.addEventListener("touchstart", e => e.preventDefault(), { passive: false });
                                                    canvas.addEventListener("touchmove", e => e.preventDefault(), { passive: false });
                                                }
                                            });

                                            // Clear buttons
                                            if (clearClient && client_pad) {
                                                clearClient.addEventListener('click', () => client_pad.clear());
                                            }

                                            if (clearEmployee && employee_pad) {
                                                clearEmployee.addEventListener('click', () => employee_pad.clear());
                                            }

                                            // Save button
                                            if (saveButton) {
                                                saveButton.addEventListener('click', function () {
                                                    if ((!client_pad || client_pad.isEmpty()) && (!employee_pad || employee_pad.isEmpty())) {
                                                        alert("Please provide at least one signature.");
                                                        return;
                                                    }

                                                    saveButton.disabled = true;
                                                    saveButton.textContent = "Saving...";

                                                    let uploads = 0;
                                                    let total = (client_pad && !client_pad.isEmpty() ? 1 : 0) +
                                                        (employee_pad && !employee_pad.isEmpty() ? 1 : 0);

                                                    function checkComplete() {
                                                        uploads++;
                                                        if (uploads === total) location.reload();
                                                    }

                                                    if (client_pad && !client_pad.isEmpty()) uploadSignature(client_pad, 'client', checkComplete);
                                                    if (employee_pad && !employee_pad.isEmpty()) uploadSignature(employee_pad, 'employee', checkComplete);
                                                });
                                            }

                                            // Upload function
                                            function uploadSignature(pad, type, callback) {
                                                const dataURL = pad.toDataURL('image/png');
                                                const blob = dataURLToBlob(dataURL);
                                                const formData = new FormData();

                                                formData.append('file', blob, type + '_signature.png');
                                                formData.append('record_id', record_id);
                                                formData.append('type', type);

                                                const xhr = new XMLHttpRequest();
                                                xhr.open("POST", "../jobcards/upload_signature.php", true);
                                                xhr.onreadystatechange = function () {
                                                    if (xhr.readyState === 4) {
                                                        if (xhr.status === 200 && xhr.responseText.includes("OK")) {
                                                            console.log(`${type} signature saved successfully.`);
                                                        } else {
                                                            alert(`Error saving ${type} signature: ${xhr.responseText}`);
                                                        }
                                                        if (callback) callback();
                                                    }
                                                };
                                                xhr.send(formData);
                                            }

                                            // Convert Base64 to Blob
                                            function dataURLToBlob(dataURL) {
                                                const binary = atob(dataURL.split(',')[1]);
                                                const array = [];
                                                for (let i = 0; i < binary.length; i++) array.push(binary.charCodeAt(i));
                                                return new Blob([new Uint8Array(array)], { type: 'image/png' });
                                            }
                                        });
                                    </script>
                                </div>

                                <div>
                        <?php
                        if (
                            !file_exists("../jobcards/signatures/employee-jc" . $record['jc_no'] . "-" . $_SESSION['user_id'] . "-signature.png") ||
                            !file_exists("../jobcards/signatures/client-jc" . $record['jc_no'] . "-" . $_SESSION['user_id'] . "-signature.png")
                        ) {
                            ?>
                                        <button type="button" id="save_signatures" class="sign_btn">SAVE</button>
                        <?php
                        }
                        ?>
                                </div>
                            </div>
                        </div>

        <?php
    }
    ?>

                    <div class="form_down" id="departure">

            <?php
            if ($has_departed && $has_arrived) {
                ?>

                            <h1 class="jobcard_h1">JOBCARD</h1>

                            <div style="display: flex; flex-direction: column;align-items: center;">
                    <?php

                    $current_jc_status = new input();
                    $current_jc_status->value("DEPARTED AND ARRIVED");
                    $current_jc_status->readonly();
                    $current_jc_status->class("inputs");
                    $current_jc_status->type("hidden");
                    $current_jc_status->id("jc_current_status");
                    $current_jc_status->onchange("check_status()");
                    $current_jc_status->add();

                    $record_id->add();

                    ?>
                                <div style="display: flex; flex-direction: row;">
                                    <div style="display: flex; flex-direction: column;">
                            <?php
                            $jc_no_label->add();
                            $jc_no->add();
                            ?>
                                    </div>
                                </div>

                    <?php
                    $client_name_lable->add();
                    $client_name->add();
                    $contact_name_label->add();
                    $contact_name->add();
                    ?>

                                <div style="display: flex; width: 100%; justify-content: space-between;">
                        <?php
                        $contact_number_label->add();
                        $other_number_label->add();
                        $alternate_number_label->add();
                        ?>
                                </div>
                                <div style="display: flex; width: 100%; justify-content: space-between;">
                        <?php
                        $phone->add();
                        $other_number->add();
                        $alternate_number->add();
                        ?>
                                </div>
                    <?php
                    $address_label->add();
                    $address->add();
                    $make_notes_btn->add();
                    ?>
                            </div>

            <?php

            } elseif ($has_departed) {
                $arrival_btn = new button();
                $arrival_btn->value("ARRIVAL");
                $arrival_btn->onclick("team_arrived()");
                $arrival_btn->id("arrival_button");
                $arrival_btn->add();

                $current_jc_status = new input();
                $current_jc_status->value("DEPARTED");
                $current_jc_status->readonly();
                $current_jc_status->class("inputs");
                $current_jc_status->type("hidden");
                $current_jc_status->id("jc_current_status");
                $current_jc_status->onchange("check_status()");
                $current_jc_status->add();

                $depart_ajax = new js_ajax();
                $depart_ajax->function_name("team_arrived");
                $depart_ajax->insert("jobcard_timeline");
                $depart_ajax->selected_div("arrival");
                $depart_ajax->add_column_and_value("jobcard_id={$_GET['record_id']},date_time={$current_date_time},type=ARRIVED,user_id={$_SESSION['user_id']},status=0");
                $depart_ajax->on_success("ARRIVAL CAPTURED");
            } else {

                $depart_btn = new button();
                $depart_btn->value("DEPARTURE");
                $depart_btn->onclick("team_departed()");
                $depart_btn->id("departure_button");
                $depart_btn->add();

                $current_jc_status = new input();
                $current_jc_status->value("START");
                $current_jc_status->readonly();
                $current_jc_status->class("inputs");
                $current_jc_status->type("hidden");
                $current_jc_status->id("jc_current_status");
                $current_jc_status->onchange("check_status()");
                $current_jc_status->add();

                $depart_ajax = new js_ajax();
                $depart_ajax->function_name("team_departed");
                $depart_ajax->insert("jobcard_timeline");
                $depart_ajax->selected_div("departure");
                $depart_ajax->add_column_and_value("jobcard_id={$_GET['record_id']},date_time={$current_date_time},type=DEPARTURE,user_id={$_SESSION['user_id']},status=0");
                $depart_ajax->on_success("DEPARTURE CAPTURED");

            }

            ?>

                    </div>

        <?php

        if ($has_departed && $has_arrived) {

            $current_jc_status = new input();
            $current_jc_status->value("DEPARTED AND ARRIVED");
            $current_jc_status->readonly();
            $current_jc_status->class("inputs");
            $current_jc_status->type("hidden");
            $current_jc_status->id("jc_current_status");
            $current_jc_status->onchange("check_status()");

            ?>

                        <div class="form_down" id="arrival">
                            <h1>JOBCARD</h1>

                            <div style="display: flex; flex-direction: column;align-items: center;width: 100%;">
                    <?php
                    $res_jobcard = $db->query("jobcards", "SELECT * FROM jobcards WHERE jc_no = {$_GET['record_id']} ORDER BY record_id DESC");
                    $jobcard_data = $res_jobcard->fetch_assoc();

                    $res_lead = $db->query("leads", "SELECT * FROM leads WHERE jc_no = {$_GET['record_id']} ORDER BY record_id DESC");
                    $lead_data = $res_lead->fetch_assoc();

                    $getLocation->add();
                    // Latitude: -25.482210, Longitude: 30.963649
            
                    //split the string with a comma
                    $lat = explode(", ", $jobcard_data['drill_co_ordinates'])[0];
                    // echo $lat;
            
                    $long = explode(", ", $jobcard_data['drill_co_ordinates'])[1];
                    // echo $long;
                    ?>
                                <div id="map"></div>

                                <style>
                                    #map {
                                        height: 70vh;
                                        width: 80%;
                                        margin-top: 10px;
                                    }

                                    #coords {
                                        font-family: monospace;
                                        margin-top: 10px;
                                    }

                                    #pin {
                                        width: 100%;
                                        font-family: monospace;
                                        padding: 5px;
                                        margin-top: 10px;
                                    }

                                    @media all and (min-width: 425px) and (max-width: 768px) {
                                        #map {
                                            height: 30vh;
                                            width: 90%;
                                            margin-top: 5vw;
                                        }

                                        #coords {
                                            font-family: monospace;
                                            margin-top: 10px;
                                        }

                                        #pin {
                                            width: 100%;
                                            font-family: monospace;
                                            padding: 5px;
                                            margin-top: 10px;
                                        }
                                    }
                                </style>

                                <script>

                                    let map;
                                    let marker;

                                    function updateCoords(lat, lng) {
                                        document.getElementById("drill_co_ordinates").value =
                                            `${lat.toFixed(6)}, ${lng.toFixed(6)}`;
                                    }

                                    function getLocation() {
                                        if (navigator.geolocation) {
                                            navigator.geolocation.getCurrentPosition(
                                                position => {
                                                    const lat = position.coords.latitude;
                                                    const lng = position.coords.longitude;

                                                    const userLocation = { lat, lng };
                                                    updateCoords(lat, lng);

                                                    if (!map) {
                                                        map = new google.maps.Map(document.getElementById("map"), {
                                                            center: userLocation,
                                                            zoom: 18
                                                        });
                                                    } else {
                                                        map.setCenter(userLocation);
                                                    }

                                                    if (!marker) {
                                                        marker = new google.maps.Marker({
                                                            position: userLocation,
                                                            map: map,
                                                            title: "Drag to adjust location",
                                                            draggable: true
                                                        });

                                                        marker.addListener("dragend", () => {
                                                            const pos = marker.getPosition();
                                                            updateCoords(pos.lat(), pos.lng());
                                                        });

                                                        marker.addListener("drag", () => {
                                                            const pos = marker.getPosition();
                                                            updateCoords(pos.lat(), pos.lng());
                                                        });

                                                    } else {
                                                        marker.setPosition(userLocation);
                                                    }
                                                },
                                                error => {
                                                    alert("Error getting location: " + error.message);
                                                },
                                                {
                                                    enableHighAccuracy: true,
                                                    timeout: 10000,
                                                    maximumAge: 0
                                                }
                                            );
                                        } else {
                                            alert("Geolocation is not supported by your browser.");
                                        }
                                    }
                                </script>

                                <script async defer
                                    src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCXu62pAxEnoWh-eXMpYBkGsz_iX-EVm2k"></script>

                    <?php
                    $pin->add();


                    if (!empty($jobcard_data['slip'])) {
                        $previous_payments = explode(", ", $jobcard_data['slip']);

                        $slip_label = new label();
                        $slip_label->for("slip_label");
                        $slip_label->value("PREVIOUS AMOUNT PAID");

                        $amount_paid = new input();
                        $amount_paid->class("inputs");
                        $amount_paid->type("number");
                        $amount_paid->placeholder("AMOUNT PAID");
                        $amount_paid->name("amount_paid");
                        $amount_paid->id("amount_paid");
                        $amount_paid->value($lead_data['amount']);
                        $amount_paid->readonly();

                        $slip_label->add();
                        $amount_paid->add();

                        ?>

                                    <div id="existing_slips" style="display: flex; flex-direction: row; align-items: center; margin-bottom: 20px;">
                            <?php
                            foreach ($previous_payments as $payment) {
                                $payment = trim($payment);
                                $i = 0;

                                if (!empty($payment) && file_exists("../jobcards/images/" . $payment)) {
                                    echo "<button type=\"button\" class=\"submit_btn\" onclick=\"window.open('../jobcards/images/$payment', '_blank')\">SLIP IMAGE</button>";

                                }
                            }
                            ?>
                                    </div>
                    <?php
                    }

                    $invoice_btn = new button();
                    $invoice_btn->value("INVOICE");
                    $invoice_btn->onclick("invoice()");

                    $payment_label = new label();
                    $payment_label->for("payment");
                    $payment_label->value("CURRENT PAYMENT TYPE");

                    $payment_method = new select();
                    $payment_method->class("inputs");
                    $payment_method->name("payment_method");
                    $payment_method->id("payment_method");
                    $payment_method->onchange("payment_type()");
                    $payment_method->add_option("", "Payment Method");
                    $payment_method->add_option("CASH", "CASH");
                    $payment_method->add_option("EFT", "EFT");

                    ?>

                                <div style='display:flex; flex-direction: column; width: 100%; align-items: center;'>

                        <?php
                        $payment_label->add();
                        $payment_method->add();
                        ?>
                                    <div id='cash' style='display: none; flex-direction: column; align-items: center;'>
                            <?php
                            $amount_label->add();
                            $amount->add();
                            ?>
                                    </div>
                                    <div style='display: flex; width: 90%; flex-wrap: wrap; justify-content: center;'>
                                        <div id='eft' style='display: none; flex-direction: column; align-items: center;'>
                                <?php

                                // new camera('slip_file', $_GET['record_id'], '../jobcards/slips/', 'slip');
                        
                                ?>
                                            <style>
                                                video,
                                                canvas {
                                                    width: 400px;
                                                    height: 300px;
                                                    border: 3px solid #ccc;
                                                    border-radius: 2vw;
                                                    margin-top: 10px;
                                                }

                                                @media all and (max-width: 600px) {

                                                    video,
                                                    canvas {
                                                        width: 600px;
                                                        height: 450px;
                                                        margin-top: -5vw;
                                                    }
                                                }
                                            </style>

                                            <video style="display: none;" id="camera_slip" autoplay playsinline></video>
                                            <br>

                                            <button id="open_camera_slip" class="submit_btn" onclick="openSlipCamera()">Open
                                                Camera</button>

                                            <div id="load_camera_slip" style="display: none; width: 100%; justify-content: center;">
                                                <button class="submit_btn" onclick="captureSlipPhoto()">Capture Photo</button>
                                                <button class="submit_btn" onclick="stopSlipCamera()">Stop Camera</button>
                                            </div>

                                            <div id="captured_image_slip" style="display:none">
                                                <h3>Captured Image:</h3>
                                                <canvas id="snapshot_slip"></canvas>
                                            </div>

                                            <script>
                                                let stream_slip;

                                                async function openSlipCamera() {
                                                    const video = document.getElementById("camera_slip");
                                                    const load_camera = document.getElementById("load_camera_slip");
                                                    const open_camera = document.getElementById("open_camera_slip");

                                                    try {

                                                        stream_slip = await navigator.mediaDevices.getUserMedia({
                                                            video: { facingMode: "environment" },
                                                            audio: false
                                                        });

                                                        const video = document.getElementById("camera_slip");
                                                        video.srcObject = stream_slip;
                                                        video.style.display = "block";

                                                        load_camera.style.display = "flex";
                                                        open_camera.style.display = "none";


                                                    } catch (error) {
                                                        alert("Error accessing camera: " + error.message);
                                                    }
                                                }

                                                function captureSlipPhoto() {
                                                    const video = document.getElementById("camera_slip");
                                                    const canvas = document.getElementById("snapshot_slip");
                                                    const context = canvas.getContext("2d");
                                                    const captured_image = document.getElementById("captured_image_slip");
                                                    const load_camera = document.getElementById("load_camera_slip");
                                                    const jobcard_no = "<?php echo $_GET['record_id']; ?>";

                                                    load_camera.style.display = "none";
                                                    canvas.width = video.videoWidth;
                                                    canvas.height = video.videoHeight;
                                                    context.drawImage(video, 0, 0, canvas.width, canvas.height);

                                                    captured_image.style.display = "none";

                                                    const imageData = canvas.toDataURL("image/png");

                                                    stopSlipCamera();
                                                    saveCapturedSlipImage(imageData, jobcard_no);
                                                }

                                                function stopSlipCamera() {
                                                    const open_camera = document.getElementById("open_camera_slip");
                                                    const load_camera = document.getElementById("load_camera_slip");
                                                    const video = document.getElementById("camera_slip");

                                                    video.style.display = "none";
                                                    load_camera.style.display = "none";
                                                    open_camera.style.display = "block";
                                                    if (stream_slip) {
                                                        stream_slip.getTracks().forEach(track => track.stop());
                                                        stream_slip = null;
                                                        document.getElementById("camera_slip").srcObject = null;
                                                    }
                                                }

                                                function saveCapturedSlipImage(imageData, jobcard_no) {
                                                    const video = document.getElementById("camera_slip");
                                                    const folder_path = "../jobcards/slips/";
                                                    const section_name = "slip";

                                                    video.style.display = "none";

                                                    var formData = new FormData();

                                                    formData.append('image', imageData);
                                                    formData.append('jobcard_no', jobcard_no);
                                                    formData.append('folder_path', folder_path);
                                                    formData.append('section_name', section_name);

                                                    const xhr = new XMLHttpRequest();
                                                    xhr.open('POST', '../jobcards/save_camera.php', true);
                                                    xhr.onreadystatechange = function () {
                                                        if (xhr.readyState == 4 && xhr.status == 200) {
                                                            if (xhr.responseText != '0') {
                                                                console.log('fileName: ' + xhr.responseText);
                                                                alert('Photo saved successfully!');
                                                                if ('slip' != '') {
                                                                    document.getElementById('slip_file').style.display = 'block';
                                                                    document.getElementById('slip_file').value = xhr.responseText;
                                                                }
                                                            } else {
                                                                alert('Error saving photo!');
                                                            }
                                                        }
                                                    };
                                                    xhr.send(formData);
                                                }
                                            </script>

                                            <input type='text' style="display: none;" class="inputs" id='slip_file' name='slip_file'>
                                <?php
                                $amount->add();

                                ?>
                                        </div>
                                    </div>

                                    <script>
                                        function payment_type() {
                                            var payment = document.getElementById("payment_method").value;
                                            if (payment == "EFT") {
                                                document.getElementById("eft").style.display = "flex";
                                                document.getElementById("cash").style.display = "none";
                                            } else if (payment == "CASH") {
                                                document.getElementById("cash").style.display = "flex";
                                                document.getElementById("eft").style.display = "none";
                                            } else {
                                                document.getElementById("cash").style.display = "none";
                                                document.getElementById("eft").style.display = "none";
                                            }
                                        }
                                    </script>

                                    <label class="labels">DIESEL START LITERS</label>
                        <?php
                        $diesel_start->add();
                        $current_jc_status->add();

                        $record_id = new input();
                        $record_id->class("inputs");
                        $record_id->type("hidden");
                        $record_id->name("record_id");
                        $record_id->id("record_id");
                        $record_id->value($_GET['record_id']);
                        $record_id->add();

                        $res_arrival = $db->query("jobcard_timeline", "SELECT * FROM jobcard_timeline WHERE jobcard_id = {$_GET['record_id']} ORDER BY record_id DESC LIMIT 1");
                        // echo "SELECT * FROM jobcard_timeline WHERE jobcard_id = {$_GET['record_id']} ORDER BY record_id DESC LIMIT 1";
                
                        $record_res = $res_arrival->fetch_assoc();
                        // echo $record_res['type'];
                        if ($record_res['type'] == "ARRIVED") {
                            $next_btn = new button();
                            $next_btn->value("SAVE");
                            $next_btn->onclick("if (check()) { update_jobcard(); next(); }");
                            $next_btn->add();

                            $update_ajax = new js_ajax();
                            $update_ajax->function_name("update_jobcard");
                            $update_ajax->update("jobcards");

                            $riem_ajax = new js_ajax();
                            $riem_ajax->function_name("next");
                            $riem_ajax->selected_div("jobcard_time");
                            $riem_ajax->insert("jobcard_timeline");
                            $riem_ajax->add_column_and_value("jobcard_id={$_GET['record_id']},date_time={$current_date_time},type=RIEMING,user_id={$_SESSION['user_id']}");
                            $riem_ajax->redirect("jobcard_actions.php?record_id={$_GET['record_id']}&jobcard_id={$record['record_id']}&user_id={$_SESSION['user_id']}");
                            $riem_ajax->on_success("DATA CAPTURED AND SAVED");

                        } elseif ($record_res['type'] == "DEPARTED") {
                            $next_btn = new button();
                            $next_btn->value("DISABLED");
                            $next_btn->style("background-color: #00008045; color: white;");
                            $next_btn->add();
                        } else {

                            $next_btn = new button();
                            $next_btn->value("NEXT");
                            $next_btn->onclick("submit_jobcard()");
                            $next_btn->add();

                            $submit_details = new js_ajax();
                            $submit_details->function_name("submit_jobcard");
                            $submit_details->update("jobcards");
                            // $submit_details->redirect("jobcard_actions.php?record_id={$_GET['record_id']}&jobcard_id={$record['record_id']}&user_id={$_SESSION['user_id']}");
                            $submit_details->exclude_inputs("jc_current_status");
                            $submit_details->on_success("DATA CAPTURED AND SAVED");


                            ?>
                                        <!-- <button type="submit" class="submit_btn"
                                            onclick="window.location.href='jobcard_actions.php?record_id=<?php echo $_GET['record_id']; ?>&jobcard_id=<?php echo $record['record_id']; ?>&user_id=<?php echo $_SESSION['user_id']; ?>'">NEXT</button> -->
                        <?php
                        }
                        ?>
                                </div>
                            </div>
                        </div>
        <?php
        }
} else {
    ?>
                    <script>
                        window.location.href = "../jobcards/jobcard_actions.php?record_id=<?= $record['record_id'] ?>&jc_no=<?= $_GET['record_id'] ?>";
                    </script>
    <?php
}

?>

<script>

    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 check_status() {
        var status = document.getElementById("jc_current_status").value.trim();
        var arrivalDiv = document.getElementById("arrival");
        var departureDiv = document.getElementById("departure");

        if (status === "START") {
            departureDiv.style.display = "flex";
            arrivalDiv.style.display = "none";
        } else if (status === "DEPARTED") {
            departureDiv.style.display = "flex";
            arrivalDiv.style.display = "none";
        } else if (status === "DEPARTED AND ARRIVED") {
            departureDiv.style.display = "none";
            arrivalDiv.style.display = "flex";
        }
    }

    function check() {
        var client_name = document.getElementById("client_name").value.trim();
        var contact_name = document.getElementById("contact_name").value.trim();
        var contact_number = document.getElementById("contact_number").value.trim();
        var address = document.getElementById("address").value.trim();
        var drill_co_ordinates = document.getElementById("drill_co_ordinates").value.trim();
        var diesel_start = document.getElementById("diesel_start").value.trim();

        if (client_name === "" || client_name == null) {
            alert("Please enter Client Name");
            return false;
        }

        if (contact_name === "" || contact_name == null) {
            alert("Please enter Contact Name");
            return false;
        }

        if (contact_number === "" || contact_number == null) {
            alert("Please enter Contact Number");
            return false;
        }

        if (address === "" || address == null) {
            alert("Please enter Address");
            return false;
        }

        if (drill_co_ordinates === "" || drill_co_ordinates == null) {
            alert("Please enter Drill Co-ordinates");
            return false;
        }

        if (diesel_start === "" || diesel_start == null) {
            alert("Please enter Diesel Start");
            return false;
        }

        // ✅ Everything is valid
        return true;
    }
</script>