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

//get the current date and time
$current_date_time = date("Y-m-d H:i", strtotime("+2 hours"));

//get the seeion user id
$user_id = $_SESSION['user_id'];

$jobcards = $db->query("jobcards", "SELECT * FROM jobcards WHERE jc_no = {$_GET['jc_no']}");

$record_id = new input();
$record_id->name("record_id");
$record_id->id("record_id");
$record_id->type("hidden");

$action_date = new input();
$action_date->class("inputs");
$action_date->type("datetime-local");
$action_date->name("action_date");
$action_date->id("action_date");
$action_date->addAttribute("style", "font-size: 1em; width: 80%; margin: 0.5vw auto;");

$action_date_label = new label();
$action_date_label->for("action_date");
$action_date_label->value("ACTION DATE : ");
$action_date_label->addAttribute("style", "font-size: 1.5em; width: 40%;");

$contact_name = new input();
$contact_name->class("inputs");
$contact_name->type("text");
$contact_name->name("contact_name");
$contact_name->id("contact_name");
$contact_name->addAttribute("style", "font-size: 1em; width: 80%; margin: 0.5vw auto;");

$address = new input();
$address->class("inputs");
$address->type("text");
$address->name("address");
$address->id("address");
$address->addAttribute("style", "font-size: 1em; width: 80%; margin: 0.5vw auto;");

$drill_co_ordinates = new input();
$drill_co_ordinates->class("inputs");
$drill_co_ordinates->type("text");
$drill_co_ordinates->name("drill_co_ordinates");
$drill_co_ordinates->id("drill_co_ordinates");
$drill_co_ordinates->addAttribute("style", "font-size: 1em; width: 80%; margin: 0.5vw auto;");

$phone = new input();
$phone->class("inputs");
$phone->type("text");
$phone->name("contact_number");
$phone->id("contact_number");
$phone->addAttribute("style", "font-size: 1em; width: 80%; margin: 0.5vw auto;");

$other_number = new input();
$other_number->class("inputs");
$other_number->type("text");
$other_number->name("other_number");
$other_number->id("other_number");
$other_number->addAttribute("style", "font-size: 1em; width: 80%; 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%;");

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

$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->addAttribute("style", "font-size: 1em; width: 80%; margin: 0.5vw auto;");

$client_name = new input();
$client_name->class("inputs");
$client_name->name("client_name");
$client_name->id("client_name");
$client_name->addAttribute("style", "font-size: 1em; width: 80%; margin: 0.5vw auto;");

$contact_name_label = new label();
$contact_name_label->for("contact_name_label");
$contact_name_label->value("CONTACT NAME : ");
$contact_name_label->addAttribute("style", "font-size: 1.5em; width: 40%;");

$date_time_closed = new input();
$date_time_closed->class("inputs");
$date_time_closed->style("display: none;");
$date_time_closed->name("date_time_closed");
$date_time_closed->value(0);
$date_time_closed->id("date_time_closed");

$jobcard_number_label = new label();
$jobcard_number_label->for("jc_no");
$jobcard_number_label->value("JOBCARD NUMBER : ");
$jobcard_number_label->addAttribute("style", "font-size: 1.5em; width: 40%;");

$jobcard_number = new input();
$jobcard_number->class("inputs");
$jobcard_number->type("text");
$jobcard_number->readonly();
$jobcard_number->name("jc_no");
$jobcard_number->id("jc_no");
$jobcard_number->addAttribute("style", "font-size: 1em; width: 80%; margin: 0.5vw auto;");

$username = $db->query("users", "SELECT * FROM users WHERE record_id = {$_SESSION['user_id']}")->fetch_assoc();

$user_assigned = new input();
$user_assigned->class("inputs");
$user_assigned->name("user_assigned");
// $user_assigned->required();
$user_assigned->id("user_assigned");
$user_assigned->value($username['username']);
$user_assigned->readonly();
$user_assigned->addAttribute("style", "font-size: 1em; width: 100%; margin: 0.5vw auto;");

$user_assigned_label = new label();
$user_assigned_label->for("user_assigned");
$user_assigned_label->value("USER ASSIGNED : ");
$user_assigned_label->addAttribute("style", "font-size: 1.5em; width: 40%;");

$team_assigned = new select();
$team_assigned->class("inputs");
$team_assigned->name("team_assigned_id");
// $team_assigned->required();
$team_assigned->id("team_assigned_id");
$team_assigned->fill_from_db("teams", "record_id", "name");

$team_assigned_label = new label();
$team_assigned_label->for("team_assigned");
$team_assigned_label->value("TEAM ASSIGNED : ");
$team_assigned_label->addAttribute("style", "font-size: 1.5em; width: 40%;");

$client_name_label = new label();
$client_name_label->for("client_name");
$client_name_label->value("CLIENT NAME : ");
$client_name_label->addAttribute("style", "font-size: 1.5em; width: 40%;");

$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: 1.5em; width: 100%; margin: 0.5vw auto;");

$payment_label = new label();
$payment_label->for("payment_label");
$payment_label->value("PAYMENT MADE : ");
$payment_label->addAttribute("style", "font-size: 1.5em; width: 80%;");

$submit_btn = new button();
$submit_btn->value("UPDATE");
// $submit_btn->onclick("update_jobcard()");

if ($jobcards->num_rows > 0) {
    $jobcard = $jobcards->fetch_assoc();

    $record_id->value($jobcard['record_id']);
    $action_date->value_from_db("jobcards", "action_date", "jc_no = {$_GET['jc_no']}");
    $contact_name->value_from_db("jobcards", "contact_name", "jc_no = {$_GET['jc_no']}");
    $address->value_from_db("jobcards", "address", "jc_no = {$_GET['jc_no']}");
    $drill_co_ordinates->value_from_db("jobcards", "drill_co_ordinates", "jc_no = {$_GET['jc_no']}");
    $phone->value_from_db("jobcards", "contact_number", "jc_no = {$_GET['jc_no']}");
    $other_number->value_from_db("jobcards", "other_number", "jc_no = {$_GET['jc_no']}");
    $alternate_number->value_from_db("jobcards", "alternate_number", "jc_no = {$_GET['jc_no']}");
    $client_name->value_from_db("jobcards", "client_name", "jc_no = {$_GET['jc_no']}");
    $jobcard_number->value_from_db("jobcards", "jc_no", "jc_no = {$_GET['jc_no']}");

    // $ajax = new js_ajax();
    // $ajax->function_name("update_jobcard");
    // $ajax->submit_btn_id("submit");
    // $ajax->update("jobcards");
    // $ajax->on_success("JOBCARD UPDATED SUCCESSFULLY");
    // $ajax->exclude_inputs("open_camera_slip");
    // $ajax->redirect("../jobcards/lead_home.php");

} else {
    $work_jobcards = $db->query("work_requests", "SELECT * FROM work_requests WHERE jc_no = {$_GET['jc_no']}");
    $jobcard = $work_jobcards->fetch_assoc();

    $record_id->value($jobcard['record_id']);
    $address->value_from_db("work_requests", "address", "jc_no = {$_GET['jc_no']}");
    $phone->value_from_db("work_requests", "contact_number", "jc_no = {$_GET['jc_no']}");
    $other_number->value_from_db("work_requests", "other_number", "jc_no = {$_GET['jc_no']}");
    $alternate_number->value_from_db("work_requests", "alternate_number", "jc_no = {$_GET['jc_no']}");
    $jobcard_number->value_from_db("work_requests", "jc_no", "jc_no = {$_GET['jc_no']}");

    // $ajax = new js_ajax();
    // $ajax->function_name("update_jobcard");
    // $ajax->submit_btn_id("submit");
    // $ajax->update("jobcards");
    // $ajax->on_success("JOBCARD UPDATED SUCCESSFULLY");
    // $ajax->exclude_inputs("open_camera_slip");
    // $ajax->redirect("../jobcards/lead_home.php");
}

?>

<form action="edit_jobcard.ajax.php" method="post">
<div class="form_down">
<h1 style="font-size: 3em; margin-bottom: 0.5vw; margin-top: 1.5vw;">EDIT JOBCARD</h1>

<script>
function add_number() {
    //create a input with a placeholder called other
    var other = document.createElement("input");
    other.type = "text";
    other.name = "other";
    other.id = "other";
    // other.required = true;
    document.getElementById("other_div").appendChild(other);
}
</script>

<?php
$record_id->add();
?>
<div
style="width: 90%; 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();
?>
</div>
<div style="display: flex; flex-direction: row; width: 100%;">
<?php
$action_date_label->add();
$action_date->add();
?>
</div>
<div style="display: flex; flex-direction: row; width: 100%;">
<?php
$client_name_label->add();
$client_name->add();
?>
</div>
<div style="display: flex; flex-direction: row; width: 100%;">
<?php
$contact_name_label->add();
$contact_name->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%;">
<label for="address_label" class="labels" style="font-size:1.5em; width: 40%;">ADDRESS : </label>
<?php
$address->add();
?>
</div>
<div style="display: flex; flex-direction: row; width: 100%;">
<label for="drill_co_ordinates_label" class="labels" style="font-size:1.5em; width: 40%;">DRILL CO-ORDINATES : </label>
<?php
$drill_co_ordinates->add();
?>
</div>
<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_assigned_id" id="team_assigned_id" class="inputs"
    style="font-size: 1em; width: 80%;  margin: 0.5vw auto;">
    <option value=""></option>
    <option value="1">B2</option>
    <option value="2">B5</option>
    <option value="3">EWG</option>
    <option value="4">B14</option>
    <option value="5">OFFICE</option>
    </select>
    <script>
    document.getElementById("team_assigned_id").value = '<?php echo $jobcard['team_assigned_id']; ?>';
    </script>
    <input type="text" hidden name="" id="" value="<?php echo $username['record_id']; ?>">
</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
$jobcard_id_data_res = $db->query("jobcards", "SELECT * FROM jobcards WHERE jc_no = {$_GET['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 $_GET['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%;" onchange="check_amount();">
</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 $_GET['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 $_GET['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: ${xhr.responseText}`);
                    // alert('Error uploading file! ,try again.');
                }
            }
        };
        xhr.open("POST", "../jobcards/upload_slip.php", true);
        xhr.send(formData);
    }
}

function check_amount() {
    var payment_amount = document.getElementById("payment_amount");

    //if the payment amount contains a letter, remove it
    if (isNaN(payment_amount.value)) {
        alert("NO LETTERS ALLOWED, TRY AGAIN");
    }
}

function loadPaymentHistory() {
    var jobcard_no = "<?php echo $_GET['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>
<?php
$submit_btn->add();
?>
</form>


<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: 90%;">
    <?php
        $jobcard_data_res = $db->query("jobcards", "SELECT * FROM jobcards WHERE jc_no = {$_GET['jc_no']}");
        // echo "SELECT * FROM jobcards WHERE jc_no = {$_GET['jc_no']}";

        if ($jobcard_data_res->num_rows > 0) {
            $jobcard_data = $jobcard_data_res->fetch_assoc();

            // echo "SELECT * FROM jobcards WHERE record_id = {$jobcard_data['record_id']}";

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

                <h1>JOBCARD SUMMARY</h1>

                <div id="timeline_summary_table" style="width: 90%; display:flex; flex-direction: column; align-items: center;"></div><br><br>

                <input type="button" onclick="add_timeline()" class="submit_btn" id="progress_btn" value="ADD PROGRESS" />

                <div id="add_timline" style="display: none; flex-direction: column; align-items: center; width: 90%; border: 3px solid black; margin-bottom: 3vw;">
                    <h2>UPDATE TIMELINE</h2>
                    <div style="display: flex; flex-direction: row; width: 100%; justify-content: space-around;">
                        <div style="display: flex; flex-direction: column; width: 30%;">
                            <input type="text" id="user_id" name="user_id" hidden value="<?php echo $_SESSION['user_id'] ?>" />
                            <input type="text" id="jobcard_no" name="jobcard_no" hidden value="<?php echo $jobcard_data['record_id'] ?>" />
                            <label for="type_label" class="labels">PROCESS TYPE</label>
                            <select id="type" name="type" style="width: 100%;" class="inputs">
                                <option>SELECT OPTION</option>
                                <option value="RIEMING_STOP">RIEMING</option>
                                <option value="DRILLING_STOP">DRILLING</option>
                                <option value="CASING_STOP">CASING</option>
                                <option value="BLASTING_STOP">BLASTING</option>
                            </select>
                        </div>
                        <div style="display: flex; flex-direction: column; width: 30%;">
                            <label for="meters_label" class="labels">METERS</label>
                            <input type="number" id="meters" name="meters" style="width: 100%;" class="inputs" />
                            </div>
                            <div style="display: flex; flex-direction: column; width: 30%;">
                            <label for="serial_number_label" class="labels">SERIAL NUMBER</label>
                            <input type="text" id="serial_number" name="serial_number" style="width: 100%;" class="inputs" />
                        </div>
                    </div>
                    <button type="button" onclick="submit_timeline()" class="submit_btn">SUBMIT</button>
                </div>

                <script>

                    function add_timeline(){
                        document.getElementById("add_timline").style.display = "flex";
                        document.getElementById("progress_btn").style.display = "none";
                    }

                    function loadTimeline() {
                        var jc_no = "<?php echo $_GET['jc_no']; ?>";

                        var xhr = new XMLHttpRequest();
                        xhr.onreadystatechange = function () {
                            if (xhr.readyState === 4 && xhr.status === 200) {
                                document.getElementById("timeline_summary_table").innerHTML = xhr.responseText;
                            }
                        };
                        xhr.open("POST", "../jobcards/timeline_summary.ajax.php", true);
                        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                        xhr.send("jc_no=" + encodeURIComponent(jc_no));
                    }

                    // Load on page ready
                    document.addEventListener("DOMContentLoaded", loadTimeline);

                    function submit_timeline() {
                        const user_id      = document.getElementById("user_id").value;
                        const jobcard_no   = document.getElementById("jobcard_no").value;
                        const type         = document.getElementById("type").value;
                        const meters       = document.getElementById("meters").value;
                        const serial_number = document.getElementById("serial_number").value;

                        const form = new FormData();
                        form.append("user_id", user_id);
                        form.append("jobcard_no", jobcard_no);
                        form.append("type", type);
                        form.append("meters", meters);
                        form.append("serial_number", serial_number);

                        const xhr = new XMLHttpRequest();
                        xhr.open('POST', '../jobcards/add_timeline.ajax.php', true);
                        xhr.onreadystatechange = function () {
                            if (xhr.readyState === 4) {
                                console.log(xhr.responseText);
                                if (xhr.status === 200 && xhr.responseText.trim() === "success") {
                                    document.getElementById("add_timline").style.display = "none";
                                    document.getElementById("progress_btn").style.display = "block";
                                    loadTimeline(); // 👈 refresh both tables
                                } else {
                                    console.log(xhr.responseText);
                                    alert('Error');
                                }
                            }
                        };
                        xhr.send(form);
                    }

                </script>

                <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:90%; 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>
                <br><br>
                </div>

                <div
                style="display: flex; flex-direction: column; align-items: center; background-color: white; margin: 4vw; border-radius: 2vw; padding: 2vw; width: 90%;">

                <script src="https://cdn.jsdelivr.net/npm/signature_pad@2.3.2/dist/signature_pad.min.js"></script>
                <?php

                $user_data_res = $db->query("jobcard_timeline", "SELECT * FROM jobcard_timeline WHERE jobcard_id = {$jobcard_data['record_id']}");
                $user_res = $user_data_res->fetch_assoc();
                
                // EMPLOYEE SIGNATURE
                $employee_files = glob("employee-jc{$jobcard['jc_no']}-*-signature.png");
                // echo "employee-jc{$jobcard['jc_no']}-{$user_res['user_id']}-signature.png <br>";

                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("client-jc{$jobcard['jc_no']}-*-signature.png");
                // echo "signatures/client-jc{$jobcard['jc_no']}-{$user_res['user_id']}-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>

                <br>
                <?php
            }

        } else {
            $work_request_res = $db->query("work_requests", "SELECT * FROM work_requests WHERE jc_no = {$jobcard['jc_no']}");
            $work_request = $work_request_res->fetch_assoc();

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

            <br>
            <?php
        }
    ?>
</div>