<?php
session_start();
include 'layouts/dbconn.php';

if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

$property_id = $_GET['property_id'] ?? '';
$month = $_GET['month'] ?? date('Y-m');

$sql = "SELECT l.*, u.unit_number, p.property_name, p.property_code,
               t.first_name, t.last_name, t.email, t.phone,
               COALESCE(SUM(rp.amount), 0) as paid_amount,
               (l.rent_amount - COALESCE(SUM(rp.amount), 0)) as outstanding
        FROM leases l
        JOIN units u ON l.unit_id = u.unit_id
        JOIN properties p ON u.property_id = p.property_id
        JOIN lease_tenants lt ON l.lease_id = lt.lease_id AND lt.is_primary = 1
        JOIN tenants t ON lt.tenant_id = t.tenant_id
        LEFT JOIN rent_payments rp ON l.lease_id = rp.lease_id 
            AND rp.payment_status = 'COMPLETED'
            AND DATE_FORMAT(rp.payment_date, '%Y-%m') = ?
        WHERE l.lease_status = 'ACTIVE'";

$params = [$month];
$types = 's';

if (!empty($property_id)) {
    $sql .= " AND p.property_id = ?";
    $params[] = $property_id;
    $types .= 'i';
}

$sql .= " GROUP BY l.lease_id ORDER BY p.property_name, u.unit_number";

// Get properties for filter
$sql_properties = "SELECT * FROM properties ORDER BY property_name";
$result_properties = $conn->query($sql_properties);

$stmt = $conn->prepare($sql);
$stmt->bind_param($types, ...$params);
$stmt->execute();
$result = $stmt->get_result();

// Calculate totals
$total_expected = 0;
$total_collected = 0;
$total_outstanding = 0;
?>
<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Rent Roll')); ?>
    <?php include 'layouts/head-css.php'; ?>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>

        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'Financials', 'title' => 'Rent Roll')); ?>

                    <div class="row mb-3">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-body">
                                    <form method="GET" class="row g-3">
                                        <div class="col-md-4">
                                            <label class="form-label">Property</label>
                                            <select class="form-select" name="property_id">
                                                <option value="">All Properties</option>
                                                <?php while($prop = $result_properties->fetch_assoc()): ?>
                                                    <option value="<?php echo $prop['property_id']; ?>" 
                                                            <?php echo $property_id == $prop['property_id'] ? 'selected' : ''; ?>>
                                                        <?php echo htmlspecialchars($prop['property_name']); ?>
                                                    </option>
                                                <?php endwhile; ?>
                                            </select>
                                        </div>
                                        <div class="col-md-3">
                                            <label class="form-label">Month</label>
                                            <input type="month" class="form-control" name="month" 
                                                   value="<?php echo htmlspecialchars($month); ?>">
                                        </div>
                                        <div class="col-md-2">
                                            <label class="form-label">&nbsp;</label>
                                            <div>
                                                <button type="submit" class="btn btn-primary w-100">
                                                    <i class="ri-search-line me-1"></i>Filter
                                                </button>
                                            </div>
                                        </div>
                                        <div class="col-md-3">
                                            <label class="form-label">&nbsp;</label>
                                            <div>
                                                <button type="button" class="btn btn-success w-100" onclick="exportRentRoll()">
                                                    <i class="ri-download-line me-1"></i>Export
                                                </button>
                                            </div>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-header align-items-center d-flex">
                                    <h4 class="card-title mb-0 flex-grow-1">Rent Roll - <?php echo date('F Y', strtotime($month . '-01')); ?></h4>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-nowrap align-middle mb-0">
                                            <thead>
                                                <tr>
                                                    <th>Property</th>
                                                    <th>Unit</th>
                                                    <th>Tenant</th>
                                                    <th>Contact</th>
                                                    <th>Expected Rent</th>
                                                    <th>Collected</th>
                                                    <th>Outstanding</th>
                                                    <th>Status</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if ($result && $result->num_rows > 0): ?>
                                                    <?php while($lease = $result->fetch_assoc()): 
                                                        $total_expected += $lease['rent_amount'];
                                                        $total_collected += $lease['paid_amount'];
                                                        $total_outstanding += $lease['outstanding'];
                                                    ?>
                                                        <tr>
                                                            <td>
                                                                <div>
                                                                    <h5 class="fs-14 mb-0"><?php echo htmlspecialchars($lease['property_name']); ?></h5>
                                                                    <p class="text-muted mb-0 small"><?php echo htmlspecialchars($lease['property_code'] ?? ''); ?></p>
                                                                </div>
                                                            </td>
                                                            <td>
                                                                <span class="fw-semibold"><?php echo htmlspecialchars($lease['unit_number']); ?></span>
                                                            </td>
                                                            <td>
                                                                <div>
                                                                    <h5 class="fs-14 mb-0">
                                                                        <?php echo htmlspecialchars($lease['first_name'] . ' ' . $lease['last_name']); ?>
                                                                    </h5>
                                                                </div>
                                                            </td>
                                                            <td>
                                                                <div>
                                                                    <p class="mb-0"><?php echo htmlspecialchars($lease['email']); ?></p>
                                                                    <small class="text-muted"><?php echo htmlspecialchars($lease['phone']); ?></small>
                                                                </div>
                                                            </td>
                                                            <td>
                                                                <span class="fw-semibold">KES <?php echo number_format($lease['rent_amount'], 2); ?></span>
                                                            </td>
                                                            <td>
                                                                <span class="fw-semibold text-success">KES <?php echo number_format($lease['paid_amount'], 2); ?></span>
                                                            </td>
                                                            <td>
                                                                <span class="fw-semibold <?php echo $lease['outstanding'] > 0 ? 'text-danger' : 'text-success'; ?>">
                                                                    KES <?php echo number_format($lease['outstanding'], 2); ?>
                                                                </span>
                                                            </td>
                                                            <td>
                                                                <?php if ($lease['outstanding'] <= 0): ?>
                                                                    <span class="badge bg-soft-success text-success">Paid</span>
                                                                <?php elseif ($lease['paid_amount'] > 0): ?>
                                                                    <span class="badge bg-soft-warning text-warning">Partial</span>
                                                                <?php else: ?>
                                                                    <span class="badge bg-soft-danger text-danger">Unpaid</span>
                                                                <?php endif; ?>
                                                            </td>
                                                        </tr>
                                                    <?php endwhile; ?>
                                                    <tr class="table-light">
                                                        <td colspan="4" class="text-end fw-bold">TOTALS:</td>
                                                        <td class="fw-bold">KES <?php echo number_format($total_expected, 2); ?></td>
                                                        <td class="fw-bold text-success">KES <?php echo number_format($total_collected, 2); ?></td>
                                                        <td class="fw-bold text-danger">KES <?php echo number_format($total_outstanding, 2); ?></td>
                                                        <td>
                                                            <?php 
                                                            $collection_rate = $total_expected > 0 ? ($total_collected / $total_expected) * 100 : 0;
                                                            ?>
                                                            <span class="badge bg-soft-info text-info">
                                                                <?php echo number_format($collection_rate, 1); ?>% Collected
                                                            </span>
                                                        </td>
                                                    </tr>
                                                <?php else: ?>
                                                    <tr>
                                                        <td colspan="8" class="text-center py-4">
                                                            <div class="text-muted">
                                                                <i class="ri-inbox-line fs-48"></i>
                                                                <p class="mt-2">No active leases found</p>
                                                            </div>
                                                        </td>
                                                    </tr>
                                                <?php endif; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script>
        function exportRentRoll() {
            window.location.href = 'export_rent_roll.php?property_id=<?php echo $property_id; ?>&month=<?php echo $month; ?>';
        }
    </script>
</body>
</html>
