<?php include "../../root.class.php";
$html = new html();
$html->add_styles_page();
$db = new db_safeguard();

$current_date_time = date("Y-m-d H:i", strtotime("+2 hours"));

if (isset($_GET['created'])) {
    echo "<script>alert('CREATED SUCCESSFULLY');</script>";
}
// Get record data
$record_id = $_GET['record_id'];
$leads_res = $db->query("leads", "SELECT * FROM leads WHERE record_id = {$record_id}");
if ($leads_res->num_rows == 0) {
    die("Lead not found");
}

$lead_data = $leads_res->fetch_assoc();
$jc_no = $lead_data['jc_no'];

$jobcard_data_res = $db->query("jobcards", "SELECT * FROM jobcards WHERE jc_no = {$lead_data['jc_no']}");
$jobcard_data = $jobcard_data_res->fetch_assoc();

$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']);

$date = new input();
$date->class("inputs");
$date->type("hidden");
$date->name("date_created");
$date->id("date_created");
$date->style("display: none;");
$date->value($lead_data['date_created']);
$date->readonly();

$jobcard_number_label = new label();
$jobcard_number_label->for("jc_no_label");
$jobcard_number_label->value("JOBCARD NO");

$jobcard_number = new input();
$jobcard_number->class("inputs");
$jobcard_number->name("jc_no");
$jobcard_number->id("jc_no");
$jobcard_number->type("number");
$jobcard_number->value_from_db("leads", "jc_no", "record_id = {$_GET['record_id']}");
$jobcard_number->readonly();

$contact_number_label = new label();
$contact_number_label->for("contact_number");
$contact_number_label->value("CONTACT NUMBER");

$phone = new input();
$phone->class("inputs");
$phone->type("text");
$phone->placeholder("PHONE NUMBER");
$phone->name("contact_number");
$phone->id("contact_number");
$phone->value_from_db("leads", "contact_number", "record_id = {$_GET['record_id']}");

$client_name_label = new label();
$client_name_label->for("client_name");
$client_name_label->value("CLIENT NAME");

$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 = {$jobcard_data['record_id']}");

$contact_name_label = new label();
$contact_name_label->for("contact_name");
$contact_name_label->value("CONTACT NAME");

$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");
$contact_name->value_from_db("jobcards", "contact_name", "record_id = {$jobcard_data['record_id']}");


$other_number_label = new label();
$other_number_label->for("other_number");
$other_number_label->value("OTHER NUMBER");

$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");
$other_number->value_from_db("leads", "other_number", "record_id = {$_GET['record_id']}");

$alternate_number_label = new label();
$alternate_number_label->for("alternate_number");
$alternate_number_label->value("ALTERNATE NUMBER");

$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");
$alternate_number->value_from_db("leads", "alternate_number", "record_id = {$_GET['record_id']}");

$type_label = new label();
$type_label->for("type_label");
$type_label->value("TYPE");

$type = new select();
$type->class("inputs");
$type->name("type");
$type->required();
$type->id("type");
$type->add_option("LEAD", "LEAD");
$type->add_option("JOBCARD", "JOBCARD");

$area_label = new label();
$area_label->for("area");
$area_label->value("AREA");

$area = new input();
$area->class("inputs");
$area->type("text");
$area->placeholder("AREA");
$area->name("area");
$area->id("area");
$area->value_from_db("leads", "area", "record_id = {$_GET['record_id']}");

$status_label = new label();
$status_label->for("status");
$status_label->value("STATUS");

$status = new select();
$status->class("inputs");
$status->name("status");
$status->id("status");
$status->add_option("WAITING FOR DEPOSIT", "WAITING FOR DEPOSIT");
$status->add_option("FOLLOW UP", "FOLLOW UP");
$status->add_option("QUOTE SENT", "QUOTE SENT");
$status->add_option("WAITNG FOR CONFIRMATION", "WAITNG FOR CONFIRMATION");
$status->add_option("ASSIGN TO TEAM", "ASSIGN TO TEAM");

$user_id = new input();
$user_id->class("inputs");
$user_id->type("hidden");
$user_id->name("user_created_id");
$user_id->id("user_created_id");
$user_id->value($_SESSION['user_id']);

$payment_label = new label();
$payment_label->for("payment_label");
$payment_label->value("PAYMENT MADE");

$payment = new select();
$payment->class("inputs");
$payment->name("payment_made");
$payment->id("payment_made");
$payment->add_option("YES", "YES");
$payment->add_option("NO", "NO");
$payment->onchange("payment()");

$payment_type_label = new label();
$payment_type_label->for("payment_type_label");
$payment_type_label->value("PAYMENT TYPE");

$payment_type = new select();
$payment_type->class("inputs");
$payment_type->name("payment_type");
$payment_type->id("payment_type");
$payment_type->add_option("CASH", "CASH");
$payment_type->add_option("EFT", "EFT");
$payment_type->add_option("OTHER", "OTHER");

$amount_label = new label();
$amount_label->for("amount_label");
$amount_label->value("AMOUNT");

$amount = new input();
$amount->class("inputs");
$amount->type("number");
$amount->placeholder("AMOUNT");
$amount->name("amount");
$amount->id("amount");
$amount->value_from_db("leads", "amount", "record_id = {$_GET['record_id']}");

$slip_image_label = new label();
$slip_image_label->for("slip_image_label");
$slip_image_label->value("SLIP IMAGE");

$slip_image = new input();
$slip_image->class("inputs");
$slip_image->name("slip_image");
$slip_image->id("slip_image");
$slip_image->type("text");
$slip_image->style("width:40vw; display: none;");
$slip_image->value_from_db("leads", "slip_image", "record_id = {$_GET['record_id']}");

$add_slip = new button();
$add_slip->value("ADD SLIP");
$add_slip->onclick("add_slip_image()");

$team_assigned_label = new label();
$team_assigned_label->for("team_assigned_label");
$team_assigned_label->value("TEAM ASSIGNED");

$team_assigned = new select();
$team_assigned->class("inputs");
$team_assigned->name("team_assigned_id");
$team_assigned->id("team_assigned_id");
$team_assigned->fill_from_db("teams", "record_id", "name", "status = 'ACTIVE'");

$additional_notes_label = new label();
$additional_notes_label->for("additional_notes_label");
$additional_notes_label->value("ADDITIONAL NOTES");

$additional_notes = new textarea();
$additional_notes->class("inputs");
$additional_notes->placeholder("ADDITIONAL NOTES");
$additional_notes->name("additional_notes");
$additional_notes->id("additional_notes");
$additional_notes->style("width:50%;");
$additional_notes->value_from_db("leads", "additional_notes", "record_id = {$_GET['record_id']}");

$submit_btn = new button();
$submit_btn->value("UPDATE");

?>

<form action="edit_lead.ajax.php" method="post" enctype="multipart/form-data">
    <div class="form_down">
        <h1>EDIT</h1>
        <?php
        $user_id->add();
        $record_id->add();
        $jobcard_number_label->add();
        $jobcard_number->add();
        $date->add();
        $client_name_label->add();
        $client_name->add();
        $contact_name_label->add();
        $contact_name->add();
        ?>

        <div style="display: flex; width: 45%; justify-content: space-between;">
            <?php
            $contact_number_label->add();
            $other_number_label->add();
            $alternate_number_label->add();
            ?>
        </div>
        <div>
            <?php
            $phone->add();
            $other_number->add();
            $alternate_number->add();
            ?>
        </div>

        <?php
        $area_label->add();
        $area->add();
        $payment_label->add();


        $leads_res = $db->query("leads", "SELECT * FROM leads WHERE record_id = {$_GET['record_id']}");
        $payment_made = "";

        if ($leads_res->num_rows > 0) {
            while ($leads = $leads_res->fetch_assoc()) {
                $payment_made = $leads['payment_made'];
                $payment_type = $leads['payment_type'];
                $type = $leads['type'];
                $status = $leads['status'];
            }
        }

        ?>
        <select name="payment_made" id="payment_made" class="inputs" onchange="payment()">
            <option value=""></option>
            <option value="YES" <?php if ($payment_made == "YES")
                echo "selected"; ?>>YES</option>
            <option value="NO" <?php if ($payment_made == "NO")
                echo "selected"; ?>>NO</option>
        </select>

        <div id="payment_yes" style="display: flex;flex-direction: column;align-items: center;">
            <div style="display: flex;flex-direction: row;">
                <div style="display: flex;flex-direction: column;">
                    <?php
                    $payment_type_label->add();
                    ?>
                    <select name="payment_type" id="payment_type" class="inputs" onchange="payment_type_func()">
                        <option value=""></option>
                        <option value="CASH" <?php if ($lead_data['payment_type'] == "CASH")
                            echo "selected"; ?>>CASH</option>
                        <option value="EFT" <?php if ($lead_data['payment_type'] == "EFT")
                            echo "selected"; ?>>EFT</option>
                        <option value="OTHER" <?php if ($lead_data['payment_type'] == "OTHER")
                            echo "selected"; ?>>OTHER
                        </option>
                    </select>
                </div>
                <div style="display: flex;flex-direction: column;">
                    <?php
                    $amount_label->add();
                    $amount->add();
                    ?>
                </div>
            </div>
            <div id="slip_section" style="display: flex;flex-direction: column;align-items: center;">
                <?php
                // Display existing slip images
                if (!empty($lead_data['slip_image'])) {

                    ?>
                    <div class="inputs" onclick="window.location.href = '<?php echo $lead_data['slip_image']; ?>';">
                        VIEW/DOWNLOAD P.O.P.
                    </div>
                    <?php
                } else {
                    ?>
                    <div id="slip_list" style="display: flex; flex-direction: column; align-items: center;"></div>
                    <input type="file" class="inputs" id="slip_image" name="slip_image">
                    <?php
                }
                ?>

            </div>
        </div>



        <?php
        $type_label->add();

        ?>
        <select name="type" id="type" class="inputs">
            <option value=""></option>
            <option value="LEAD" <?php if ($lead_data['type'] == "LEAD")
                echo "selected"; ?>>LEAD</option>
            <option value="JOBCARD" <?php if ($lead_data['type'] == "JOBCARD")
                echo "selected"; ?>>JOBCARD</option>
        </select>
        <?php
        $status_label->add();
        ?>

        <select name="status" id="status" class="inputs" onchange="assign_team()">
            <option value=""></option>
            <option value="WAITING FOR DEPOSIT" <?php if ($lead_data['status'] == "WAITING FOR DEPOSIT")
                echo "selected"; ?>>
                WAITING FOR DEPOSIT</option>
            <option value="FOLLOW UP" <?php if ($lead_data['status'] == "FOLLOW UP")
                echo "selected"; ?>>FOLLOW UP
            </option>
            <option value="QUOTE SENT" <?php if ($lead_data['status'] == "QUOTE SENT")
                echo "selected"; ?>>QUOTE SENT
            </option>
            <option value="WAITNG FOR CONFIRMATION" <?php if ($lead_data['status'] == "WAITNG FOR CONFIRMATION")
                echo "selected"; ?>>WAITNG FOR CONFIRMATION</option>
            <option value="ASSIGN TO TEAM" <?php if ($lead_data['status'] == "ASSIGN TEAM")
                echo "selected"; ?>>ASSIGN TO
                TEAM
            </option>
        </select>

        <script>
            document.getElementById("status").value = '<?php echo $lead_data['status']; ?>';
        </script>

        <?php
        $team_assigned_label->add();
        ?>
        <div id="teams" style="flex-direction: column;">
            <select name="team_assigned_id" id="team_assigned_id" class="inputs">
                <option value=""></option>
                <option value="1" <?php if ($lead_data['team_assigned_id'] == "1")
                    echo "selected"; ?>>B2</option>
                <option value="2" <?php if ($lead_data['team_assigned_id'] == "2")
                    echo "selected"; ?>>B5</option>
                <option value="3" <?php if ($lead_data['team_assigned_id'] == "3")
                    echo "selected"; ?>>EWG</option>
                <option value="4" <?php if ($lead_data['team_assigned_id'] == "4")
                    echo "selected"; ?>>B14</option>
                <option value="5" <?php if ($lead_data['team_assigned_id'] == "5")
                    echo "selected"; ?>>OFFICE</option>
            </select>
        </div>
        <?php

        $additional_notes_label->add();
        $additional_notes->add();

        $submit_btn->add();
        ?>

        <style>
            .summary_popup {
                display: none;
                position: fixed;
                z-index: 1000;
                left: 0;
                top: 0;
                width: 100%;
                height: 100%;
                background-color: rgba(0, 0, 0, 0.5);
            }

            .summary_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;
            }

            .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
            style="display: flex; flex-direction: column; align-items: center; background-color: white; margin: 4vw; border-radius: 2vw; width: 80%;">
            <?php
            $res_data = $db->query("jobcard_timeline", "SELECT * FROM jobcard_timeline WHERE jobcard_id = {$jobcard_data['record_id']}  ORDER BY record_id ASC");

            if ($res_data->num_rows > 0) {

                $jobcard_res = $db->query("jobcards", "SELECT * FROM jobcards WHERE record_id = {$jobcard_data['record_id']}");
                $jobcard = $jobcard_res->fetch_assoc();

                // echo $jobcard['record_id'];
            
                ?>

                <h1>JOBCARD SUMMARY</h1>

                <table
                    style='border-radius: 2vw;padding-top: 2vw;padding-bottom: 2vw;width:60%; text-align:center; border: 2px solid black;background-color: #ffffffc4;'>
                    <tr>
                        <th>TYPE</th>
                        <th>METERS</th>
                        <th>DATE</th>
                    </tr>
                    <?php
                    $riem_meters = 0;
                    $drilling_meters = 0;
                    $casing_meters = 0;
                    $blasting_meters = 0;

                    while ($jc_timeline = $res_data->fetch_assoc()) {

                        if ($jc_timeline['type'] == "RIEM_STOP" || $jc_timeline['type'] == "RIEMING_STOP") {
                            $riem_meters += $jc_timeline['meters'];
                        }

                        if ($jc_timeline['type'] == "DRILLING_STOP") {
                            $drilling_meters += $jc_timeline['meters'];
                        }

                        if ($jc_timeline['type'] == "CASING_STOP") {
                            $casing_meters += $jc_timeline['meters'];
                        }

                        if ($jc_timeline['type'] == "BLASTING_START" || $jc_timeline['type'] == "BLASTING_STOP") {
                            $blasting_meters += $jc_timeline['meters'];
                        }

                        ?>
                        <tr>
                            <td> <?php echo $jc_timeline['type'] ?> </td>
                            <td> <?php echo $jc_timeline['meters'] ?> </td>
                            <td> <?php echo $jc_timeline['date_time'] ?> </td>
                        </tr>
                        <?php
                    }
                    ?>
                </table><br><br>

                <table style="width:80%;">
                    <tr>
                        <td> </td>
                        <td> TOTAL </td>
                    </tr>
                    <tr>
                        <td> TOTAL RIEM METERS </td>
                        <td> <?php echo $riem_meters ?> </td>
                    </tr>
                    <tr>
                        <td> TOTAL DRILLING METERS </td>
                        <td> <?php echo $drilling_meters ?> </td>
                    </tr>
                    <tr>
                        <td> TOTAL CASING METERS </td>
                        <td> <?php echo $casing_meters ?> </td>
                    </tr>
                    <tr>
                        <td> TOTAL BLASTING METERS</td>
                        <td> <?php echo $blasting_meters ?></td>
                    </tr>
                </table>

                <br><br>

            </div>

            <div
                style="display: flex; flex-direction: column; align-items: center; background-color: white; margin: 4vw; border-radius: 2vw; padding: 2vw;width: 80%;">
                <table
                    style='border-radius: 2vw;padding-top: 2vw;padding-bottom: 2vw;width:60%; text-align:center; border: 2px solid black;background-color: #ffffffc4;'>
                    <tr>
                        <th></th>
                        <th>VALUE</th>
                    </tr>
                    <tr>
                        <td>Interested in Pump: </td>
                        <td><?php echo $jobcard['Interested_in_pump'] == 1 ? "YES" : "NO"; ?></td>
                    </tr>
                    <tr>
                        <td>Water Flow: </td>
                        <td> <?php echo $jobcard['water_flow']; ?> </td>
                    </tr>
                    <tr>
                        <td>Compressor Hours: </td>
                        <td> <?php echo $jobcard['compressor_hours'] ?> </td>
                    </tr>
                    <tr>
                        <td>Diesel Start: </td>
                        <td> <?php echo $jobcard['diesel_start'] ?> </td>
                    </tr>
                    <tr>
                        <td>Diesel Stop: </td>
                        <td> <?php echo $jobcard['diesel_stop'] ?> </td>
                    </tr>

                    </tr>
                </table>
            </div>

            <div
                style="display: flex; flex-direction: column; align-items: center; background-color: white; margin: 4vw; border-radius: 2vw; padding: 2vw; width: 80%;">

                <script src="https://cdn.jsdelivr.net/npm/signature_pad@2.3.2/dist/signature_pad.min.js"></script>
                <?php

                // EMPLOYEE SIGNATURE
                $employee_files = glob("signatures/employee-jc{$jc_no}-*-signature.png");

                if (!empty($employee_files)) {
                    $employee_sig = $employee_files[0]; // first match
                    ?>
                    <div class='jobcard_work_signature' style='margin-bottom:1vw;'>
                        <h2>EMPLOYEE SIGNATURE</h2>
                        <input type='image' src='<?php echo $employee_sig; ?>' alt='employee signature' class="signature_image">
                    </div>
                    <?php
                }


                // CLIENT SIGNATURE
                $client_files = glob("signatures/client-jc{$jc_no}-*-signature.png");

                if (!empty($client_files)) {
                    $client_sig = $client_files[0]; // first match
                    ?>
                    <div class='jobcard_work_signature' style='margin-bottom:1vw;'>
                        <h2>CLIENT SIGNATURE</h2>
                        <input type="image" src="<?php echo $client_sig; ?>" alt="client signature" class="signature_image">
                    </div>
                    <?php
                }

                ?>

                <br>
            </div>

            <?php

            } else {
                ?>
            <h1>Job Card Summary</h1>
            <table
                style='border-radius: 2vw;padding-top: 2vw;padding-bottom: 2vw;width:50%; text-align:center; border: 2px solid black;background-color: #ffffffc4;'>
                <tr>
                    <th>NAME</th>
                    <th>VALUE</th>
                </tr>
                <tr>
                    <td></td>
                    <td> DATA NOT FOUND </td>
                    <td></td>
                </tr>

            </table>

            <?php
            }
            ?>


    </div>
</form>

<script>
    // Initialize on page load

    payment();
    payment_type_func();
    assign_team();

    function payment() {
        var payment = document.getElementById("payment_made");
        if (payment.value == "YES") {
            document.getElementById("payment_yes").style.display = "flex";
        } else if (payment.value == "NO") {
            document.getElementById("payment_yes").style.display = "none";
        } else {
            document.getElementById("payment_yes").style.display = "none";
        }
    }

    function payment_type_func() {
        var payment_type = document.getElementById("payment_type");
        if (payment_type.value === "EFT") {
            document.getElementById("slip_section").style.display = "flex";
        } else {
            document.getElementById("slip_section").style.display = "none";
        }
    }

    function assign_team() {
        var status = document.getElementById("status").value;
        if (status == "ASSIGN TO TEAM") {
            document.getElementById("teams").style.display = "flex";
        } else {
            document.getElementById("teams").style.display = "none";
        }
    }

    function check_number() {
        var contact_number = document.getElementById("contact_number");
        var other_number = document.getElementById("other_number");
        var alternate_number = document.getElementById("alternate_number");

        if (contact_number.value.length > 0) {
            if (contact_number.value.length != 10) {
                alert("Please enter a valid contact number.");
                contact_number.style.border = "3px solid red";
                return false;
            } else {
                contact_number.style.border = "3px solid green";
            }
        } else {
            contact_number.style.border = "3px solid orange";
        }
    }

    function remove_existing_image(filename) {
        if (!confirm("Are you sure you want to remove this image?")) {
            return;
        }

        var slip_image_input = document.getElementById("slip_image");
        var filenames = slip_image_input.value.split(",").map(f => f.trim());
        filenames = filenames.filter(f => f !== filename);
        slip_image_input.value = filenames.join(", ");

        // Remove the image element from DOM
        var existingSlips = document.getElementById("existing_slips");
        var images = existingSlips.getElementsByTagName("img");
        for (var i = 0; i < images.length; i++) {
            if (images[i].src.includes(filename)) {
                images[i].parentElement.remove();
                break;
            }
        }

        // Hide existing_slips div if no images left
        if (existingSlips.getElementsByTagName("img").length === 0) {
            existingSlips.style.display = "none";
        }

        console.log("Removed: " + filename);
        console.log("Updated slip_image: " + slip_image_input.value);
    }

    let slipCounter = 0;

    // function add_slip_image(file_save_path = "../jobcards/images/") {
    //     // Prevent form submission
    //     document.querySelector("form").addEventListener("submit", function(event) {
    //         event.preventDefault();
    //     });
    //     // Create new file input
    //     var new_input = document.createElement("input");
    //     new_input.type = "file";
    //     new_input.className = "inputs";
    //     new_input.accept = "image/jpeg,image/png";
    //     new_input.style.width = "40vw";

    //     // attach file_save_path as data attribute
    //     new_input.setAttribute("data-file-save-path", file_save_path);

    //     // Append to container
    //     document.getElementById("slip_list").appendChild(new_input);

    //     // Add change listener
    //     new_input.addEventListener("change", function () {
    //         if (this.files && this.files[0]) {
    //             var file = this.files[0];
    //             var savePath = this.getAttribute("data-file-save-path");
    //             var all_file_list = document.getElementById("slip_image");

    //             // --- Remove previous preview ---
    //             var nextElem = this.nextSibling;
    //             while (nextElem && nextElem.nodeType !== 1) {
    //                 nextElem = nextElem.nextSibling;
    //             }
    //             if (nextElem && nextElem.tagName === "IMG") {
    //                 nextElem.remove();
    //             }

    //             // --- Remove previous filename from all_file_list if exists ---
    //             if (this.dataset.prevFile) {
    //                 var filenames = all_file_list.value.split(",").map(f => f.trim());
    //                 filenames = filenames.filter(f => f !== this.dataset.prevFile);
    //                 all_file_list.value = filenames.join(", ");
    //             }

    //             // --- Preview ---
    //             var preview = document.createElement("img");
    //             preview.style.maxWidth = "200px";
    //             preview.style.height = "auto";
    //             preview.style.display = "block";
    //             preview.style.marginTop = "10px";

    //             var reader = new FileReader();
    //             reader.onload = function (e) {
    //                 preview.src = e.target.result;
    //             };
    //             reader.readAsDataURL(file);

    //             this.parentNode.insertBefore(preview, this.nextSibling);

    //             // --- Upload ---
    //             var formData = new FormData();
    //             // Replace spaces with underscores in filename
    //             var cleanName = file.name.replace(/\s+/g, '_');

    //             formData.append('fileToUpload', file);
    //             formData.append('ajax_type', "file_upload");
    //             formData.append('file_save_path', savePath);
    //             formData.append('file_name', cleanName);

    //             // Store reference to current input for use in callback
    //             var currentInput = this;

    //             var xhr = new XMLHttpRequest();
    //             xhr.onreadystatechange = function () {
    //                 if (xhr.readyState === XMLHttpRequest.DONE) {
    //                     if (xhr.status === 200) {
    //                         console.log(`Uploaded: ${file.name} → ${savePath}`);

    //                         // Add new filename to slip_image
    //                         if (all_file_list.value) {
    //                             all_file_list.value += ", " + cleanName;
    //                         } else {
    //                             all_file_list.value = cleanName;
    //                         }

    //                         // Store current filename in dataset for next change
    //                         currentInput.dataset.prevFile = cleanName;
    //                         console.log(`Updated slip_image: ${all_file_list.value}`);
    //                     } else {
    //                         console.error("Upload failed or server error:", xhr.responseText);
    //                         alert("Failed to upload image. Please try again.");
    //                     }
    //                 }
    //             };
    //             xhr.open("POST", "../jobcards/upload.php", true);
    //             xhr.send(formData);
    //         }
    //     });

    //     slipCounter++;
    // }
</script>