<?php include 'db_connect.php' ?>

<?php 
if(!isset($_GET['id']) || intval($_GET['id']) <= 0) {
    echo "<div class='alert alert-danger m-2'>Error: Invalid or missing Tenant identification reference parameter.</div>";
    exit;
}
$id = intval($_GET['id']);

// 1. Pull the core tenant configuration records
$tenants = $conn->query("SELECT t.*, concat(t.lastname,', ',t.firstname,' ',t.middlename) as name, h.house_no, h.price, h.building FROM tenants t inner join houses h on h.id = t.house_id where t.id = {$id} ");

if($tenants->num_rows <= 0) {
    echo "<div class='alert alert-danger m-2'>Error: Tenant records could not be found inside the system database ledger.</div>";
    exit;
}

foreach($tenants->fetch_array() as $k => $v){
    if(!is_numeric($k)){
        $$k = $v;
    }
}

// 2. Accurate DateTime calculation matching tenants.php
$date_in_dt = new DateTime($date_in);
$today = new DateTime(date('Y-m-d'));
$interval = $date_in_dt->diff($today);
$months_stayed = ($interval->y * 12) + $interval->m;

// Enforce the 3-month baseline period condition
$billing_months = ($months_stayed < 3) ? 3 : $months_stayed;

// 3. Gather Utilities aggregation logs
$utils = $conn->query("SELECT SUM(amount) as utotal FROM utility_bills where tenant_id = {$id}");
$u_total = $utils->num_rows > 0 ? $utils->fetch_array()['utotal'] : 0;
$u_total = $u_total > 0 ? $u_total : 0;

// 4. Group all gross financial components together
$total_rent = $price * $billing_months;
$total_parking = $parking_monthly * $billing_months;
$payable = $total_rent + $total_parking + $u_total + $security_deposit;

// 5. Total historical payments made
$paid_query = $conn->query("SELECT SUM(amount) as paid FROM payments where tenant_id =".$id);
$paid = $paid_query->num_rows > 0 ? $paid_query->fetch_array()['paid'] : 0;

// Determine final outstanding balance
$outstanding = $payable - $paid;
?>

<div class="container-fluid" id="printable-statement-zone">
    <div class="row mb-3 filter-action-row">
        <div class="col-12 text-right">
            <button class="btn btn-success btn-sm font-weight-bold px-4 shadow-sm" type="button" id="print-statement-btn">
                <i class="fa fa-print mr-1"></i> Print Account Statement
            </button>
        </div>
    </div>

    <div class="print-only-header border-bottom pb-2 mb-4">
        <div class="row align-items-center">
            <div class="col-7">
                <h3 class="mb-0 font-weight-bold tracking-tight text-uppercase text-dark">Tenant Invoice & Account Statement</h3>
                <p class="text-muted small mb-0">Generated Real Estate Portfolio Management Node Ledger</p>
            </div>
            <div class="col-5 text-right text-muted small">
                <p class="mb-0">Run Timestamp: <b><?php echo date('M d, Y h:i A') ?></b></p>
                <p class="mb-0">Status: <span class="badge <?php echo $outstanding > 0 ? 'badge-danger' : 'badge-success' ?>"><?php echo $outstanding > 0 ? 'Pending Arrears' : 'Settled' ?></span></p>
            </div>
        </div>
    </div>

    <div class="col-lg-12 px-0">
        <div class="row">
            <div class="col-md-5 statement-summary-column">
                <div id="details" class="alert alert-light border card-shadow-sm-print bg-white p-3 rounded">
                    <large class="font-weight-bold text-dark text-uppercase tracking-wider small d-block mb-2">
                        <i class="fa fa-file-invoice-dollar mr-1 text-primary"></i> Account Summary Statement
                    </large>
                    <hr class="mt-1 mb-2">
                    <p class="mb-1">Tenant Name: <b class="text-dark"><?php echo ucwords($name) ?></b></p>
                    <p class="mb-1">House / Unit Assignment: <b>Unit <?php echo $house_no ?> — <?php echo isset($building) ? ucwords($building) : 'Main Block' ?></b></p>
                    <p class="mb-1">Lease Activation Date: <b><?php echo date("M d, Y", strtotime($date_in)) ?></b></p>
                    <p class="mb-1">Calculated Bill Months: <b><?php echo $billing_months ?> <?php echo ($months_stayed < 3) ? '<span class="badge badge-warning pb-1" style="font-size:10px;">Initial Minimum Period</span>' : '' ?></b></p>
                    
                    <hr class="my-2 border-dashed">
                    
                    <p class="d-flex justify-content-between mb-1 text-secondary"><span>Accumulated Baseline Rent:</span> <b class="text-monospace"><?php echo number_format($total_rent,2) ?></b></p>
                    <p class="d-flex justify-content-between mb-1 text-secondary"><span>Escrow Security Deposit:</span> <b class="text-monospace"><?php echo number_format($security_deposit,2) ?></b></p>
                    <p class="d-flex justify-content-between mb-1 text-secondary"><span>Parking Allocations Total:</span> <b class="text-monospace"><?php echo number_format($total_parking,2) ?></b></p>
                    <p class="d-flex justify-content-between mb-2 text-secondary"><span>Utilities Consumption Total:</span> <b class="text-info text-monospace"><?php echo number_format($u_total,2) ?></b></p>
                    
                    <hr class="my-2 border-double">
                    
                    <p class="d-flex justify-content-between mb-1 text-dark font-weight-medium"><span>Gross Calculated Charges:</span> <span class="text-monospace"><?php echo number_format($payable,2) ?></span></p>
                    <p class="d-flex justify-content-between mb-1 text-success font-weight-medium"><span>Aggregate Remitted Paid:</span> <span class="text-monospace">- <?php echo number_format($paid,2) ?></span></p>
                    <p class="d-flex justify-content-between align-items-center mt-2 pt-2 border-top">
                        <span class="font-weight-bold text-uppercase text-secondary small">Outstanding Balance (KES):</span> 
                        <b class="text-monospace font-weight-bold h5 mb-0 <?php echo $outstanding > 0 ? 'text-danger' : 'text-success' ?>">
                            <?php echo number_format($outstanding,2) ?>
                        </b>
                    </p>
                </div>
            </div>
            
            <div class="col-md-7 statement-ledger-column">
                <large class="font-weight-bold text-dark text-uppercase tracking-wider small d-block mb-2">
                    <i class="fa fa-history mr-1 text-secondary"></i> Payment History Ledger
                </large>
                <hr class="mt-1 mb-2">
                <table class="table table-condensed table-striped table-bordered font-size-sm-print bg-white">
                    <thead class="bg-light">
                        <tr>
                            <th class="py-2">Transaction Date</th>
                            <th class="py-2">Invoice / Ref Reference String</th>
                            <th class="text-right py-2">Amount Remitted (KES)</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php 
                        $payments = $conn->query("SELECT * FROM payments where tenant_id = $id order by date_created asc, id asc");
                        if($payments->num_rows > 0):
                            while($row=$payments->fetch_assoc()):
                        ?>
                        <tr>
                            <td class="align-middle"><?php echo date("M d, Y h:i A", strtotime($row['date_created'])) ?></td>
                            <td class="align-middle text-monospace font-weight-bold text-uppercase"><?php echo $row['invoice'] ?></td>
                            <td class='text-right align-middle font-weight-bold text-success text-monospace'><?php echo number_format($row['amount'],2) ?></td>
                        </tr>
                        <?php endwhile; ?>
                        <?php else: ?>
                        <tr>
                            <td colspan="3" class="text-center text-muted py-4 font-italic">No validated payment transaction processing data records cleared for this active lease ledger space.</td>
                        </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
                
                <div class="print-only-footer row mt-5 pt-4 text-center">
                    <div class="col-5 offset-7">
                        <div class="border-top pt-2 text-muted font-weight-medium small text-uppercase">
                            System Financial Audit Authorization
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
    /* Global View Layout Framework Adjustments */
    #details p {
        margin: unset;
        padding: unset;
        line-height: 1.6em;
        font-size: 0.9rem;
    }
    td, th {
        padding: 8px 10px !important;
        vertical-align: middle !important;
    }
    .text-monospace {
        font-family: SFMono-Regular, Menlo, Monaco, Consolas, monospace !important;
    }
    .border-dashed { border-top: 1px dashed #dee2e6 !important; }
    .border-double { border-top: 3px double #dee2e6 !important; }
    .font-weight-medium { font-weight: 500; }
    .tracking-wider { letter-spacing: 0.05em; }
    .print-only-header, .print-only-footer { display: none !important; }

    /* Custom CSS Print Engine Adjustments for Clean A4 Outputs */
    @media print {
        body * {
            visibility: hidden;
            background: transparent !important;
            color: #000000 !important;
        }
        #printable-statement-zone, #printable-statement-zone * {
            visibility: visible;
        }
        #printable-statement-zone {
            position: absolute;
            left: 0;
            top: 0;
            width: 100% !important;
            padding: 0 !important;
            margin: 0 !important;
        }
        .filter-action-row {
            display: none !important;
        }
        .print-only-header, .print-only-footer {
            display: flex !important;
        }
        .print-only-footer {
            display: block !important;
            margin-top: 60px !important;
        }
        .statement-summary-column {
            width: 41.666667% !important;
            float: left;
        }
        .statement-ledger-column {
            width: 58.333333% !important;
            float: left;
            padding-left: 20px;
        }
        .card-shadow-sm-print {
            border: 1px solid #c8ced3 !important;
            box-shadow: none !important;
        }
        .font-size-sm-print {
            font-size: 12px !important;
        }
        .badge {
            border: 1px solid #000000 !important;
            color: #000000 !important;
            font-weight: bold !important;
        }
    }
</style>

<script>
    $(document).ready(function(){
        // Handles routing actions safely via asynchronous printing window abstraction sandboxes
        $('#print-statement-btn').click(function(){
            var printContents = $('#printable-statement-zone').html();
            
            // Generate clean sandbox browser context instance frame window
            var printWindow = window.open('', '_blank', 'width=1000,height=750,scrollbars=yes');
            printWindow.document.write('<html><head><title>Tenant Ledger Account Statement Report Summary</title>');
            
            // Mount Bootstrap UI rules and visual layout styles down into sandbox DOM matrix 
            printWindow.document.write('<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css">');
            printWindow.document.write('<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">');
            printWindow.document.write('<style>' + $('style').html() + ' .filter-action-row { display:none !important; }</style>');
            
            printWindow.document.write('</head><body class="bg-white p-4">');
            printWindow.document.write(printContents);
            printWindow.document.write('</body></html>');
            printWindow.document.close();
            
            // Wait for dependencies to resolve across layout nodes before triggering hardware drivers
            setTimeout(function(){
                printWindow.focus();
                printWindow.print();
                setTimeout(function(){
                    printWindow.close();
                }, 400);
            }, 600);
        });
    });
</script>