<?php

$query_latest_date = mysqli_query($conn, "SELECT MAX(reading_date) AS latest_date FROM tbl_members_report");
$row_latest = mysqli_fetch_assoc($query_latest_date);
$latestReadingDate = $row_latest['latest_date'] ?? date("Y-m-d"); 
$filterDate = isset($_POST['reading_date']) ? $_POST['reading_date'] : $latestReadingDate;

//$datetoday = date("Y-m-d");
//$filterDate = isset($_POST['reading_date']) ? $_POST['reading_date'] : $datetoday;

?><p id="success"></p>
<section class="content">
<div class="container-fluid">
    <div class="col-lg-12 col-12">
        <div class="small-box bg-secondary " style="height: auto; width: 100%;"></div>
    </div>
</div>

<section class="content">
<div class="container-fluid">
    <div class="col-lg-12 col-12">
        <div class="small-box  shadow_block" style="height: auto; width: 100%;">
            <div class="inner">
                <h4 style="mx-auto">
                    <b>Reading Transaction Count: </b> <?php
                    $query_total = mysqli_query($conn, "SELECT COUNT(*) AS total FROM tbl_members_report WHERE reading_date = '$filterDate'");
                    $row_total = mysqli_fetch_assoc($query_total);
                    $rowtotalread = $row_total['total'];
                    
                    echo number_format(($rowtotalread)); ?>
                </h4>

                <?php
            // Calculate the total sum of billing amounts for the selected date
            $query_total = mysqli_query($conn, "SELECT SUM(billing_amount) AS sumtotal FROM tbl_members_report WHERE reading_date = '$filterDate'");
            $row_total = mysqli_fetch_assoc($query_total);
            $rowtotalsum = $row_total['sumtotal'] ?? 0; // Ensure it doesn't return null
            ?>

            <!-- Display the total billing amount -->
            <h4 style="mx-auto">
                <b>Total: </b> <?php echo number_format($rowtotalsum, 2); ?>
            </h4>

               
                <!-- Date Filter Form -->
                <form method="POST" action="">
                   
                    <select class="form-select" id="reading_date" name="reading_date" required>
                        <option value="">--Select a Date--</option>
                        <?php
                        if ($result_alldates->num_rows > 0) {
                            while ($row = $result_alldates->fetch_assoc()) {
                                $selected = (isset($_POST['reading_date']) && $_POST['reading_date'] == $row['reading_date']) ? "selected" : "";
                                echo "<option value='" . $row['reading_date'] . "' $selected>" . $row['reading_date'] . "</option>";
                            }
                        } else {
                            echo "<option value=''>No Dates Available</option>";
                        }
                        ?>
                    </select>
                    <button type="submit" name="filter_date" class="btn btn-primary">Filter Date</button>
                </form>

           <!-- Search Bar -->
<div class="mb-3">
  <input type="text" id="searchInput" class="form-control" placeholder="Search by Account No or Name...">
</div>

<!-- List Container -->
<div id="readingList" class="row g-3">
<?php
$result = mysqli_query($conn, "SELECT * FROM tbl_members_report WHERE reading_date = '$filterDate' ORDER BY id DESC");
while ($row = mysqli_fetch_array($result)) {
    $id = $row['id'];
    $transaction_date = $row['transaction_date'];
    $account_no = $row['account_no'];
    $account_name = $row['account_name'];
    $prev_reading = $row['prev_reading'];
    $pres_reading = $row['pres_reading'];
    $total_reading = $row['total_reading'];
    $billing_amount = $row['billing_amount'];
    $reading_date = $row['reading_date'];

    $account_no_enc = urlencode($account_no);
    $account_name_enc = urlencode($account_name);
    $pres_reading_enc = urlencode($pres_reading);
    $prev_reading_enc = urlencode($prev_reading);
    $total_reading_enc = urlencode($total_reading);
    $billing_amount_enc = urlencode($billing_amount);
    $reading_date_enc = urlencode($reading_date);
    $disconnection_date = urlencode($c_disconnection_date ?? '');
    $due_date = urlencode($c_due_date ?? '');

    $random_hash = bin2hex(random_bytes(10));
    $url = "printreceipt_reading.php?print$random_hash&mid=$account_no_enc&acctholder=$account_name_enc&pres_reading=$pres_reading_enc&prev_reading=$prev_reading_enc&total_reading=$total_reading_enc&billing_amount=$billing_amount_enc&reading_date=$reading_date_enc&disconnection=$disconnection_date&duedate=$due_date";
?>
  <div class="col-12 filter-item">
    <div class="card shadow-sm p-3">
      <div class="row">
        <div class="col-md-8">
          <h6 class="mb-1"><strong><?php echo $account_name; ?></strong> (<?php echo $account_no; ?>)</h6>
          <p class="mb-1">Trxn Date: <b><?php echo $transaction_date; ?></b></p>
          <p class="mb-1">Reading Date: <b><?php echo $reading_date; ?></b></p>
          <p class="mb-1">Previous: <b><?php echo $prev_reading; ?></b> | Present: <b><?php echo $pres_reading; ?></b> | Total: <b><?php echo $total_reading; ?></b></p>
          <p>Bill: <span class="text-success fw-bold">&#8369;<?php echo number_format($billing_amount, 2); ?></span></p>
        </div>
        <div class="col-md-4 text-end d-flex flex-column justify-content-center gap-2">
          <a href="<?php echo $url; ?>" class="btn btn-warning btn-sm"><i class="fas fa-print"></i> Print</a>
          <button class="btn btn-primary btn-sm edit-btn"
            data-id="<?php echo $id; ?>"
            data-prev-reading="<?php echo $prev_reading; ?>"
            data-pres-reading="<?php echo $pres_reading; ?>"
            data-reading-date="<?php echo $reading_date; ?>">
            <i class="fas fa-edit"></i> Edit
          </button>
          <button class="btn btn-danger btn-sm delete-button"
            data-id="<?php echo $id; ?>"
            data-account-no="<?php echo $account_no; ?>"
            data-prev-reading="<?php echo $prev_reading; ?>">
            <i class="fas fa-trash-alt"></i> Delete
          </button>
        </div>
      </div>
    </div>
  </div>
<?php } ?>
</div>

            </div>
        </div>
    </div>
</div>
<!-- Edit Modal -->
<div class="modal fade" id="editModal" tabindex="-1" role="dialog" aria-labelledby="editModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <form id="editForm">
                <div class="modal-header">
                    <h4 class="modal-title">UPDATE METER READING VALUES</h4>
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                </div>
                <div class="modal-body">
                <div class="form-group">
                        <label for="changeReadingDate">Change Date:</label>
                        <input type="date" id="changeReadingDate" class="form-control">
                    </div>

                    <div class="form-group">
                        <label for="prevReading">Previous Reading:</label>
                        <input type="number" id="prevReading-id-1" class="form-control" readonly>
                    </div>
                    <div class="form-group">
                        <label for="presReading">Enter New Reading:</label>
                        <input type="number" id="presReading-id-2" class="form-control">
                        <input type="hidden" value="75" readonly="readonly" name="reading_result_cubic" class="form-control" id="id-4">
                    </div>
                    <div class="form-group">
                        <label for="totalReading">Total Reading:</label>
                        <input type="text" min="0" readonly="readonly" name="reading_result" class="form-control" id="id-3">
                    </div>
                    <div class="form-group">
                        <label for="billingAmount">Billing Amount:</label>
                        <input type="number" id="billingAmount-id-5" class="form-control" readonly>
                    </div>
                </div>
                <div class="modal-footer">
                    <input type="hidden" id="editId">
                    <button type="submit" id="saveChangesBtn" class="btn btn-success" disabled>Save Changes</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
    // Open Modal
    $(document).on('click', '.edit-btn', function () {
        var id = $(this).data('id');
        var prevReading = $(this).data('prev-reading');
        var presReading = $(this).data('pres-reading');

        $('#editId').val(id);
        $('#prevReading-id-1').val(prevReading);
        $('#presReading-id-2').val(presReading);
        $('#changeReadingDate').val($(this).data('reading-date'));
        $('#editModal').modal('show');
    });

    // Enable/Disable Save Changes Button
    function toggleSaveButton() {
        var prevReading = parseFloat($('#prevReading-id-1').val()) || 0;
        var presReading = parseFloat($('#presReading-id-2').val()) || 0;

        if (presReading >= prevReading) {
            $('#saveChangesBtn').prop('disabled', false);
        } else {
            $('#saveChangesBtn').prop('disabled', true);
        }
    }

    function calculateReadings() {
    var prevReading = parseFloat($('#prevReading-id-1').val()) || 0;
    var presReading = parseFloat($('#presReading-id-2').val()) || 0;
    var rate = parseFloat($('#id-4').val()) || 0;

    var totalReading = presReading - prevReading;
    
    // Ensure totalReading is not negative
    if (totalReading < 0) totalReading = 0;

    // Update the total reading value
    $('#id-3').val(totalReading);

    // Logic for billing amount based on totalReading
    if (totalReading < 1) {
        // If total reading is less than 1, set the billing amount to 0
        $('#billingAmount-id-5').val(0);
    } else if (totalReading < 5) {
        // If total reading is between 1 and 5, set the billing amount to 300
        $('#billingAmount-id-5').val(300);
    } else {
        // If total reading is greater than or equal to 5, calculate billing amount
        $('#billingAmount-id-5').val((totalReading * rate).toFixed(2));
    }
}


    // Event Listener for presReading Input
    $('#presReading-id-2').on('input', function () {
        toggleSaveButton();
        calculateReadings();
    });

    // Save Changes with SweetAlert
    $('#editForm').on('submit', function (e) {
        e.preventDefault();

        Swal.fire({
            title: 'Are you sure?',
            text: "Do you want to save these changes?",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            confirmButtonText: 'Yes, save it!'
        }).then((result) => {
            if (result.isConfirmed) {
                var id = $('#editId').val();
                var presReading = $('#presReading-id-2').val();
                var totalReading = $('#id-3').val();
                var billingAmount = $('#billingAmount-id-5').val();
                var readingDate = $('#changeReadingDate').val(); // Added reading date

                

                $.ajax({
                    url: 'update_reading.php',
                    type: 'POST',
                    data: {
                        id: id,
                        pres_reading: presReading,
                        total_reading: totalReading,
                        billing_amount: billingAmount,
                        reading_date: readingDate 
                    },
                    success: function (response) {
                        if (response === 'success') {
                            Swal.fire(
                                'Updated!',
                                'The record has been updated successfully.',
                                'success'
                            ).then(() => {
                                location.reload(); // Reload page to reflect changes
                            });
                        } else {
                            Swal.fire(
                                'Error!',
                                'There was an issue updating the record.',
                                'error'
                            );
                        }
                    }
                });
            }
        });
    });
</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>
    $(document).on('click', '.delete-button', function () {
    var row = $(this).closest('tr'); // Get the closest table row
    var accountNo = row.find('td:eq(1)').text().trim(); // First column (Account No)
    var readingDate = row.find('td:eq(2)').text().trim(); // Second column (Reading Date)
    var accountName = row.find('td:eq(3)').text().trim(); // Third column (Account Name)
    var id = $(this).data('id'); // Get ID from button attribute

    Swal.fire({
        title: 'Are you sure?',
        text: `Do you really want to delete this record?\n\nAccount No: ${accountNo}\nReading Date: ${readingDate}\nAccount Name: ${accountName}`,
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#d33',
        cancelButtonColor: '#3085d6',
        confirmButtonText: 'Yes, delete it!'
    }).then((result) => {
        if (result.isConfirmed) {
            $.ajax({
                url: 'delete_readingrecord.php',
                type: 'POST',
                data: { id: id },
                success: function (response) {
                    if (response === 'success') {
                        Swal.fire('Deleted!', 'The record has been deleted.', 'success').then(() => location.reload());
                    } else {
                        Swal.fire('Error!', 'There was a problem deleting the record.', 'error');
                    }
                }
            });
        }
    });
});

</script>

<script>
document.getElementById('searchInput').addEventListener('keyup', function() {
  var searchValue = this.value.toLowerCase();
  var items = document.querySelectorAll('#readingList .filter-item');

  items.forEach(function(item) {
    var text = item.textContent.toLowerCase();
    item.style.display = text.includes(searchValue) ? '' : 'none';
  });
});
</script>
<style>
.card {
  border-radius: 10px;
  transition: 0.2s ease-in-out;
}
.card:hover {
  box-shadow: 0 0 10px rgba(0,0,0,0.15);
}
@media (max-width: 576px) {
  .text-end {
    text-align: left !important;
    margin-top: 1rem;
  }
}
</style>

