<!-- Modal -->
<div class="modal fade" id="updateModal" tabindex="-1" aria-labelledby="updateModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <form id="updateForm" method="post" action="update_reading.php">
        <div class="modal-header">
          <h5 class="modal-title" id="updateModalLabel"><b>Reset Meter Values </b></h5>
          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
        <div class="modal-body">
          <div class="form-group">
            <label for="accountNo">Account Number</label>
            <input type="text" class="form-control" id="accountNo" name="accountNo" readonly>
          </div>
          <div class="form-group">
            <label for="name">Account Holder</label>
            <input type="text" class="form-control" id="name" name="name" readonly>
          </div>
          <div class="form-group">
            <label for="prevReading">Current Meter Value</label>
            <input type="text" class="form-control" id="prevReading" name="prevReading" readonly>
          </div>
          <div class="form-group">
            <label for="newReading">New Meter Value</label>
            <input type="number" class="form-control" id="newReading" name="newReading" required>
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
          <button type="submit" class="btn btn-primary">Save Changes</button>
        </div>
      </form>
    </div>
  </div>
</div>

<div class="inner">
  <h4 class="mx-auto">Active Line <b>Accounts</b></h4>
  <table id="example1" class="table table-striped table-bordered table-sm table-hover" cellspacing="0" width="100%">
    <thead>
      <tr>
        <th>Account</th>
        <th>Account Holder</th>
        <th>MD Balance</th>
        <th>WB Balance</th>
        <th>Status</th>
        <th>Action</th>
      </tr>
    </thead>
    <tbody>
      <?php
      $result = mysqli_query($conn, "SELECT * FROM tbl_user_account WHERE line_status = 1 ORDER BY unique_id DESC");
      $i = 1;
      while ($row = mysqli_fetch_array($result)) {
      ?>
        <tr id="<?php echo $row["id"]; ?>">
          <td><?php echo $row['unique_id'] ?></td>
          <td><?php echo $row['acct_holder'] ?></td>
          <td>
            <?php
            $unique_id = $row['unique_id'];
            $sql_user_billrecord = "SELECT SUM(amount) as feepaidbalances FROM tbl_payments WHERE payment_type = 'MD' AND unique_id = '$unique_id'";
            $result_user_billpay = mysqli_query($conn, $sql_user_billrecord);
            $row_user_billpay_summary = mysqli_fetch_assoc($result_user_billpay);

            $sql_user_readings1 = "SELECT sum(fee) as totalfee FROM tbl_meterdevice WHERE account_no = '$unique_id'";
            $result_user_details2 = mysqli_query($conn, $sql_user_readings1);
            $row_user_readings_summary = mysqli_fetch_assoc($result_user_details2);

            $remainingbalance_summary = $row_user_readings_summary['totalfee'];
            $billspayment_summary = $row_user_billpay_summary['feepaidbalances'];

            $totalmeterfee = $remainingbalance_summary - $billspayment_summary;

            if ($totalmeterfee > 0) {
              echo '<b style="color:red">&#8369;' . $totalmeterfee . '</b>';
            } else {
              echo '<b style="color:green">&#8369; 0.00</b>';
            }
            ?>
          </td>
          <td>
            <?php
            $sql_user_billrecord = "SELECT SUM(amount) as billspaidbalances FROM tbl_payments WHERE unique_id = '$unique_id' AND payment_type = 'WB'";
            $result_user_billpay = mysqli_query($conn, $sql_user_billrecord);
            $row_user_billpay = mysqli_fetch_assoc($result_user_billpay);

            $sql_user_readings1 = "SELECT sum(billing_amount) as totalbills FROM tbl_members_report WHERE account_no = '$unique_id' ORDER BY reading_date DESC";
            $result_user_details2 = mysqli_query($conn, $sql_user_readings1);
            $row_user_readings3 = mysqli_fetch_assoc($result_user_details2);
            $wpblance = $row_user_readings3['totalbills'];

            $sql_user_bklogs = "SELECT sum(amount) as bklogtotal FROM tbl_backlogs_collection WHERE account_no = '$unique_id'";
            $result_bl_details2 = mysqli_query($conn, $sql_user_bklogs);
            $row_user_bklogread = mysqli_fetch_assoc($result_bl_details2);
            $bklog = $row_user_bklogread['bklogtotal'];

            $remainingbalance = $wpblance + $bklog;
            $billspayment = $row_user_billpay['billspaidbalances'];

            $totalunpaidbill = $remainingbalance - $billspayment;

            if ($totalunpaidbill > 0) {
              echo '<b style="color:red">&#8369;' . $totalunpaidbill . '</b>';
            } else {
              echo '<b style="color:green">&#8369; 0.00</b>';
            }
            ?>
          </td>
          <td>
            <?php
            $linestatus = $row['line_status'];
            if ($linestatus == 0) {
            ?>
              <a href="connection.php?con=1&&mid=<?php echo $row['unique_id'] ?>" class="btn btn-outline-danger btn-radius">Disconnected</a>
            <?php
            } elseif ($linestatus == 1) {
            ?>
              <a href="connection.php?con=0&&mid=<?php echo $row['unique_id'] ?>" class="btn btn-outline-success btn-radius">Connected</a>
            <?php
            }
            ?>
          </td>
          <td>
            <a href="editmoreaccount.php?mid=<?php echo $row["unique_id"]; ?>" class="btn btn-outline-dark"><i class="fas fa-edit"></i></a>
            <a href="#updateModal" class="btn btn-outline-success btn-radius open-update-modal" style="background-color: #c5c5c5;" data-accountno="<?php echo $row['unique_id']; ?>" data-name="<?php echo $row['acct_holder']; ?>" data-prevreading="<?php echo $row['pres_reading']; ?>" data-toggle="modal"><i class="fas fa-infinity"></i></a>
            <a href="#deleteEmployeeModal" class="delete btn btn-danger btn-radius" data-id="<?php echo $row["id"]; ?>" data-toggle="modal"><i class="fas fa-trash-alt"></i></a>
          </td>
        </tr>
      <?php
      $i++;
      }
      ?>
    </tbody>
  </table>
 
</div>

<script> 
	$(document).on('click', '.open-update-modal', function () {
  const accountNo = $(this).data('accountno');
  const name = $(this).data('name');
  const prevReading = $(this).data('prevreading');

  $('#accountNo').val(accountNo);
  $('#name').val(name);
  $('#prevReading').val(prevReading);
});
$('#updateForm').on('submit', function (e) {
  e.preventDefault();

  // Perform AJAX request to update_reading.php
  $.ajax({
    url: 'reset_newmeter.php',
    type: 'POST',
    data: $(this).serialize(),
    success: function (response) {
      // Check if response.success is true
      if (response.success) {
        Swal.fire({
          icon: 'success',
          title: 'Success',
          text: 'Meter reading updated successfully!',
        }).then(() => {
          location.reload(); // Reload the page to reflect changes
        });
      } else {
        Swal.fire({
          icon: 'error',
          title: 'Error',
          text: response.message || 'An error occurred. Please try again.',
        });
      }
    },
    error: function () {
      Swal.fire({
        icon: 'error',
        title: 'Error',
        text: 'Unable to process your request.',
      });
    },
  });
});


</script>