<?php include 'db_connect.php' ?>
<style>
    /* System Layout Isolation Context */
    .report-view-wrapper {
        padding: 20px;
        background-color: #f8fafc;
        min-height: calc(100vh - 3.5rem);
    }

    /* Modern Card Architecture */
    .report-card {
        border: none !important;
        border-radius: 16px !important;
        background: #ffffff;
        box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.05), 0 2px 4px -1px rgba(0, 0, 0, 0.03) !important;
        overflow: hidden;
    }

    .report-card-header {
        background: linear-gradient(135deg, #1e293b 0%, #334155 100%) !important;
        padding: 18px 24px !important;
        border-bottom: none !important;
    }

    .report-card-title {
        font-size: 1.1rem;
        font-weight: 600;
        letter-spacing: 0.3px;
        color: #ffffff !important;
    }

    /* Polished Input Configurations */
    .custom-filter-label {
        color: #475569;
        font-weight: 600 !important;
        font-size: 13px;
        margin-bottom: 6px;
    }

    .report-input-field {
        border: 1px solid #cbd5e1 !important;
        border-radius: 8px !important;
        height: 42px !important;
        font-size: 14px !important;
        color: #334155 !important;
        transition: all 0.2s ease;
        background-color: #ffffff;
    }

    .report-input-field:focus {
        border-color: #3b82f6 !important;
        box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.15) !important;
    }

    /* Premium Button Frameworks */
    .btn-action-generate {
        background: linear-gradient(135deg, #2563eb 0%, #1d4ed8 100%) !important;
        color: #ffffff !important;
        border: none !important;
        border-radius: 8px !important;
        height: 42px;
        font-weight: 600 !important;
        font-size: 14px !important;
        box-shadow: 0 4px 6px -1px rgba(37, 99, 235, 0.2) !important;
        transition: all 0.2s ease !important;
    }

    .btn-action-generate:hover {
        transform: translateY(-1px);
        box-shadow: 0 6px 12px -1px rgba(37, 99, 235, 0.3) !important;
        opacity: 0.95;
    }

    .btn-action-print {
        background: #10b981 !important;
        color: #ffffff !important;
        border: none !important;
        border-radius: 8px !important;
        font-weight: 600 !important;
        font-size: 14px !important;
        box-shadow: 0 4px 6px -1px rgba(16, 185, 129, 0.2) !important;
        transition: all 0.2s ease !important;
    }

    .btn-action-print:hover {
        background: #059669 !important;
        transform: translateY(-1px);
        box-shadow: 0 6px 12px -1px rgba(16, 185, 129, 0.3) !important;
    }

    /* Blank Slate Styling */
    .empty-state-box {
        background-color: #f8fafc;
        border: 2px dashed #e2e8f0;
        border-radius: 12px;
        max-width: 600px;
        margin: 0 auto;
    }
</style>

<div class="report-view-wrapper">
    <div class="container-fluid px-0">
        <div class="col-lg-12">
            
            <div class="card report-card mb-4">
                <div class="card-header report-card-header">
                    <span class="report-card-title">
                        <i class="fa fa-file-invoice mr-2 text-info"></i> 
                        Monthly Financial Statements & Collections Report
                    </span>
                </div>
                
                <div class="card-body p-4">
                    <div class="row justify-content-center d-print-none align-items-end">
                        <div class="col-md-4 mb-3 mb-md-0">
                            <div class="form-group mb-0">
                                <label class="custom-filter-label">Filter Building / Block:</label>
                                <select id="filter_building" class="custom-select report-input-field select2">
                                    <option value="all">All Buildings / Blocks</option>
                                    <?php 
                                    $b_qry = $conn->query("SELECT DISTINCT building FROM houses WHERE building IS NOT NULL AND building != '' ORDER BY building ASC");
                                    while($brow = $b_qry->fetch_assoc()):
                                    ?>
                                    <option value="<?php echo $brow['building'] ?>"><?php echo ucwords($brow['building']) ?></option>
                                    <?php endwhile; ?>
                                </select>
                            </div>
                        </div>
                        
                        <div class="col-md-4 mb-3 mb-md-0">
                            <div class="form-group mb-0">
                                <label class="custom-filter-label">Target Billing Month:</label>
                                <input type="month" name="month" id="month" value="<?php echo date('Y-m') ?>" class="form-control report-input-field">
                            </div>
                        </div>
                        
                        <div class="col-md-3">
                            <button class="btn btn-action-generate btn-block d-flex align-items-center justify-content-center" type="button" id="filter">
                                <i class="fa fa-filter mr-2"></i> Generate Report
                            </button>
                        </div>
                    </div>
                    
                    <hr class="d-print-none my-4" style="border-top: 1px solid #e2e8f0;">
                    
                    <div id="report-list" class="p-2">
                        <div class="text-center py-5 px-4 empty-state-box">
                            <div class="mb-3 d-inline-flex align-items-center justify-content-center" style="width: 70px; height: 70px; background: #f1f5f9; border-radius: 50%;">
                                <i class="fa fa-calculator fa-2x style-icon text-muted"></i>
                            </div>
                            <h5 class="font-weight-bold text-dark mb-2">No Statement Generated</h5>
                            <p class="text-muted small mb-0 mx-auto" style="max-width: 400px;">
                                Please choose a structural building criteria and target billing month above to compute matching system financial ledgers.
                            </p>
                        </div>
                    </div>
                </div>
                
                <div class="card-footer d-print-none bg-light p-3 border-top d-flex justify-content-end">
                    <button class="btn btn-action-print px-4 py-2 d-flex align-items-center" type="button" id="print">
                        <i class="fa fa-print mr-2"></i> Print Clean A4 Ledger
                    </button>
                </div>
            </div>

            <div class="card report-card col-md-12 mb-4 d-print-none">
                <div class="card-header report-card-header">
                    <span class="report-card-title">
                        <i class="fa fa-chart-bar mr-2 text-success"></i> 
                        Spreadsheet Rent Analysis Metrics
                    </span>
                </div>
                <div class="card-body p-4">
                    <div class="row align-items-end">
                        <div class="col-md-4">
                            <div class="form-group mb-0">
                                <label class="custom-filter-label">Select Analysis Month:</label>
                                <input type="month" id="filter_month" class="form-control report-input-field" value="<?php echo date('Y-m') ?>">
                            </div>
                        </div>
                        <div class="col-md-3">
                            <button class="btn btn-action-generate btn-block d-flex align-items-center justify-content-center" id="generate_analysis">
                                <i class="fa fa-sync mr-2"></i> Load Analysis
                            </button>
                        </div>
                    </div>
                    <hr class="my-4" style="border-top: 1px solid #e2e8f0;">
                    <div id="report_render_area" class="p-2">
                        <div class="text-center py-4 text-muted empty-state-box bg-light border p-4 rounded">
                            <p class="mb-0 small">Select a target period and click load to generate spreadsheet summary data.</p>
                        </div>
                    </div>
                </div>
            </div>
                     
        </div>
    </div>
</div>

<noscript id="print-styles">
    <style>
        @media print {
            @page {
                size: A4 portrait;
                margin: 10mm 8mm 10mm 8mm;
            }
            body {
                font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Arial, sans-serif;
                color: #000;
                background: #fff;
                font-size: 8.5pt;
                line-height: 1.25;
            }
            .print-header {
                text-align: center;
                margin-bottom: 15px;
                border-bottom: 2px solid #0f172a;
                padding-bottom: 8px;
            }
            .print-header h2 { margin: 0; font-size: 15pt; font-weight: 700; color: #0f172a; text-transform: uppercase; letter-spacing: 0.5px; }
            .print-header p { margin: 3px 0 0 0; color: #334155; font-size: 9.5pt; font-weight: 500; }
            
            .table-responsive { overflow: visible !important; }
            table {
                width: 100%;
                border-collapse: collapse;
                margin-top: 5px;
                page-break-inside: auto;
            }
            tr {
                page-break-inside: avoid;
                page-break-after: auto;
            }
            thead {
                display: table-header-group;
            }
            th {
                background-color: #f1f5f9 !important;
                -webkit-print-color-adjust: exact;
                print-color-adjust: exact;
                font-weight: 700;
                border: 1px solid #334155 !important;
                color: #0f172a !important;
                padding: 5px 6px;
                font-size: 8pt;
                text-transform: uppercase;
            }
            td {
                border: 1px solid #cbd5e1 !important;
                color: #000 !important;
                padding: 5px 6px;
                font-size: 8pt;
            }
            
            /* Class background color rules for column grouping context in print mode */
            .bg-primary { background-color: #eff6ff !important; -webkit-print-color-adjust: exact; print-color-adjust: exact; }
            .bg-info { background-color: #ecfeff !important; -webkit-print-color-adjust: exact; print-color-adjust: exact; }
            .bg-warning { background-color: #fefce8 !important; -webkit-print-color-adjust: exact; print-color-adjust: exact; }
            .bg-secondary { background-color: #f8fafc !important; -webkit-print-color-adjust: exact; print-color-adjust: exact; }
            
            .text-right { text-align: right !important; }
            .text-center { text-align: center !important; }
            .font-weight-bold { font-weight: 700 !important; }
            .text-monospace { font-family: SFMono-Regular, Menlo, Monaco, Consolas, monospace !important; }
            small.text-muted { color: #475569 !important; font-size: 7.5pt; display: block; margin-top: 2px; }
            hr { border-top: 1px solid #cbd5e1; }
        }
    </style>
</noscript>

<script>
    $(document).ready(function(){
        if($('.select2').length > 0){
            $('.select2').select2({ width: "100%" });
        }
    });

    $('#filter').click(function(){
        if(typeof start_load === "function") start_load();
        var month = $('#month').val();
        var building = $('#filter_building').val();
        
        $.ajax({
            url: 'ajax.php?action=get_report',
            method: 'POST',
            data: { month: month, building: building },
            success: function(resp){
                if(resp){
                    $('#report-list').html(resp);
                }
            },
            error: function(err){
                console.error("Report extraction processing fault:", err);
                alert_toast("An execution fault halted compilation.", "danger");
            },
            complete: function(){
                if(typeof end_load === "function") end_load();
            }
        });
    });

    $('#generate_analysis').click(function(){
        var targeted = $('#filter_month').val();
        $('#report_render_area').html(`
            <div class="text-center py-4">
                <div class="spinner-border text-primary mb-2" role="status"></div>
                <div class="text-muted small">Processing calculations... Please wait.</div>
            </div>
        `);
        
        $.ajax({
            url: 'ajax.php?action=get_rent_analysis',
            method: 'POST',
            data: { month: targeted },
            success: function(response){
                if(response) {
                    $('#report_render_area').html(response);
                }
            },
            error: function(err){
                console.error("Rent analysis compilation fault:", err);
                $('#report_render_area').html('<div class="alert alert-danger">Failed to process data calculations.</div>');
            }
        });
    });

    $('#print').click(function(){
        if($('#report-list').find('.empty-state-box').length > 0) {
            alert_toast("Cannot execute print arrays on blank parameters. Generate data loops first.", "danger");
            return false;
        }
        
        var _style = $('#print-styles').html();
        var _content = $('#report-list').html();
        var month_val = $('#month').val();
        
        // Format targeted header context display nicely (e.g. "May 2026")
        var dateObj = new Date(month_val + "-01");
        var formattedMonth = dateObj.toLocaleString('en-US', { month: 'long', year: 'numeric' });
        
        var nw = window.open("", "_blank", "width=1050,height=800");
        nw.document.write('<html><head><title>Monthly Financial Statements Ledger</title>');
        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="print-header">');
        nw.document.write('<h2>IMPALA HOUSE</h2>');
        nw.document.write('<p>Consolidated Statement of Accounts — Period Ending: ' + formattedMonth + '</p>');
        nw.document.write('</div>');
        nw.document.write('<div class="container-fluid px-0">');
        nw.document.write(_content);
        nw.document.write('</div>');
        nw.document.write('</body></html>');
        nw.document.close();
        
        setTimeout(function(){
            nw.print();
            setTimeout(function(){
                nw.close();
            }, 500);
        }, 600);
    });
</script>