<?php include('db_connect.php'); ?>
<?php 
// Fallback gracefully to the current calendar period if no filter parameter is specified
$month_of = isset($_GET['month_of']) ? $_GET['month_of'] : date('Y-m');
?>

<div class="container-fluid">
    <div class="col-lg-12 mt-3">
        <div class="card">
            <div class="card-body">
                <div class="col-md-12">
                    <form id="filter-report" class="d-print-none">
                        <div class="row form-group justify-content-center align-items-center">
                            <label class="control-label font-weight-bold text-dark mr-2 mb-0">Statement Month: </label>
                            <div class="col-md-4">
                                <input type="month" name="month_of" class="form-control" value="<?php echo $month_of ?>">
                            </div>
                            <div class="col-md-2">
                                <button class="btn btn-sm btn-primary btn-block font-weight-bold py-2">
                                    <i class="fa fa-filter"></i> Filter
                                </button>
                            </div>
                        </div>
                    </form>
                    <hr class="d-print-none">
                    
                    <div class="row mb-3 d-print-none">
                        <div class="col-md-12">
                            <button class="btn btn-sm btn-success px-4 float-right font-weight-bold" type="button" id="print">
                                <i class="fa fa-print"></i> Print Clean A4 Report
                            </button>
                        </div>
                    </div>
                    
                    <div id="report" class="p-3 bg-white">
                        <div class="print-header text-center mb-4">
                            <h3 class="font-weight-bold mb-1 text-dark">Rental Payments Report</h3>
                            <p class="text-muted">For the Month of: <span class="font-weight-bold text-primary"><?php echo date('F, Y', strtotime($month_of.'-01')) ?></span></p>
                            <hr class="print-divider" style="display:none; border-top: 2px solid #000;">
                        </div>
                        
                        <div class="table-responsive">
                            <table class="table table-bordered table-striped table-hover font-size-14">
                                <thead class="bg-light">
                                    <tr>
                                        <th class="text-center">#</th>
                                        <th>Payment Date</th>
                                        <th>Tenant Name</th>
                                        <th>House Unit No</th>
                                        <th>Invoice Ref #</th>
                                        <th class="text-right">Amount Remitted (KES)</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php 
                                    $i = 1;
                                    $tamount = 0;
                                    
                                    // Execute transactional calculation array against current active month parameters
                                    $payments = $conn->query("SELECT p.*, concat(t.lastname,', ',t.firstname,' ',t.middlename) as name, h.house_no FROM payments p inner join tenants t on t.id = p.tenant_id inner join houses h on h.id = t.house_id where date_format(p.date_created,'%Y-%m') = '$month_of' order by unix_timestamp(p.date_created) asc");
                                    
                                    if($payments && $payments->num_rows > 0):
                                        while($row = $payments->fetch_assoc()):
                                            $tamount += $row['amount'];
                                    ?>
                                    <tr>
                                        <td class="text-center"><?php echo $i++ ?></td>
                                        <td><?php echo date('M d, Y', strtotime($row['date_created'])) ?></td>
                                        <td><span class="font-weight-bold"><?php echo ucwords($row['name']) ?></span></td>
                                        <td><span class="badge badge-secondary py-1 px-2">Unit <?php echo $row['house_no'] ?></span></td>
                                        <td><code><?php echo !empty($row['invoice']) ? $row['invoice'] : 'N/A' ?></code></td>
                                        <td class="text-right font-weight-bold text-dark"><?php echo number_format($row['amount'], 2) ?></td>
                                    </tr>
                                    <?php endwhile; ?>
                                    <?php else: ?>
                                    <tr>
                                        <td colspan="6" class="text-center py-4 text-muted font-italic">
                                            No collection data or cash receipts logged for this calendar period.
                                        </td>
                                    </tr>
                                    <?php endif; ?>
                                </tbody>
                                <tfoot class="bg-light border-top">
                                    <tr>
                                        <th colspan="5" class="text-right font-weight-bold text-dark">Aggregate Monthly Revenue Collection:</th>
                                        <th class="text-right font-weight-bold text-success border-double" style="font-size: 1.1rem;">
                                            KES <?php echo number_format($tamount, 2) ?>
                                        </th>
                                    </tr>
                                </tfoot>
                            </table>
                        </div>
                    </div>

                </div>
            </div>
        </div>
    </div>
</div>

<noscript id="print-rules-sheet">
    <style>
        @media print {
            @page {
                size: A4 portrait;
                margin: 20mm 15mm 20mm 15mm;
            }
            body {
                font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
                color: #333;
                background: #fff;
                font-size: 11pt;
            }
            .d-print-none, #filter-report, button {
                display: none !important;
            }
            table {
                width: 100%;
                border-collapse: collapse;
                margin-top: 10px;
                page-break-inside: auto;
            }
            tr {
                page-break-inside: avoid;
                page-break-after: auto;
            }
            thead {
                display: table-header-group;
            }
            th {
                background-color: #f8f9fa !important;
                color: #000 !important;
                -webkit-print-color-adjust: exact;
                print-color-adjust: exact;
                border: 1px solid #222 !important;
                font-weight: bold;
                padding: 8px;
            }
            td {
                border: 1px solid #ddd !important;
                padding: 8px;
                vertical-align: middle;
            }
            .text-right { text-align: right !important; }
            .text-center { text-align: center !important; }
            .font-weight-bold { font-weight: bold !important; }
            .print-divider { display: block !important; }
            .badge { border: 1px solid #777; padding: 2px 4px; font-size: 10pt; }
            .border-double { border-top: 1px solid #000; border-bottom: 4px double #000 !important; }
        }
    </style>
</noscript>

<script>
    $(document).ready(function(){
        // Ensure data layout metrics table initializes styling wrappers correctly
        if($('.font-size-14').length > 0 && typeof $.fn.dataTable === "function") {
            // Optional local datatable mapping wrapper configuration can be safely injected here
        }
    });

    $('#filter-report').submit(function(e){
        e.preventDefault();
        // Redirect seamlessly into index routing framework parameters
        location.href = 'index.php?page=payment_report&' + $(this).serialize();
    });

    $('#print').click(function(){
        // Validate payload rows before spawning popup frames
        if($('#report-list').find('.text-muted').length > 0) {
            alert_toast("Cannot execute print on empty transaction parameters.", "danger");
            return false;
        }

        var _style = $('#print-rules-sheet').html();
        var _content = $('#report').html();
        
        var nw = window.open("", "_blank", "width=950,height=800");
        nw.document.write('<html><head><title>Rental Payments Statement</title>');
        // Load layout framework configuration defaults
        nw.document.write('<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">');
        nw.document.write(_style);
        nw.document.write('</head><body>');
        nw.document.write('<div class="container py-3">');
        nw.document.write(_content);
        nw.document.write('</div>');
        nw.document.write('</body></html>');
        
        nw.document.close();
        
        // Split-second delay script configuration block to allow layout engines to apply portrait styles smoothly
        setTimeout(function(){
            nw.print();
            setTimeout(function(){
                nw.close();
            }, 500);
        }, 500);
    });
</script>