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

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

$user_id = $_SESSION['user_id'];
$property_id = $_GET['property_id'] ?? '';
$start_date = $_GET['start_date'] ?? date('Y-m-01');
$end_date = $_GET['end_date'] ?? date('Y-m-t');

$sql = "SELECT rp.*, l.lease_code, u.unit_number, p.name as property_name,
               t.first_name, t.last_name, i.invoice_number
        FROM rent_payments rp
        JOIN leases l ON rp.lease_id = l.id
        JOIN units u ON l.unit_id = u.id
        JOIN properties p ON u.property_id = p.id
        JOIN lease_tenants lt ON l.id = lt.lease_id AND lt.is_primary = 1
        JOIN tenants t ON lt.tenant_id = t.tenant_id
        LEFT JOIN invoices i ON rp.invoice_id = i.id
        WHERE p.owner_id = ?
        AND rp.payment_status = 'COMPLETED'
        AND rp.payment_date BETWEEN ? AND ?";

$params = [$user_id, $start_date, $end_date];
$types = 'iss';

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

$sql .= " ORDER BY rp.payment_date DESC";

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

// Calculate totals
$total_income = 0;
while($row = $result->fetch_assoc()) {
    $total_income += $row['amount'];
}
$result->data_seek(0);

// Get properties for filter
$sql_properties = "SELECT * FROM properties WHERE owner_id = ? ORDER BY name";
$stmt_prop = $conn->prepare($sql_properties);
$stmt_prop->bind_param("i", $user_id);
$stmt_prop->execute();
$result_properties = $stmt_prop->get_result();
?>
<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Rental Income')); ?>
    <?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' => 'Rental Income')); ?>

                    <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-3">
                                            <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['id']; ?>" 
                                                            <?php echo $property_id == $prop['id'] ? 'selected' : ''; ?>>
                                                        <?php echo htmlspecialchars($prop['name']); ?>
                                                    </option>
                                                <?php endwhile; ?>
                                            </select>
                                        </div>
                                        <div class="col-md-3">
                                            <label class="form-label">Start Date</label>
                                            <input type="date" class="form-control" name="start_date" 
                                                   value="<?php echo htmlspecialchars($start_date); ?>">
                                        </div>
                                        <div class="col-md-3">
                                            <label class="form-label">End Date</label>
                                            <input type="date" class="form-control" name="end_date" 
                                                   value="<?php echo htmlspecialchars($end_date); ?>">
                                        </div>
                                        <div class="col-md-3">
                                            <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>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="row mb-3">
                        <div class="col-12">
                            <div class="card bg-soft-success">
                                <div class="card-body text-center">
                                    <h6 class="text-muted mb-2">Total Rental Income</h6>
                                    <h2 class="text-success mb-0">KES <?php echo number_format($total_income, 2); ?></h2>
                                    <small class="text-muted">
                                        Period: <?php echo date('M d, Y', strtotime($start_date)); ?> to <?php echo date('M d, Y', strtotime($end_date)); ?>
                                    </small>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">Payment History</h4>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-nowrap align-middle mb-0">
                                            <thead>
                                                <tr>
                                                    <th>Date</th>
                                                    <th>Property/Unit</th>
                                                    <th>Tenant</th>
                                                    <th>Invoice</th>
                                                    <th>Amount</th>
                                                    <th>Method</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if ($result && $result->num_rows > 0): ?>
                                                    <?php while($payment = $result->fetch_assoc()): ?>
                                                        <tr>
                                                            <td><?php echo date('M d, Y', strtotime($payment['payment_date'])); ?></td>
                                                            <td>
                                                                <div>
                                                                    <h5 class="fs-14 mb-0"><?php echo htmlspecialchars($payment['property_name']); ?></h5>
                                                                    <p class="text-muted mb-0 small">Unit: <?php echo htmlspecialchars($payment['unit_number']); ?></p>
                                                                </div>
                                                            </td>
                                                            <td>
                                                                <?php echo htmlspecialchars($payment['first_name'] . ' ' . $payment['last_name']); ?>
                                                            </td>
                                                            <td>
                                                                <a href="invoice_details.php?id=<?php echo $payment['invoice_id']; ?>" class="text-primary">
                                                                    <?php echo htmlspecialchars($payment['invoice_number'] ?? 'N/A'); ?>
                                                                </a>
                                                            </td>
                                                            <td>
                                                                <span class="fw-semibold">KES <?php echo number_format($payment['amount'], 2); ?></span>
                                                            </td>
                                                            <td>
                                                                <span class="badge bg-soft-info text-info">
                                                                    <?php echo htmlspecialchars($payment['payment_method']); ?>
                                                                </span>
                                                            </td>
                                                        </tr>
                                                    <?php endwhile; ?>
                                                <?php else: ?>
                                                    <tr>
                                                        <td colspan="6" class="text-center py-4">
                                                            <div class="text-muted">
                                                                <i class="ri-inbox-line fs-48"></i>
                                                                <p class="mt-2">No payments 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'; ?>
</body>
</html>
