<?php include "../../root.class.php";
$html = new html();
$html->add_styles_page();
$db = new db_safeguard();

// Get record data
$record_id = $_GET['record_id'];

$work_res = $db->query("work_requests", "SELECT * FROM work_requests WHERE record_id = {$record_id}");
if ($work_res->num_rows == 0) {
    die("Lead not found");
}

$work_data = $work_res->fetch_assoc();
$jc_no = $work_data['jc_no'];

// echo "SELECT * FROM jobcards WHERE jc_no = {$work_data['jc_no']}";

$work_data_res = $db->query("work_requests", "SELECT * FROM work_requests WHERE record_id = {$_GET['record_id']}");

// echo "SELECT * FROM jobcards WHERE jc_no = {$work_data['jc_no']}";

if ($work_data_res->num_rows > 0) {
    $work_data = $work_data_res->fetch_assoc();

    if ($work_data['type'] == "JOBCARD") {
        ?>
        <script>
            window.location.href = "../jobcards/edit_jobcard.php?jc_no=<?php echo $work_data['jc_no']; ?>";
        </script>

        <?php
    }
}

$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_from_db("work_requests", "date_created", "record_id = {$_GET['record_id']}");
$date->readonly();

$jobcard_number_label = new label();
$jobcard_number_label->for("jc_no_label");
$jobcard_number_label->value("JOBCARD NO  : ");
$jobcard_number_label->addAttribute("style", "font-size: 1.5em; width: 40%;");

$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("work_requests", "jc_no", "record_id = {$_GET['record_id']}");
$jobcard_number->readonly();
$jobcard_number->addAttribute("style", "font-size: 1em; width: 100%; margin: 0.5vw auto;");

$contact_number_label = new label();
$contact_number_label->for("contact_number");
$contact_number_label->value("CONTACT NUMBER  : ");
$contact_number_label->addAttribute("style", "font-size: 1.5em; width: 40%;");

$phone = new input();
$phone->class("inputs");
$phone->type("text");
$phone->name("contact_number");
$phone->id("contact_number");
$phone->value_from_db("work_requests", "contact_number", "record_id = {$_GET['record_id']}");
$phone->addAttribute("style", "font-size: 1em; width: 100%; margin: 0.5vw auto;");

$other_number_label = new label();
$other_number_label->for("other_number");
$other_number_label->value("OTHER NUMBER : ");
$other_number_label->addAttribute("style", "font-size: 1.5em; width: 40%;");

$other_number = new input();
$other_number->class("inputs");
$other_number->type("text");
$other_number->name("other_number");
$other_number->id("other_number");
$other_number->value_from_db("work_requests", "other_number", "record_id = {$_GET['record_id']}");
$other_number->addAttribute("style", "font-size: 1em; width: 100%; margin: 0.5vw auto;");

$alternate_number_label = new label();
$alternate_number_label->for("alternate_number");
$alternate_number_label->value("ALTERNATE NUMBER : ");
$alternate_number_label->addAttribute("style", "font-size: 1.5em; width: 40%;");

$alternate_number = new input();
$alternate_number->class("inputs");
$alternate_number->type("text");
$alternate_number->name("alternate_number");
$alternate_number->id("alternate_number");
$alternate_number->value_from_db("work_requests", "alternate_number", "record_id = {$_GET['record_id']}");
$alternate_number->addAttribute("style", "font-size: 1em; width: 100%; margin: 0.5vw auto;");

$type_label = new label();
$type_label->for("type_label");
$type_label->value("TYPE : ");
$type_label->addAttribute("style", "font-size: 1.5em; width: 40%;");

$type = new select();
$type->class("inputs");
$type->name("type");
$type->id("type");
$type->add_option("LEAD", "LEAD");
$type->add_option("JOBCARD", "JOBCARD");
$type->addAttribute("style", "font-size: 1em; width: 100%; margin: 0.5vw auto;");

$area_label = new label();
$area_label->for("area");
$area_label->value("AREA : ");
$area_label->addAttribute("style", "font-size: 1.5em; width: 40%;");

$area = new input();
$area->class("inputs");
$area->type("text");
$area->name("area");
$area->id("area");
$area->value_from_db("work_requests", "address", "record_id = {$_GET['record_id']}");
$area->addAttribute("style", "font-size: 1em; width: 100%; margin: 0.5vw auto;");

$status_label = new label();
$status_label->for("status");
$status_label->value("STATUS : ");
$status_label->addAttribute("style", "font-size: 1.5em; width: 40%;");

$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 TEAM", "ASSIGN TO TEAM");
$status->addAttribute("style", "font-size: 1em; width: 100%; margin: 0.5vw auto;");

$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_label->addAttribute("style", "font-size: 1.5em; width: 80%;");

$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_available()");
$payment->addAttribute("style", "font-size: 1em; width: 100%; margin: 0.5vw auto;");

$payment_type_label = new label();
$payment_type_label->for("payment_type_label");
$payment_type_label->value("PAYMENT TYPE");
$payment_type_label->addAttribute("style", "font-size: 1.5em; width: 40%;");

$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");
$payment_type->addAttribute("style", "font-size: 1em; width: 100%; margin: 0.5vw auto;");

$team_assigned_label = new label();
$team_assigned_label->for("team_assigned_label");
$team_assigned_label->value("TEAM ASSIGNED");
$team_assigned_label->addAttribute("style", "font-size: 1.5em; width: 40%;");

$team_assigned = new select();
$team_assigned->class("inputs");
$team_assigned->name("team_id");
$team_assigned->id("team_id");
$team_assigned->fill_from_db("teams", "record_id", "name", "status = 'ACTIVE'");
$team_assigned->addAttribute("style", "font-size: 1em; width: 100%; margin: 0.5vw auto;");

$additional_notes_label = new label();
$additional_notes_label->for("additional_notes_label");
$additional_notes_label->value("ADDITIONAL NOTES");
$additional_notes_label->addAttribute("style", "font-size: 1.5em;");

$additional_notes = new textarea();
$additional_notes->class("inputs");
$additional_notes->name("additional_notes");
$additional_notes->id("additional_notes");
// $additional_notes->style("width:50%;");
$additional_notes->value_from_db("work_requests", "additional_notes", "record_id = {$_GET['record_id']}");
$additional_notes->addAttribute("style", "font-size: 1em; width: 100%; margin: 0.5vw auto;");
$additional_notes->rows(5);

$submit_btn = new button();
$submit_btn->value("UPDATE");
// $submit_btn->onclick("validateTeam()");

?>

<form action="edit_lead.ajax.php" method="post" onsubmit="return validateTeam()">
    <div class="form_down">
        <h1 style="font-size: 3em; margin-bottom: 0.5vw; margin-top: 1.5vw;">EDIT LEAD</h1>
        <?php
        $user_id->add();
        $record_id->add();

        ?>

        <div
            style="width: 95%; background-color: white; border-radius: 2vw; display: flex; flex-direction: column;padding: 1vw;">
            <div style="display: flex; flex-direction: row; width: 100%;">
                <?php
                $jobcard_number_label->add();
                $jobcard_number->add();
                $date->add();
                ?>
            </div>
            <div style="display: flex; flex-direction: row; width: 100%;">
                <?php
                $contact_number_label->add();
                $phone->add();

                ?>
            </div>
            <div style="display: flex; flex-direction: row; width: 100%;">
                <?php
                $other_number_label->add();
                $other_number->add();

                ?>
            </div>
            <div style="display: flex; flex-direction: row; width: 100%;">
                <?php
                $alternate_number_label->add();
                $alternate_number->add();

                ?>
            </div>
            <div style="display: flex; flex-direction: row; width: 100%;">
                <?php
                $area_label->add();
                $area->add();
                ?>
            </div>
        </div>
        <br><br>

        <div style="padding: 2vw; background-color: navy; width: 90%;">
            <h2 style="color:white;">PAYMENTS</h2>
            <div style="width: 100%; display: flex;flex-direction: row;">
                <div
                    style='display:flex; flex-direction: column; width: 50%; align-items: center; background-color: whitesmoke; padding: 1vw;'>
                    <div style="display: flex; flex-direction: row; width: 100%;">
                        <?php
                        $payment_label->add();
                        $payment->add();
                        ?>
                    </div>
                    <?php

                    $data_res = $db->query("work_requests", "SELECT * FROM work_requests WHERE record_id = {$_GET['record_id']}");
                    $data = $data_res->fetch_assoc();

                    $jobcard_id_data_res = $db->query("jobcards", "SELECT * FROM jobcards WHERE jc_no = {$data['jc_no']}");
                    $jobcard_id = $jobcard_id_data_res->fetch_assoc();
                    ?>

                    <div id="payments_section"
                        style="display:none; flex-direction: column; align-items: center; width: 100%; margin: 2vw;">
                        <div style="display: flex; flex-direction: row; width: 100%;">
                            <label for="payment_type_label" class="labels" style="font-size: 1.5em; width: 80%;">PAYMENT
                                TYPE : </label>
                            <select name="payment_type" id="payment_type" onchange="payment_option()" class="inputs"
                                style="font-size: 1.5em; margin-top: 0.5vw; width: 100%;">
                                <option value=""></option>
                                <option value="CASH">CASH</option>
                                <option value="EFT">EFT</option>
                            </select>
                        </div>

                        <div id="eft_payment"
                            style="display:none; flex-direction: column; align-items: center; width: 100%;">
                            <div style="display: flex; flex-direction: row; width: 100%;">
                                <label for="eft_type" class="labels" style="font-size: 1.5em; width: 80%;">TYPE :
                                </label>
                                <select name="eft_type" id="eft_type" onchange="eft_option()" class="inputs"
                                    style="font-size: 1.5em; margin-top: 0.5vw; width: 100%;">
                                    <option value=""></option>
                                    <option value="FILE">ATTACH FILE</option>
                                    <option value="CAMERA">OPEN CAMERA</option>
                                </select>
                            </div>

                            <div id="file_div" style="display:none; flex-direction: column; align-items: center;">
                                <div style="display: flex; flex-direction: row; width: 100%;">
                                    <label for="payment_proof_label" class="labels"
                                        style="font-size: 1.5em; width: 80%;">POP FILE : </label>
                                    <input type="file" name="payment_proof" id="payment_proof" class="inputs"
                                        onchange="upload_file_ajax()"
                                        style="font-size: 1.5em; margin-top: 0.5vw; width: 100%;">
                                </div>
                            </div>
                            <div id="camera_div" style="display:none; flex-direction: column; align-items: center;">
                                <style>
                                    video,
                                    canvas {
                                        width: 400px;
                                        height: 300px;
                                        border: 3px solid #ccc;
                                        border-radius: 2vw;
                                        margin-top: 10px;
                                    }

                                    @media all and (max-width: 600px) {

                                        video,
                                        canvas {
                                            width: 600px;
                                            height: 450px;
                                            margin-top: -5vw;
                                        }
                                    }
                                </style>

                                <video style="display: none;" id="camera_slip" autoplay playsinline></video>
                                <br>

                                <input type="button" id="open_camera_slip" class="submit_btn" onclick="openSlipCamera()"
                                    value="Open Camera" style="min-width: auto; width: 100%;">

                                <div id="load_camera_slip" style="display: none; width: 100%; justify-content: center;">
                                    <input type="button" class="submit_btn" onclick="captureSlipPhoto()"
                                        value="Capture Photo">
                                    <input type="button" class="submit_btn" onclick="stopSlipCamera()"
                                        value="Stop Camera">
                                </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 $jc_no; ?>";

                                        load_camera.style.display = "none";
                                        canvas.width = video.videoWidth;
                                        canvas.height = video.videoHeight;
                                        context.drawImage(video, 0, 0, canvas.width, canvas.height);

                                        captured_image.style.display = "none";

                                        const imageData = canvas.toDataURL("image/png");

                                        stopSlipCamera();
                                        saveCapturedSlipImage(imageData, jobcard_no);
                                    }

                                    function stopSlipCamera() {
                                        const open_camera = document.getElementById("open_camera_slip");
                                        const load_camera = document.getElementById("load_camera_slip");
                                        const video = document.getElementById("camera_slip");

                                        video.style.display = "none";
                                        load_camera.style.display = "none";
                                        open_camera.style.display = "block";
                                        if (stream_slip) {
                                            stream_slip.getTracks().forEach(track => track.stop());
                                            stream_slip = null;
                                            document.getElementById("camera_slip").srcObject = null;
                                        }
                                    }

                                    function saveCapturedSlipImage(imageData, jobcard_no) {
                                        const video = document.getElementById("camera_slip");
                                        const folder_path = "../jobcards/slips/";
                                        const section_name = "slip";

                                        video.style.display = "none";

                                        var formData = new FormData();

                                        formData.append('image', imageData);
                                        formData.append('jobcard_no', jobcard_no);
                                        formData.append('folder_path', folder_path);
                                        formData.append('section_name', section_name);

                                        const xhr = new XMLHttpRequest();
                                        xhr.open('POST', '../jobcards/save_camera.php', true);
                                        xhr.onreadystatechange = function () {
                                            if (xhr.readyState == 4 && xhr.status == 200) {
                                                if (xhr.responseText != '0') {
                                                    console.log('fileName: ' + xhr.responseText);
                                                    alert('Photo saved successfully!');
                                                    if ('slip' != '') {
                                                        document.getElementById('slip_file').style.display = 'block';
                                                        document.getElementById('slip_file').value = xhr.responseText;
                                                    }
                                                } else {
                                                    alert('Error saving photo!');
                                                }
                                            }
                                        };
                                        xhr.send(formData);
                                    }
                                </script>

                                <input type='text' style="display: none; width: 100%;" class="inputs" id='slip_file'
                                    name='slip_file'>
                            </div>
                        </div>

                        <div id="cash_payment"
                            style="display:none; flex-direction: column; align-items: center; width: 100%;">
                            <div style="display: flex; flex-direction: row; width: 100%;">
                                <label for="payment_amount_label" class="labels"
                                    style="font-size: 1.5em; width: 80%;">AMOUNT : </label>
                                <input type="text" class="inputs" name="payment_amount" id="payment_amount"
                                    style="font-size: 1.5em; margin-top: 0.5vw; width: 100%;">
                            </div>
                            <div class="error-message" id="error" style="display: none;"></div>

                        </div>

                        <input type="button" value="SAVE PAYMENT" class="submit_btn" onclick="save_file_ajax()">
                    </div>

                    <script>

                        function save_file_ajax() {
                            var payment_type = document.getElementById("payment_type").value;
                            var amount = document.getElementById("payment_amount").value;
                            var jobcard_no = "<?php echo $jc_no; ?>";
                            var user_id = "<?php echo $_SESSION['user_id'] ?>";
                            var eft_type = document.getElementById("eft_type").value;

                            var formData = new FormData();

                            if (payment_type === "") {
                                alert("Please select a payment type.");
                                return false;
                            }

                            if (amount.trim() === "" || isNaN(amount) || amount <= 0) {
                                alert("Please enter a valid positive amount.");
                                return false;
                            }

                            // Handle EFT specific validation and file attachment
                            if (payment_type === "EFT") {
                                // FIXED: Changed "CAMARA" to "CAMERA"
                                if (eft_type === "CAMERA") {
                                    var slip_input = document.getElementById("slip_file").value;

                                    // FIXED: Check for empty string, not space
                                    if (slip_input === "" || slip_input.trim() === "") {
                                        alert("Please capture Slip Image");
                                        return false;
                                    }

                                    formData.append('file', slip_input);
                                } else if (eft_type === "FILE") {
                                    // CHANGED: Get the stored filename instead of the file object
                                    var uploaded_filename = document.getElementById("uploaded_file_name");

                                    if (!uploaded_filename || uploaded_filename.value === "") {
                                        alert("Please upload a file first.");
                                        return false;
                                    }

                                    formData.append('file', uploaded_filename.value);
                                } else {
                                    alert("Please select how you want to provide payment proof.");
                                    return false;
                                }
                            }

                            // AJAX Request (simulated for demo)
                            console.log('Sending payment data:', {
                                payment_type: payment_type,
                                amount: amount,
                                jobcard_no: jobcard_no,
                                user_id: user_id,
                                eft_type: eft_type,
                            });

                            // Simulate successful save
                            setTimeout(() => {
                                // alert("Payment saved successfully!");

                                // FIXED: Clear inputs properly
                                document.getElementById("payment_made").value = "";
                                document.getElementById("payment_type").value = "";
                                document.getElementById("payment_amount").value = "";
                                document.getElementById("eft_type").value = "";
                                document.getElementById("slip_file").value = "";
                                document.getElementById("payment_proof").value = "";

                                // Reset file input
                                var fileInput = document.getElementById("payment_proof");
                                if (fileInput) fileInput.value = "";

                                // Hide sections
                                document.getElementById("cash_payment").style.display = "none";
                                document.getElementById("eft_payment").style.display = "none";
                                document.getElementById("file_div").style.display = "none";
                                document.getElementById("camera_div").style.display = "none";
                                document.getElementById("payments_section").style.display = "none";

                            }, 500);

                            formData.append('payment_type', payment_type);
                            formData.append('jobcard_no', jobcard_no);
                            formData.append('record_id', jobcard_no)
                            formData.append('amount', amount);
                            formData.append('user_id', user_id);
                            formData.append('create', "create");

                            var xhr = new XMLHttpRequest();
                            xhr.onreadystatechange = function () {

                                if (xhr.readyState === 4) {
                                    if (xhr.status === 200 && xhr.responseText.includes("OK")) {
                                        console.log(`PAYMENYT SUCCESS: ${xhr.responseText}`);
                                        alert("Payment Saved successfully!");

                                        // Clear all inputs
                                        document.getElementById("payment_type").value = "";
                                        document.getElementById("payment_amount").value = "";
                                        document.getElementById("eft_type").value = "";
                                        document.getElementById("slip_file").value = "";

                                        var fileInput = document.getElementById("payment_proof");
                                        if (fileInput) fileInput.value = "";

                                        //update payment history
                                        loadPaymentHistory();

                                        // Hide sections
                                        payment_option();


                                    } else {
                                        console.log(`Error saving PAYMENT: ${xhr.responseText}`);
                                        // alert('Error completing payment! ,try again.');
                                        return false;
                                    }
                                }
                            };
                            xhr.open("POST", "../jobcards/jobcard_payments.ajax.php", true);
                            xhr.send(formData);
                        }

                        function payment_option() {
                            var select = document.getElementById("payment_type");
                            var cash_payment = document.getElementById("cash_payment");
                            var eft_payment = document.getElementById("eft_payment");

                            if (select.value === "EFT") {
                                cash_payment.style.display = "flex";
                                eft_payment.style.display = "flex";
                            } else if (select.value === "CASH") {
                                cash_payment.style.display = "flex";
                                eft_payment.style.display = "none";
                            } else {
                                cash_payment.style.display = "none";
                                eft_payment.style.display = "none";
                            }
                        }

                        function eft_option() {
                            var select = document.getElementById("eft_type");
                            var file_div = document.getElementById("file_div");
                            var camera_div = document.getElementById("camera_div");

                            if (select.value === "FILE") {
                                file_div.style.display = "flex";
                                camera_div.style.display = "none";
                            } else if (select.value === "CAMERA") {
                                file_div.style.display = "none";
                                camera_div.style.display = "flex";
                            } else {
                                file_div.style.display = "none";
                                camera_div.style.display = "none";
                            }
                        }

                        function payment_available() {
                            var payment_made = document.getElementById("payment_made");
                            if (payment_made.value == "YES") {
                                document.getElementById("payments_section").style.display = "flex";
                            } else if (payment_made.value == "NO") {
                                document.getElementById("payments_section").style.display = "none";
                            } else {
                                document.getElementById("payments_section").style.display = "none";
                            }
                        }

                        function upload_file_ajax() {
                            var payment_proof = document.getElementById("payment_proof");
                            var file = payment_proof.files[0];
                            var jobcard_no = "<?php echo $jc_no; ?>";

                            if (file) {
                                var formData = new FormData();
                                formData.append('file', file);
                                formData.append('jobcard_no', jobcard_no);
                                formData.append('ajax_type', "lead_payment_slip");
                                formData.append('section_name', "slip");
                                formData.append('file_save_path', "../jobcards/slips/");

                                var xhr = new XMLHttpRequest();
                                xhr.onreadystatechange = function () {
                                    if (xhr.readyState === 4) {
                                        if (xhr.status === 200 && xhr.responseText.includes("OK")) {
                                            console.log(`File uploaded successfully: ${xhr.responseText}`);

                                            var response = xhr.responseText;
                                            var filename = response.replace('OK | ', '').trim(); // Adjust based on your response format

                                            // Store filename in hidden input (create this if it doesn't exist)
                                            var uploadedFileInput = document.getElementById('uploaded_file_name');
                                            if (!uploadedFileInput) {
                                                uploadedFileInput = document.createElement('input');
                                                uploadedFileInput.type = 'hidden';
                                                uploadedFileInput.id = 'uploaded_file_name';
                                                uploadedFileInput.name = 'uploaded_file_name';
                                                document.getElementById('file_div').appendChild(uploadedFileInput);
                                            }
                                            uploadedFileInput.value = filename;

                                            alert("File uploaded successfully!");
                                        } else {
                                            console.log(`Error uploading file: ${xhr.responseText}`);
                                            alert('Error uploading file! ,try again.');
                                        }
                                    }
                                };
                                xhr.open("POST", "../jobcards/upload.php", true);
                                xhr.send(formData);
                            }
                        }

                        function loadPaymentHistory() {
                            var jobcard_no = "<?php echo $jc_no; ?>";

                            var xhr = new XMLHttpRequest();
                            xhr.onreadystatechange = function () {
                                if (xhr.readyState === 4 && xhr.status === 200) {
                                    document.getElementById("payment_history_table").innerHTML = xhr.responseText;
                                }
                            };

                            xhr.open("POST", "../jobcards/payment_history.ajax.php", true);
                            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                            xhr.send("jobcard_no=" + encodeURIComponent(jobcard_no));
                        }

                        // Load history on page load
                        document.addEventListener("DOMContentLoaded", loadPaymentHistory);

                        loadPaymentHistory();

                    </script>
                </div>
                <div id="payment_history_table"
                    style="display: flex; flex-direction: column;width: 50%;justify-content: center; padding: 1vw; background-color: whitesmoke;">
                </div>
            </div>
        </div>

        <br><br>
        <div
            style="width: 95%; background-color: white; border-radius: 2vw; display: flex; flex-direction: column;padding: 1vw;">
            <div style="display: flex; flex-direction: row; width: 100%;">
                <?php
                $type_label->add();

                $request_data = $db->query("work_requests", "SELECT * FROM work_requests WHERE record_id = {$_GET['record_id']}");

                // echo "SELECT * FROM work_requests WHERE record_id = {$_GET['record_id']}";
                
                $requests = $request_data->fetch_assoc();
                ?>
                <select name="type" id="type" class="inputs" onchange="jobcard_type()"
                    style="font-size: 1em; width: 100%;  margin: 0.5vw auto;">
                    <option value=""></option>
                    <option value="LEAD" <?php if ($requests['type'] == "LEAD")
                        echo "selected"; ?>>LEAD</option>
                    <option value="JOBCARD" <?php if ($requests['type'] == "JOBCARD")
                        echo "selected"; ?>>JOBCARD</option>
                </select>
            </div>

            <div style="display: flex; flex-direction: row; width: 100%;">
                <?php
                $status_label->add();
                ?>

                <select name="status" id="status" class="inputs" onchange="assign_team()"
                    style="font-size: 1em; width: 100%;  margin: 0.5vw auto;">
                    <option value=""></option>
                    <option value="WAITING FOR DEPOSIT" <?php if ($requests['status'] == "WAITING FOR DEPOSIT")
                        echo "selected"; ?>>
                        WAITING FOR DEPOSIT</option>
                    <option value="FOLLOW UP" <?php if ($requests['status'] == "FOLLOW UP")
                        echo "selected"; ?>>FOLLOW UP
                    </option>
                    <option value="QUOTE SENT" <?php if ($requests['status'] == "QUOTE SENT")
                        echo "selected"; ?>>QUOTE
                        SENT
                    </option>
                    <option value="WAITNG FOR CONFIRMATION" <?php if ($requests['status'] == "WAITNG FOR CONFIRMATION")
                        echo "selected"; ?>>WAITNG FOR CONFIRMATION</option>

                    <div id="jobcard_section" style="display:none;">
                        <option value="ASSIGN TEAM" <?php if ($requests['status'] == "ASSIGN TEAM")
                            echo "selected"; ?>>ASSIGN
                            TO
                            TEAM
                        </option>
                    </div>
                </select>

                <script>
                    document.getElementById("status").value = '<?php echo $requests['status']; ?>';
                </script>
            </div>

            <div id="teams" style="flex-direction: column;">
                <div style="display: flex; flex-direction: row; width: 100%;">
                    <label for="team_assigned_label" class="labels" style="font-size: 1.5em; width: 40%;">TEAM ASSIGNED
                        : </label>
                    <select name="team_id" id="team_id" class="inputs"
                        style="font-size: 1em; width: 100%;  margin: 0.5vw auto;">
                        <option value=""></option>
                        <option value="1" <?php if ($requests['team_id'] == "1")
                            echo "selected"; ?>>B2</option>
                        <option value="2" <?php if ($requests['team_id'] == "2")
                            echo "selected"; ?>>B5</option>
                        <option value="3" <?php if ($requests['team_id'] == "3")
                            echo "selected"; ?>>EWG</option>
                        <option value="4" <?php if ($requests['team_id'] == "4")
                            echo "selected"; ?>>B14</option>
                        <option value="5" <?php if ($requests['team_id'] == "5")
                            echo "selected"; ?>>OFFICE</option>
                    </select></style>
                </div>
            </div>
        </div>
        <br><br>

        <div
            style="width: 95%; background-color: white; border-radius: 2vw; display: flex; flex-direction: column;padding: 1vw; align-items: center;">
            <?php
            $additional_notes_label->add();
            $additional_notes->add();

            $submit_btn->add();
            ?>
        </div>


        <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

            $work_lead_res = $db->query("work_requests", "SELECT * FROM work_requests WHERE record_id = {$_GET['record_id']}");
            // echo "SELECT * FROM work_requests WHERE record_id = {$_GET['record_id']}";
            
            if ($work_lead_res->num_rows > 0) {

                $work_leads = $work_lead_res->fetch_assoc();

                $res_data = $db->query("jobcard_timeline", "SELECT * FROM jobcard_timeline WHERE jobcard_id = {$work_leads['jc_no']}  ORDER BY record_id ASC");
                // echo "SELECT * FROM jobcard_timeline WHERE jobcard_id = {$work_leads['jc_no']}  ORDER BY record_id ASC";
            
                if ($res_data->num_rows > 0) {

                    $work_lead_res = $db->query("jobcards", "SELECT * FROM jobcards WHERE record_id = {$data['jc_no']}");
                    $jobcard = $work_lead_res->fetch_assoc();

                    // echo $jobcard['record_id'];
            
                    ?>

                    <h1>JOBCARD SUMMARY</h1>

                    <table
                        style='border-radius: 2vw;padding-top: 2vw;padding-bottom: 2vw;width:80%; 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:80%; 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']; ?>
                            </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:90%; text-align:center; border: 2px solid black;background-color: #ffffffc4;'>
                    <tr>
                        <th>TYPE</th>
                        <th>METERS</th>
                        <th>DATE</th>
                    </tr>
                    <tr>
                        <td colspan="3" style="text-align: center;"> DATA NOT FOUND </td>
                    </tr>
                </table>
                <br>
                <?php
                }
            } else {
                ?>
            <h1>Job Card Summary</h1>
            <table
                style='border-radius: 2vw;padding-top: 2vw;padding-bottom: 2vw;width:90%; text-align:center; border: 2px solid black;background-color: #ffffffc4;'>
                <tr>
                    <th>TYPE</th>
                    <th>METERS</th>
                    <th>DATE</th>
                </tr>
                <tr>
                    <td colspan="3" style="text-align: center;"> DATA NOT FOUND </td>
                </tr>
            </table>
            <br>
            <?php
            }
            ?>
    </div>
</form>

<script>
    // Initialize on page load
    assign_team();

    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 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 jobcard_type() {
        var type_value = document.getElementById("type").value;

        if (type_value == "JOBCARD") {
            document.getElementById("jobcard_section").style.display = "block";
        } else {
            document.getElementById("jobcard_section").style.display = "none";
        }
    }

    function validateTeam() {
        var status = document.getElementById("status").value;
        const teamId = document.getElementById("team_id").value;

        if (status !== "ASSIGN TEAM") {
            return true;
        } else {
            if (teamId === "" || teamId === "0") {
                alert("Please select a team before updating.");
                return false;
            }
        }

        return true;
    }

</script>