<script>
    if (<?php echo json_encode($hidestatus); ?> == 0) {
        document.querySelectorAll('.hidebutton').forEach(div => div.setAttribute('style', 'display:none;'));
    }
</script>

<p id="success"></p>
<section class="content">
  <div class="container-fluid">
    <div class="col-lg-12 col-12">
      <div class="small-box bg-secondry shadow_block p-3">
        <div class="inner">
         <!-- <h4 class="text-center mb-4">
            Today <b>Payment Collections</b> &#8369;<?php echo number_format(($todaypayreceived)); ?>
          </h4>  -->

          <!-- Search Input -->
          <input type="text" id="paymentSearch" class="form-control mb-4" placeholder="Search by name, account ID, type, ref #" />

          <?php
          $result = mysqli_query($conn, 
            "SELECT 
              tbl_user_account.unique_id, 
              tbl_user_account.acct_holder, 
              tbl_user_account.firstname, 
              tbl_user_account.lastname, 
              tbl_user_account.pres_reading, 
              tbl_payments.referrence_code, 
              tbl_payments.payment_type, 
              tbl_payments.amount, 
              tbl_payments.payment_option, 
              tbl_payments.reading_date, 
              tbl_payments.collection_date, 
              tbl_payments.date_encoded, 
              tbl_payments.payment_date 
            FROM 
              tbl_user_account 
            LEFT JOIN 
              tbl_payments 
            ON 
              tbl_user_account.unique_id = tbl_payments.unique_id 
            WHERE 
              tbl_payments.payment_date LIKE '$newcurrentdate%' 
            ORDER BY 
              tbl_payments.date_encoded DESC"
          );

          $i = 1;
          while($row = mysqli_fetch_array($result)) {
            $unique_id = $row['unique_id'];
            $acct_holder = $row['acct_holder'];
            $firstname = $row['firstname'];
            $lastname = $row['lastname'];
            $pres_reading = $row['pres_reading']; 
            $payment_type = $row['payment_type'];
            $amount = $row['amount'];
            $payment_option = $row['payment_option'];
            $reading_date = $row['reading_date'];
            $payment_date = $row['payment_date'];
            $collection_date = $row['collection_date'];
            $referrence_code = $row['referrence_code'];
            $date_encoded = $row['date_encoded'];
          ?>

          <div class="card mb-3 p-3 shadow payment-card" 
               data-search="<?php echo strtolower("$referrence_code $acct_holder $unique_id $payment_type $payment_date"); ?>">
            <div class="row">
              <div class="col-md-9">
                <p><strong>Ref #:</strong> <?= $referrence_code ?></p>
                <p><strong>Name:</strong> <?= $acct_holder ?></p>
                <p><strong>Account ID:</strong> <?= $unique_id ?></p>
                <p><strong>Type:</strong> <?= $payment_type ?></p>
                <p><strong>Amount Paid:</strong> ₱<?= number_format($amount, 2) ?></p>
                <p><strong>Payment Date:</strong> <?= $payment_date ?></p>
                <p><strong>Reading Date:</strong> <?= $reading_date ?></p>
                <p><strong>Encoded:</strong> <?= $date_encoded ?></p>
              </div>
              <div class="col-md-3 text-right">
                <a href="printreceipt.php?mid=<?= urlencode($unique_id); ?>&acctholder=<?= urlencode($acct_holder); ?>&fname=<?= urlencode($firstname); ?>&lname=<?= urlencode($lastname); ?>&pres_reading=<?= urlencode($pres_reading); ?>&payment_type=<?= urlencode($payment_type); ?>&amount=<?= urlencode($amount); ?>&payment_option=<?= urlencode($payment_option); ?>&reading_date=<?= urlencode($reading_date); ?>&payment_date=<?= urlencode($payment_date); ?>&collection_date=<?= urlencode($collection_date); ?>&refnum=<?= urlencode($referrence_code); ?>"
                   class="btn btn-sm btn-info mb-2">
                  <i class="fas fa-print"></i> Print
                </a>

                <div class="hidebutton">
                  <button class="btn btn-sm btn-danger delete-btn" data-unique-id="<?= $unique_id ?>" data-ref-code="<?= $referrence_code ?>">
                    <i class="fas fa-trash-alt"></i>
                  </button>
                </div>
              </div>
            </div>
          </div>

          <?php $i++; } ?>
        </div>
      </div>
    </div>
  </div>
</section>

<!-- Live Search Script -->
<script>
  document.getElementById("paymentSearch").addEventListener("input", function () {
    const searchValue = this.value.toLowerCase();
    const cards = document.querySelectorAll(".payment-card");

    cards.forEach(function (card) {
      const searchText = card.getAttribute("data-search");
      card.style.display = searchText.includes(searchValue) ? "" : "none";
    });
  });
</script>

<!-- Delete Button Script (Unchanged) -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
  document.querySelectorAll('.delete-btn').forEach(function(button) {
    button.addEventListener('click', function() {
      const uniqueId = button.getAttribute('data-unique-id');
      const refCode = button.getAttribute('data-ref-code');
      const accountName = button.closest('.card').querySelector('p:nth-child(2)').innerText;

      Swal.fire({
        title: 'Are you sure?',
        html: `<b>Account ID:</b> ${uniqueId} <br> <b>Account Name:</b> ${accountName} <br> <b>Reference #:</b> ${refCode}`,
        icon: 'warning',
        showCancelButton: true,
        confirmButtonText: 'Yes, delete it!',
        cancelButtonText: 'No, cancel!',
      }).then((result) => {
        if (result.isConfirmed) {
          fetch('delete_payment.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: 'unique_id=' + uniqueId + '&ref_code=' + refCode
          })
          .then(response => response.text())
          .then(data => {
            if (data === 'success') {
              Swal.fire('Deleted!', 'The payment record has been deleted.', 'success').then(() => location.reload());
            } else {
              Swal.fire('Error!', 'There was an issue deleting the payment record.', 'error');
            }
          })
          .catch((error) => {
            console.error('Error:', error);
            Swal.fire('Error!', 'An unexpected error occurred.', 'error');
          });
        }
      });
    });
  });
</script>
