<?php include "../../root.class.php";
$html = new html();
$html->add_styles_page();
// $html->check_user_type("ADMIN");
$db = new db_safeguard();

$current_date_time = date("Y-m-d H:i", strtotime("+2 hours"));

$user_id = $_SESSION['user_id'];

$install_jobcards_res = $db->query("pump_installation", "SELECT * FROM pump_installation WHERE record_id = {$_GET['record_id']}");

if ($install_jobcards_res->num_rows < 0) {
  echo "PUMP INSTALL JOBCARD NOT FOUND";
  exit;
}

$install_jobcards = $install_jobcards_res->fetch_assoc();

?>

<style>
  .div_signatures {
      position: relative;
      display: flex;
      flex-direction: column;
      width: 100%;
      justify-content: space-around;
      width: fit-content;
      margin-top: 0vh;
      margin-bottom: 0vh;
  }

  @media (min-width: 1050px) {

  }

  @media (min-width: 651px) and (max-width: 1050px) {

  }
</style>

<form action="edit_install.ajax.php" method="post">
  <div class="form_down">
    <div style="width: 90%; background-color: white; border-radius: 2vw; display: flex; flex-direction: column;padding: 1vw; margin: 1vw;">
      <input type="text" id="record_id" name="record_id" hidden />
      <h1 style="font-size: 3em; margin-bottom: 0.5vw; margin-top: 1.5vw;">EDIT PUMP INSTALL</h1>

      <div style="display: flex; flex-direction: row; width: 100%;">
        <label for="jobcard_no_label" style="font-size: 1.5em; width: 40%;" class="label">JOBCARD NO</label>
        <input type="text" id="jobcard_no" name="jobcard_no" style="font-size: 1em; width: 80%; margin: 0.5em;" class="inputs" />
      </div>

      <div style="display: flex; flex-direction: row; width: 100%;">
        <label for="drilling_invoice_label" style="font-size: 1.5em; width: 40%;" class="label">DRILLING INVOICE</label>
        <input type="text" id="drilling_invoice" name="drilling_invoice" style="font-size: 1em; width: 80%; margin: 0.5em;" class="inputs" />
      </div>

      <div style="display: flex; flex-direction: row; width: 100%;">
        <label for="pump_slip_label" style="font-size: 1.5em; width: 40%;" class="label">PUMP SLIP</label>
        <input type="text" id="pump_slip" name="pump_slip" style="font-size: 1em; width: 80%; margin: 0.5vw;" class="inputs" />
      </div>

      <div style="display: flex; flex-direction: row; width: 100%;">
        <label for="install_team_label" style="font-size: 1.5em; width: 40%;" class="label">INSTALL TEAM</label>
        <input type="text" id="install_team_id" name="install_team_id" style="font-size: 1em; margin: 0.5vw; width: 80%;" class="inputs" />
      </div>

      <div style="display: flex; flex-direction: row; width: 100%;">
        <label for="_label" style="font-size: 1.5em; width: 40%;" class="label"></label>
        <input type="text" id="" name="" style="font-size: 1em; margin: 0.5vw; width: 80%;" class="inputs" />
      </div>

      <div style="display: flex; flex-direction: row; width: 100%;">
        <label for="_label" style="font-size: 1.5em; width: 40%;" class="label"></label>
        <input type="text" id="" name="" style="font-size: 1em; margin: 0.5vw; width: 80%;" class="inputs" />
      </div>

      <div style="display: flex; flex-direction: row; width: 100%;">
        <label for="_label" style="font-size: 1.5em; width: 40%;" class="label"></label>
        <input type="text" id="" name="" style="font-size: 1em; margin: 0.5vw; width: 80%;" class="inputs" />
      </div>
    </div>
    
    <div style="background-color: rgb(255 255 255 / 87%); width: 90%; border-radius: 2vw; padding: 1vw; margin: 1vw;">
      <h1 class="heading_h1">PAYMENTS</h1><br>
      <div style="padding: 2vw; background-color: navy; width: 95%;">
                <div style="width: 98%; display: flex; flex-direction: column;">
                  <div id="payment_history_table" style="display: flex; flex-direction: column;width: 98%;justify-content: center; padding: 1vw; background-color: whitesmoke;">
                  </div>

                  <div id="payments" style='display:flex; flex-direction: column; width: 100%; align-items: center; background-color: whitesmoke; padding: 1vw;'>
                    <label for="payment" class="big_labels">PAYMENT TYPE</label>
                    <select id="payment_method" name="payment_method" class="big_inputs" onchange="payment_type()" style="width: 90%;">
                      <option>Payment Method</option>
                      <option value="CASH">CASH</option>
                      <option value="EFT">EFT</option>
                    </select>

                  <div id='eft' style='display: none; flex-direction: column; align-items: center;'>
                    <label for="eft_type" class="big_labels">TYPE</label>
                    <!-- Add this as a new option in your EFT type dropdown -->

                    <select name="eft_type" id="eft_type" onchange="eft_option()" class="big_inputs" style="width: 90%;">
                        <option value=""></option>
                        <option value="FILE">ATTACH FILE</option>
                        <option value="CAMERA">OPEN CAMERA</option>
                    </select>

                    <div id="file_div" style="display:none; flex-direction: column; align-items: center;">
                        <label for="proof" class="big_labels">Insert Payment Proof</label>
                        <input type="file" name="payment_proof" id="payment_proof" style="width: 90%;"
                            class="big_inputs" onchange="upload_file_ajax()">
                        <span id="upload_status" style="font-size:13px; margin-top:5px; color:gray;"></span>
                        <!-- FIXED: Static hidden input — no longer created dynamically -->
                        <input type="hidden" id="uploaded_file_name" name="uploaded_file_name" value="">
                    </div>

                    <div id="camera_div" style="display:none; flex-direction: column; align-items: center;">
                        <style>
                            video,
                            canvas {
                                width: 400px;
                                height: 300px;
                                border: 3px solid #ccc;
                                border-radius: 2vw;
                                margin-top: 10px;
                            }

                            @media all and (max-width: 600px) {

                                video,
                                canvas {
                                    width: 600px;
                                    height: 450px;
                                    margin-top: -5vw;
                                }
                            }
                        </style>

                        <video style="display: none;" id="camera_slip" autoplay playsinline></video>
                        <br>

                        <button id="open_camera_slip" class="submit_btn" onclick="openSlipCamera()">Open
                        Camera</button>

                        <div id="load_camera_slip" style="display: none; width: 100%; justify-content: center;">
                            <button class="submit_btn" onclick="captureSlipPhoto()">Capture Photo</button>
                            <button class="submit_btn" onclick="stopSlipCamera()">Stop Camera</button>
                        </div>

                        <div id="captured_image_slip" style="display:none">
                            <h3>Captured Image:</h3>
                            <canvas id="snapshot_slip"></canvas>
                        </div>

                        <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['jobcard_no']; ?>";

                                load_camera.style.display = "none";
                                canvas.width = video.videoWidth;
                                canvas.height = video.videoHeight;
                                context.drawImage(video, 0, 0, canvas.width, canvas.height);

                                captured_image.style.display = "none";

                                const imageData = canvas.toDataURL("image/png");

                                stopSlipCamera();
                                saveCapturedSlipImage(imageData, jobcard_no);
                            }

                            function stopSlipCamera() {
                                const open_camera = document.getElementById("open_camera_slip");
                                const load_camera = document.getElementById("load_camera_slip");
                                const video = document.getElementById("camera_slip");

                                video.style.display = "none";
                                load_camera.style.display = "none";
                                open_camera.style.display = "block";
                                if (stream_slip) {
                                    stream_slip.getTracks().forEach(track => track.stop());
                                    stream_slip = null;
                                    document.getElementById("camera_slip").srcObject = null;
                                }
                            }

                            function saveCapturedSlipImage(imageData, jobcard_no) {
                                const video = document.getElementById("camera_slip");
                                const folder_path = "../pump/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', '../pump/save_camera.php', true);
                                xhr.onreadystatechange = function () {
                                    if (xhr.readyState == 4 && xhr.status == 200) {
                                        if (xhr.responseText != '0') {
                                            console.log('fileName: ' + xhr.responseText);
                                            alert('Photo saved successfully!');
                                            if ('slip' != '') {
                                                document.getElementById('slip_file').style.display = 'block';
                                                document.getElementById('slip_file').value = xhr.responseText;
                                            }
                                        } else {
                                            alert('Error saving photo!');
                                        }
                                    }
                                };
                                xhr.send(formData);
                            }
                        </script>

                        <input type='text' style="display: none; width: 90%;" class="inputs" id='slip_file'
                        name='slip_file'>
                  </div>
                </div>

                <div id='cash' style='display: none; flex-direction: column; align-items: center;'>
                <label for="amount" class="big_labels">Amount</label>
                <input type="text" class="big_inputs" name="cash_amount" id="cash_amount" placeholder="AMOUNT" style="width: 90%;" />
                <button class="submit_btn" onclick="complete_payment()">SEND PAYMENT</button>
                </div>

                <div style="display: flex; flex-direction: column;align-items: center;width: 100%;"></div>

                <script>
                function payment_type() {
                    var payment = document.getElementById("payment_method").value;

                    if (payment == "EFT") {
                        document.getElementById("eft").style.display = "flex";
                        document.getElementById("cash").style.display = "flex";
                    } else if (payment == "CASH") {
                        document.getElementById("cash").style.display = "flex";
                        document.getElementById("eft").style.display = "none";
                    } else {
                        document.getElementById("cash").style.display = "none";
                        document.getElementById("eft").style.display = "none";
                    }
                }

                function eft_option() {
                    var select = document.getElementById("eft_type");
                    var file_div = document.getElementById("file_div");
                    var camera_div = document.getElementById("camera_div");

                    if (select.value === "FILE") {
                        file_div.style.display = "flex";
                        camera_div.style.display = "none";
                    } else if (select.value === "CAMERA") {
                        file_div.style.display = "none";
                        camera_div.style.display = "flex";
                    } else {
                        file_div.style.display = "none";
                        camera_div.style.display = "none";
                    }
                }

                // ─── Upload state tracker ───────────────────────────────────────────────────
                var uploadInProgress = false;
                var uploadComplete   = false;

                function upload_file_ajax() {
                    var payment_proof = document.getElementById("payment_proof");
                    var file          = payment_proof.files[0];
                    var jobcard_no    = "<?php echo $_GET['jobcard_no']; ?>";
                    var statusEl      = document.getElementById("upload_status");
                    var hiddenInput   = document.getElementById("uploaded_file_name");

                    // Reset state on new file selection
                    uploadComplete = false;
                    hiddenInput.value = "";

                    if (!file) return;

                    uploadInProgress = true;
                    statusEl.style.color = "gray";
                    statusEl.textContent  = "⏳ Uploading…";

                    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/pump/slips/");

                    var xhr = new XMLHttpRequest();

                    xhr.onreadystatechange = function () {
                        if (xhr.readyState === 4) {
                            uploadInProgress = false;

                            if (xhr.status === 200 && xhr.responseText.includes("OK")) {
                                // Extract filename — handles "OK | filename.jpg" or just "filename.jpg"
                                var filename = xhr.responseText.replace(/^OK\s*\|\s*/i, '').trim();

                                if (filename === "") {
                                    statusEl.style.color = "red";
                                    statusEl.textContent  = "⚠ Upload succeeded but no filename returned.";
                                    console.error("Server returned OK but no filename:", xhr.responseText);
                                    return;
                                }

                                hiddenInput.value = filename;
                                uploadComplete    = true;

                                statusEl.style.color = "green";
                                statusEl.textContent  = "✔ Uploaded: " + filename;
                                console.log("Uploaded filename stored:", filename);

                            } else {
                                uploadComplete = false;
                                statusEl.style.color = "red";
                                statusEl.textContent  = "✖ Upload failed. Try again.";
                                console.error("Upload error:", xhr.responseText);
                            }
                        }
                    };

                    xhr.open("POST", "../pump/upload_slip.php", true);
                    xhr.send(formData);
                }

                function complete_payment() {
                    var payment = document.getElementById("payment_method").value;
                    var eft_type = document.getElementById("eft_type").value;
                    var user_id = "<?= $_SESSION['user_id'] ?>";
                    var record_id  = "<?= $_GET['jobcard_no'] ?>";

                    if (payment == "") {
                        alert("Please select Payment Method");
                        return false;
                    }

                    var amount = document.getElementById("cash_amount").value;
                    if (amount.trim() === "" || isNaN(amount) || amount <= 0) {
                        alert("Please enter a valid Amount Paid");
                        return false;
                    }

                    var formData = new FormData();
                    formData.append('record_id', record_id);
                    formData.append('payment_method', payment);
                    formData.append('amount', amount);
                    formData.append('user_id', user_id);

                    if (payment === "EFT") {
                        if (eft_type === "CAMERA") {
                            var slip_input = document.getElementById("slip_file").value;
                            if (slip_input === "" || slip_input.trim() === "") {
                                alert("Please capture Slip Image");
                                return false;
                            }
                            formData.append('file', slip_input);

                        } else if (eft_type === "FILE") {
                            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;
                        }
                    }

                                // Continue with existing AJAX submission code...
                                const xhr = new XMLHttpRequest();
                                xhr.open('POST', '../jobcard_payments.ajax.php', true);
                                xhr.onreadystatechange = function () {
                                    if (xhr.readyState === 4) {
                                        if (xhr.status === 200 && xhr.responseText.includes("OK")) {
                                            console.log(`PAYMENT SUCCESS: ${xhr.responseText}`);
                                            alert('Payment completed successfully!');

                                            document.getElementById("cash_amount").value = "";
                                            document.getElementById("slip_file").value = "";
                                            document.getElementById("payment_proof").value = "";

                                            if (document.getElementById("uploaded_file_name")) {
                                                document.getElementById("uploaded_file_name").value = "";
                                            }

                                            document.getElementById("payment_method").selectedIndex = 0;
                                            document.getElementById("eft_type").selectedIndex = 0;
                                            document.getElementById("cash").style.display = "none";
                                            document.getElementById("eft").style.display = "none";

                                            loadPaymentHistory();
                                        } else {
                                            console.log(`Error saving PAYMENT: ${xhr.responseText}`);
                                            alert('Error completing payment! Try again.');
                                            return false;
                                        }
                                    }
                                };
                                xhr.send(formData);
                }

                function loadPaymentHistory() {
                    var jobcard_no = "<?php echo $_GET['jobcard_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", "../pump/payment_history.ajax.php", true);
                    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                    xhr.send("jobcard_no=" + encodeURIComponent(jobcard_no));
                }

                // Load history on page load
                document.addEventListener("DOMContentLoaded", loadPaymentHistory);

                loadPaymentHistory();
                </script>
      </div>

      </div>
    </div>
    

    <div style="width: 90%; background-color: white; border-radius: 2vw; display: flex; flex-direction: column;padding: 1vw; margin: 1vw;">
      <div class='div_signatures'>
        <div class="sub_down">
          <?php
            $target_dir = __DIR__ . "/signatures/";
            $target_url = "/app/jobcards/pump/signatures/";

            $employee_flie = $target_dir . "employee-jc_" . $install_jobcards['jobcard_no'] . "-" . $_SESSION['user_id'] . "-signature.png";
            $employee_url = $target_url . "employee-jc_" . $install_jobcards['jobcard_no'] . "-" . $_SESSION['user_id'] . "-signature.png";

            // EMPLOYEE SIGNATURE
            if (file_exists($employee_flie)) {
              ?>
                  <div class='jobcard_work_signature' style='margin-bottom:1vw;'>
                  <h2 style="font-size: 3em;">EMPLOYEE SIGNATURE</h2>
                  <input type='image' src='<?php echo $employee_url; ?>' alt='employee signature' class="signature_image">
                  </div>
              <?php
            }

            // CLIENT SIGNATURE
            $client_file = $target_dir . "client-jc_" . $install_jobcards['jobcard_no'] . "-" . $_SESSION['user_id'] . "-signature.png";
            $client_url = $target_url . "client-jc_" . $install_jobcards['jobcard_no'] . "-" . $_SESSION['user_id'] . "-signature.png";

            if (file_exists($client_file)) {
              ?>
                  <div class='jobcard_work_signature' style='margin-bottom:1vw;'>
                  <h2 style="font-size: 3em;">CLIENT SIGNATURE</h2>
                  <input type="image" src="<?php echo $client_url; ?>" alt="client signature" class="signature_image">
                  </div>
              <?php
            } 
          ?>
        </div>
      </div>
    </div>
  </div>
</form>