<?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>Collection Ledger & Payments</b></h5>
                <button class="btn btn-primary btn-sm px-3 font-weight-bold" id="new_invoice">
                    <i class="fa fa-plus"></i> Record New Payment
                </button>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-bordered table-striped table-hover" id="payment-history-table">
                        <thead class="bg-light">
                            <tr>
                                <th class="text-center" style="width: 5%;">#</th>
                                <th style="width: 15%;">Transaction Date</th>
                                <th style="width: 35%;">Tenant & Allocation Reference</th>
                                <th style="width: 20%;">Invoice / Ref #</th>
                                <th class="text-right" style="width: 15%;">Amount Paid (KES)</th>
                                <th class="text-center" style="width: 10%;">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php 
                            $i = 1;
                            // Pulls payments data along with tenant and house configurations, including classification type maps
                            $invoices = $conn->query("SELECT p.*, concat(t.lastname,', ',t.firstname,' ',t.middlename) as name, t.status as tenant_status, h.house_no, h.building 
                                                     FROM payments p 
                                                     INNER JOIN tenants t ON t.id = p.tenant_id 
                                                     INNER JOIN houses h ON h.id = t.house_id 
                                                     ORDER BY DATE(p.date_created) DESC, p.id DESC");
                            
                            while($row = $invoices->fetch_assoc()):
                                // Map technical data keys to human-readable text labels and semantic styles
                                $p_type = isset($row['type']) ? strtolower($row['type']) : 'rent';
                                switch($p_type) {
                                    case 'parking':
                                        $badge_class = 'badge-info';
                                        $type_label = '<i class="fa fa-car mr-1"></i> Parking Fee';
                                        break;
                                    case 'utility':
                                        $badge_class = 'badge-warning text-dark';
                                        $type_label = '<i class="fa fa-tools mr-1"></i> Utilities/Garbage';
                                        break;
                                    case 'rent':
                                    default:
                                        $badge_class = 'badge-primary';
                                        $type_label = '<i class="fa fa-home mr-1"></i> Rent Payment';
                                        break;
                                }

                                // Apply penalty tracking modifier if flagged
                                if(isset($row['is_penalty']) && $row['is_penalty'] == 1) {
                                    $badge_class = 'badge-danger';
                                    $type_label = '<i class="fa fa-exclamation-triangle mr-1"></i> Late Penalty Charge';
                                }
                            ?>
                            <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['date_created'])) ?></span>
                                </td>
                                <td class="align-middle">
                                    <div class="mb-1 d-flex flex-wrap align-items-center" style="gap: 6px;">
                                        <b class="text-dark mr-1"><?php echo ucwords($row['name']) ?></b>
                                        <?php if($row['tenant_status'] == 1): ?>
                                            <span class="badge badge-success" style="font-size: 10px; padding: 2px 6px;">Active</span>
                                        <?php else: ?>
                                            <span class="badge badge-secondary" style="font-size: 10px; padding: 2px 6px;">Moved Out</span>
                                        <?php endif; ?>
                                        
                                        <span class="badge <?php echo $badge_class ?>" style="font-size: 10px; padding: 2px 6px; font-weight: 600;">
                                            <?php echo $type_label ?>
                                        </span>
                                    </div>
                                    <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 text-monospace">
                                    <span class="text-uppercase font-weight-bold tracking-wider"><?php echo $row['invoice'] ?></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_invoice font-weight-bold" type="button" data-id="<?php echo $row['id'] ?>" title="Edit Payment Record">
                                            <i class="fa fa-edit"></i>
                                        </button>
                                        <button class="btn btn-sm btn-outline-danger delete_invoice" type="button" data-id="<?php echo $row['id'] ?>" title="Void Receipt">
                                            <i class="fa fa-trash-alt"></i>
                                        </button>
                                    </div>
                                </td>
                            </tr>
                            <?php endwhile; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div> 
</div>

<style>
    td {
        vertical-align: middle !important;
    }
    .text-monospace {
        font-family: SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace !important;
    }
    .tracking-wider {
        letter-spacing: 0.05em;
    }
    .scale-up {
        transition: transform 0.2s ease;
    }
</style>

<script>
    $(document).ready(function(){
        if($('#payment-history-table').length > 0){
            $('#payment-history-table').dataTable({
                "order": [[1, "desc"]], // Keep recent cash receipts at the top automatically
                "pageLength": 10
            });
        }
    });
    
    $('#new_invoice').click(function(){
        uni_modal("<i class='fa fa-plus text-primary'></i> Record Cash Remittance Receipt","manage_payment.php","mid-large");
    });

    $('.edit_invoice').click(function(){
        uni_modal("<i class='fa fa-edit text-warning'></i> Modify Payment Reconciliation Parameters","manage_payment.php?id="+$(this).attr('data-id'),"mid-large");
    });

    $('.delete_invoice').click(function(){
        _conf("Are you entirely sure you want to void this payment record? This action will reverse the transaction and update the tenant's outstanding balance ledger.", "delete_invoice", [$(this).attr('data-id')]);
    });
    
    function delete_invoice($id){
        start_load();
        $.ajax({
            url: 'ajax.php?action=delete_payment',
            method: 'POST',
            data: { id: $id },
            success: function(resp){
                if(resp == 1){
                    alert_toast("Payment reference successfully voided and ledger updated.", 'success');
                    setTimeout(function(){
                        location.reload();
                    }, 1000);
                } else {
                    alert_toast("The transaction reversal request was rejected by the server.", 'danger');
                    end_load();
                }
            },
            error: function(err){
                console.error("Critical execution breakdown updating payment node logs:", err);
                alert_toast("Network infrastructure timeout fault experienced.", 'danger');
                end_load();
            }
        });
    }
</script>