<?php include('db_connect.php');?>

<div class="container-fluid">
    <div class="col-lg-12 mt-3">
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center bg-light">
                <h5 class="mb-0 text-dark"><b>Utility Billing Ledger</b></h5>
                <button class="btn btn-primary btn-sm px-3 font-weight-bold" id="new_utility">
                    <i class="fa fa-plus"></i> Add New Bill
                </button>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-bordered table-striped table-hover" id="utility-list">
                        <thead class="bg-light">
                            <tr>
                                <th class="text-center" style="width: 5%;">#</th>
                                <th style="width: 15%;">Billing Date</th>
                                <th style="width: 35%;">Tenant / Property Info</th>
                                <th style="width: 15%;">Bill Type</th>
                                <th class="text-right" style="width: 10%;">Meter Reading</th>
                                <th class="text-right" style="width: 10%;">Amount (KES)</th>
                                <th class="text-center" style="width: 10%;">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php 
                            $i = 1;
                            // Pull bills cleanly tied back to active property contexts
                            $bills = $conn->query("SELECT b.*, concat(t.lastname,', ',t.firstname) as tname, h.house_no, h.building 
                                                 FROM utility_bills b 
                                                 INNER JOIN tenants t ON t.id = b.tenant_id 
                                                 INNER JOIN houses h ON h.id = t.house_id 
                                                 ORDER BY b.billing_date DESC");
                            
                            while($row = $bills->fetch_assoc()):
                            ?>
                            <tr>
                                <td class="text-center align-middle"><?php echo $i++ ?></td>
                                <td class="align-middle">
                                    <span class="font-weight-bold text-secondary"><?php echo date("M d, Y", strtotime($row['billing_date'])) ?></span>
                                </td>
                                <td class="align-middle">
                                    <p class="mb-0">Occupant: <b class="text-dark"><?php echo ucwords($row['tname']) ?></b></p>
                                    <p class="mb-0"><small class="text-muted"><i class="fa fa-building"></i> <?php echo ucwords($row['building']) ?> — Unit <?php echo $row['house_no'] ?></small></p>
                                </td>
                                <td class="align-middle">
                                    <span class="badge badge-info px-2 py-1 font-weight-bold"><?php echo $row['type'] ?></span>
                                </td>
                                <td class="text-right align-middle text-monospace">
                                    <?php echo $row['reading'] > 0 ? number_format($row['reading'], 2) : '<span class="text-muted font-italic">N/A</span>' ?>
                                </td>
                                <td class="text-right align-middle text-dark font-weight-bold">
                                    <?php echo number_format($row['amount'], 2) ?>
                                </td>
                                <td class="text-center align-middle">
                                    <div class="btn-group" role="group">
                                        <button class="btn btn-sm btn-outline-primary edit_utility font-weight-bold" type="button" data-id="<?php echo $row['id'] ?>" title="Modify Bill Entry">
                                            <i class="fa fa-edit"></i>
                                        </button>
                                        <button class="btn btn-sm btn-outline-danger delete_utility" type="button" data-id="<?php echo $row['id'] ?>" title="Drop Record">
                                            <i class="fa fa-trash-alt"></i>
                                        </button>
                                    </div>
                                </td>
                            </tr>
                            <?php endwhile; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(document).ready(function(){
        if($('#utility-list').length > 0){
            $('#utility-list').dataTable({
                "order": [[1, "desc"]], // Sort cleanly by latest biological transaction run-date defaults
                "pageLength": 10
            });
        }
    });

    // Routed safely directly into our updated manage_utility.php target view modal file
    $('#new_utility').click(function(){
        uni_modal("<i class='fa fa-plus text-primary'></i> Record Structural Utility Log","manage_utility.php","mid-large");
    });

    $('.edit_utility').click(function(){
        uni_modal("<i class='fa fa-edit text-warning'></i> Adjust Utility Adjustment Parameters","manage_utility.php?id="+$(this).attr('data-id'),"mid-large");
    });

    $('.delete_utility').click(function(){
        _conf("Are you entirely sure you want to drop this utility statement validation? All linked outstanding ledger tracking metrics will adjust.","delete_utility",[$(this).attr('data-id')]);
    });

    function delete_utility($id){
        start_load();
        $.ajax({
            url: 'ajax.php?action=delete_utility',
            method: 'POST',
            data: { id: $id },
            success: function(resp){
                if(resp == 1){
                    alert_toast("Utility billing node cleared from database ecosystem.", 'success');
                    setTimeout(function(){
                        location.reload();
                    }, 1000);
                } else {
                    alert_toast("An infrastructure rejection code halted clearing behaviors.", 'danger');
                    end_load();
                }
            },
            error: function(err){
                console.error("Critical execution fault dropping operational statement:", err);
                alert_toast("Network connectivity error occurred during operation.", 'danger');
                end_load();
            }
        });
    }
</script>