<script src="https://cdn.jsdelivr.net/npm/tesseract.js@2.1.1/dist/tesseract.min.js"></script>
  <style>
    #camera {
      display: none;
    }
    #preview {
      max-width: 100%;
      margin-top: 10px;
      display: none;
    }
    #status {
      font-weight: bold;
      margin-top: 10px;
    }
  </style> 
  
  <!-- Add Payment TAB HTML -->
<div id="addmetertModal" class="modal fade">
    <div class="modal-dialog">
        <div class="modal-content">
            <form id="user_form_meterreading" method="POST">
                <div class="modal-header">
                    <h4 class="modal-title">Meter Reading Details</h4>
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                </div>
                <div class="modal-body">
                    <div class="row">
                        <div class="col-sm-3">
                             
                            <input type="text" id="id_u_reading" name="id" class="form-control" hidden>
                        </div>
                        <div class="col-sm-8">
                            <label for="datepost">Account Holder: </label>
                            <input type="text" id="txt_acct_holder1" name="acctholder" class="form-control" readonly>
                        </div>
                        <label>Unpaid Balance:</label> 
                          <input type="text" id="wbbalancer" name="wbbalancer" class="form-control" style="font-size: 18px; color: blue; font-weight: bold;" readonly>
                        </div>

                    <div class="row">
                        <div class="col-sm-3">
                            <input type="hidden" id="duedate" name="duedate" value="" class="form-control" readonly>
                        </div>
                        <div class="col-sm-8">
                            <input type="hidden" id="disconnection" name="disconnection" value="" class="form-control" readonly>
                        </div>
                    </div>

                    <br>
                    <div class="row">
                      
                        <div class="col-sm-9">
                            <label for="datepost">New Reading Date:</label>
                            <input type="date" class="form-control" id="postdate" name="postdate" style="background: transparent;" value="<?php echo $c_readingdate; ?>" >
                            <input type="hidden" name="first_num" id="first_num" value="">
                        </div>
                    </div>

                    <br>
   <div class="form-group">
                  <label for="datepost">Previous Meter Value: </label>
                              <input type="number" id="id-1" name="prev_reading" min="0" class="form-control" style="background: transparent;" readonly>
                          </div>
                         
                          <center> 

                       <div class="col-12">
                         
                          
                                <p style="background: #000; color: #ffe900; padding: 5px;">
                                    <b>Enter Present Reading: </b>
                                </p>
                                <input type="text" name="newreading" id="id-2" class="form-control" required="required" style="font-size: 20px; font-weight: bold; color: #eb0000; text-align: center;" />
                                <input type="hidden" min="0" readonly="readonly" name="reading_result" class="form-control" id="id-3">
                                <input type="hidden" value="75" readonly="readonly" name="reading_result_cubic" class="form-control" id="id-4">
                          <hr>
                                <b>Total Bill: </b>
                                <input type="number" readonly="readonly" name="reading_result_bill" class="form-control" id="id-5" value="0" style="text-align: center; border: none; background-color: transparent; font-weight: bold; color: #ff0c0c; font-size: 45px;" />
                            
                        </div> 
                        </center>
                   
    </div>

<div class="modal-footer">
    <input type="hidden" value="7" name="type">

    <!-- Submit button -->
    <button type="submit" 
            class="btn btn-danger btn-radius btn-block btn-multi text-white" 
            id="btn-addmeterreading">
        Submit Reading
    </button>

    <!-- Warning message 
    <p id="reading-warning" style="display:none; color:red; font-weight:bold; text-align:center;">
        Cannot submit reading, Please pay Previous balance to proceed
    </p>-->
</div>
    </form>
    <center>
        <a href="transactionhistory.php?mid=" 
           onclick="this.href = this.href + document.getElementById('id_u_reading').value;">
           [View Readings History]
        </a>
    </center>
</div>
</div>
</div>
 

<script>
document.addEventListener("DOMContentLoaded", function() {
    let prevInput = document.getElementById("id-1"); // previous reading input
    let submitBtn = document.getElementById("btn-addmeterreading");

    if (submitBtn) { // only run if button exists
        function checkPrevReading() {
            let prevReading = parseFloat(prevInput.value) || 0;
            if (prevReading > 0) {
                submitBtn.disabled = true;
                submitBtn.innerText = "Reading Already Submitted";
                submitBtn.title = "Submit disabled because previous reading already exists.";
            } else {
                submitBtn.disabled = false;
                submitBtn.innerText = "Submit Reading";
                submitBtn.title = "";
            }
        }

        // Run on page load
        checkPrevReading();

        // Run again if value is updated dynamically
        prevInput.addEventListener("input", checkPrevReading);
    }
});
</script>




<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>



<script type="text/javascript"> 

//add meter reading
$(document).on("click", ".addmeterreading", function (e) {
  var id1 = $(this).attr("data-id");
  var acctholder1 = $(this).attr("data-name");
  var prevreading = $(this).attr("data-prevreading");
  var wbbalancer = $(this).attr("data-wbbalancer");

  $("#id_u1").val(id1);
  $("#txt_acct_holder1").val(acctholder1);
  $("#id-1").val(prevreading);
   $("#wbbalancer").val(wbbalancer);
});

 

$(function () {
  $("#id-1, #id-2, #id-3, #id-4, #id-5").keyup(function () {
    // Calculate the difference between Present Reading and Previous Reading
    const difference = +$("#id-2").val() - +$("#id-1").val();
    
    // Set the value of #id-3 as the difference
    $("#id-3").val(difference);

    // Check if the value of #id-3 is less than 1
    if (difference < 1) {
      // If the difference is less than 1, set #id-5 to 0
      $("#id-5").val(0);
    } else if (difference < 5) {
      // If the difference is less than 5 but not less than 1, set #id-5 to 300
      $("#id-5").val(300);
    } else if (difference === 0) {
      // If the difference is less than 5 but not less than 1, set #id-5 to 300
      $("#id-5").val(0);
    } else {
      // If the difference is greater than or equal to 5, calculate the Total Bill
      const readingResult = +$("#id-3").val(); // Get the difference (or reading result)
      const cubicRate = +$("#id-4").val(); // Get the cubic rate
      $("#id-5").val(readingResult * cubicRate); // Set the calculated total bill
    }
  });
});


</script>


<script>
    // Handle form submission with AJAX
    $('#user_form_meterreading').on('submit', function (e) {
        e.preventDefault();

        $.ajax({
            url: 'addnew_reading.php', // PHP file for processing
            type: 'POST',
            data: $(this).serialize(),
            dataType: 'json',
            success: function (response) {
                if (response.status === 'success') {
                    Swal.fire({
                        title: 'Success!',
                        text: response.message,
                        icon: 'success',
                        confirmButtonText: 'OK'
                    }).then(() => {
                        window.location.href = 'printlogs_reading.php';
                    });
                } else {
                    Swal.fire({
                        title: 'Error!',
                        text: response.message,
                        icon: 'error',
                        confirmButtonText: 'OK'
                    });
                }
            }
        });
    });
</script>

<script>
    $(document).ready(function () {
        const submitButton = $('#btn-addmeterreading');
        const newReadingInput = $('#id-2'); // Present Reading input
        const prevReadingInput = $('#id-1'); // Prev Reading input
        const newReadingDateInput = $('#postdate'); // New Reading Date input

        // Function to check if the button should be enabled
        function validateForm() {
            const presentReading = parseFloat(newReadingInput.val()) || 0;
            const prevReading = parseFloat(prevReadingInput.val()) || 0;
            const newReadingDate = newReadingDateInput.val();

            // Check conditions: new reading date should not be empty & present reading > previous reading
            if (newReadingDate && presentReading >= prevReading) {
               submitButton.prop('disabled', false);
            } else {
               submitButton.prop('disabled', true);
            }
        }

        // Attach event listeners to input fields
        newReadingInput.on('input', validateForm);
        prevReadingInput.on('input', validateForm); // In case you allow manual entry for testing
        newReadingDateInput.on('change', validateForm);

        // Initial validation on page load
        validateForm();
    });
</script>

 
<script>
  let video = document.getElementById('camera');
  let canvas = document.getElementById('canvas');
  let preview = document.getElementById('preview');
  let status = document.getElementById('status');
  let output = document.getElementById('output');
  let stream = null;

  function startCamera() {
    navigator.mediaDevices.getUserMedia({ video: { facingMode: 'environment' } })
      .then(function (mediaStream) {
        stream = mediaStream;
        video.srcObject = mediaStream;
        video.style.display = 'block';
        preview.style.display = 'none';
        status.innerText = "";
        output.value = "";
      })
      .catch(function (err) {
        alert('Camera access denied or not available');
        console.error(err);
      });
  }
  function captureImage() {
  if (!stream) return;

  // Set canvas size
  canvas.width = video.videoWidth;
  canvas.height = video.videoHeight;
  let context = canvas.getContext('2d');
  context.drawImage(video, 0, 0, canvas.width, canvas.height);

  let rawImageData = canvas.toDataURL('image/png');
  preview.src = rawImageData;
  preview.style.display = 'block';

  // Stop camera and hide it
  let tracks = stream.getTracks();
  tracks.forEach(track => track.stop());
  video.style.display = 'none';
  stream = null;

  // Preprocess image (grayscale + threshold)
  let img = new Image();
  img.onload = () => {
    context.drawImage(img, 0, 0, canvas.width, canvas.height);

    let imageDataObj = context.getImageData(0, 0, canvas.width, canvas.height);
    let data = imageDataObj.data;

    // Grayscale + thresholding
    for (let i = 0; i < data.length; i += 4) {
      let avg = (data[i] + data[i + 1] + data[i + 2]) / 3;
      let threshold = avg > 128 ? 255 : 0;
      data[i] = data[i + 1] = data[i + 2] = threshold; // black & white
    }

    context.putImageData(imageDataObj, 0, 0);

    // Run OCR on processed image
    let processedImageData = canvas.toDataURL('image/png');
    runTesseract(processedImageData);
  };
  img.src = rawImageData;
}

function runTesseract(imageData) {
  status.innerText = "Reading digits...";
  output.value = "";

  Tesseract.recognize(
    imageData,
    'eng',
    {
      logger: m => {
        if (m.status === "recognizing text") {
          status.innerText = `Progress: ${Math.round(m.progress * 100)}%`;
        }
      }
    }
  ).then(({ data: { text } }) => {
    const digits = text.match(/\d+/g)?.join('') || '';
    output.value = digits;
    status.innerText = digits ? "Reading complete." : "No digits found.";
  }).catch(err => {
    console.error(err);
    status.innerText = "Failed to read text.";
  });
}


  function resetAll() {
    if (stream) {
      let tracks = stream.getTracks();
      tracks.forEach(track => track.stop());
    }
    video.style.display = 'none';
    preview.style.display = 'none';
    preview.src = "";
    output.value = "";
    status.innerText = "";
    stream = null;
  }
</script> 

<script>
function checkUnpaidBalance() {
    const unpaidBalance = document.getElementById("wbbalancer");
    const submitBtn = document.getElementById("btn-addmeterreading");
    const warningMsg = document.getElementById("reading-warning");

    const value = parseFloat(unpaidBalance.value) || 0;
    if (value > 0) {
      //  submitBtn.style.display = "none";   // hide submit button
      //  warningMsg.style.display = "block"; // show warning
    } else {
      //  submitBtn.style.display = "block";  // show submit button
      //  warningMsg.style.display = "none";  // hide warning
    }
}

// Run once on page load (in case PHP sets a value)
window.addEventListener("load", checkUnpaidBalance);

// Also run whenever the modal is opened & values are set
$(document).on("click", ".addmeterreading", function (e) {
    var id1 = $(this).attr("data-id");
    var acctholder1 = $(this).attr("data-name");
    var prevreading = $(this).attr("data-prevreading");
    var wbbalancer = $(this).attr("data-wbbalancer");

    $("#id_u1").val(id1);
    $("#txt_acct_holder1").val(acctholder1);
    $("#id-1").val(prevreading);
    $("#wbbalancer").val(wbbalancer);

    // ✅ Check after assigning new value
    checkUnpaidBalance();
});
</script>
