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

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

$landlord_id = $_GET['landlord_id'] ?? '';

// Get landlords with wallet balances
$sql = "SELECT u.id, u.first_name, u.last_name, u.email, u.phone,
               COUNT(DISTINCT p.id) as property_count,
               COALESCE(SUM(rp.amount), 0) as total_collected,
               COALESCE(SUM(e.amount), 0) as total_expenses,
               (COALESCE(SUM(rp.amount), 0) - COALESCE(SUM(e.amount), 0)) as wallet_balance
        FROM users u
        LEFT JOIN properties p ON u.id = p.owner_id
        LEFT JOIN units un ON p.id = un.property_id
        LEFT JOIN leases l ON un.id = l.unit_id
        LEFT JOIN rent_payments rp ON l.id = rp.lease_id AND rp.payment_status = 'COMPLETED'
        LEFT JOIN expenses e ON p.id = e.property_id AND e.status = 'paid'
        WHERE u.role_id IN (SELECT id FROM roles WHERE role_name = 'Landlord')";

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

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

$sql .= " GROUP BY u.id ORDER BY u.first_name, u.last_name";

if (!empty($params)) {
    $stmt = $conn->prepare($sql);
    $stmt->bind_param($types, ...$params);
    $stmt->execute();
    $result = $stmt->get_result();
} else {
    $result = $conn->query($sql);
}
?>
<?php include 'layouts/main.php'; ?>

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

                    <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">Landlord Wallet Balances</h4>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-nowrap align-middle mb-0">
                                            <thead>
                                                <tr>
                                                    <th>Landlord</th>
                                                    <th>Contact</th>
                                                    <th>Properties</th>
                                                    <th>Total Collected</th>
                                                    <th>Total Expenses</th>
                                                    <th>Wallet Balance</th>
                                                    <th>Action</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if ($result && $result->num_rows > 0): ?>
                                                    <?php while($landlord = $result->fetch_assoc()): ?>
                                                        <tr>
                                                            <td>
                                                                <div class="d-flex align-items-center">
                                                                    <div class="avatar-xs me-2">
                                                                        <span class="avatar-title rounded-circle bg-soft-primary text-primary">
                                                                            <?php echo strtoupper(substr($landlord['first_name'], 0, 1) . substr($landlord['last_name'], 0, 1)); ?>
                                                                        </span>
                                                                    </div>
                                                                    <div>
                                                                        <h5 class="fs-14 mb-0">
                                                                            <?php echo htmlspecialchars($landlord['first_name'] . ' ' . $landlord['last_name']); ?>
                                                                        </h5>
                                                                    </div>
                                                                </div>
                                                            </td>
                                                            <td>
                                                                <div>
                                                                    <p class="mb-0"><?php echo htmlspecialchars($landlord['email']); ?></p>
                                                                    <small class="text-muted"><?php echo htmlspecialchars($landlord['phone']); ?></small>
                                                                </div>
                                                            </td>
                                                            <td>
                                                                <span class="badge bg-soft-info text-info">
                                                                    <?php echo $landlord['property_count'] ?? 0; ?> Properties
                                                                </span>
                                                            </td>
                                                            <td>
                                                                <span class="fw-semibold text-success">
                                                                    KES <?php echo number_format($landlord['total_collected'], 2); ?>
                                                                </span>
                                                            </td>
                                                            <td>
                                                                <span class="fw-semibold text-danger">
                                                                    KES <?php echo number_format($landlord['total_expenses'], 2); ?>
                                                                </span>
                                                            </td>
                                                            <td>
                                                                <span class="fw-semibold <?php echo $landlord['wallet_balance'] >= 0 ? 'text-success' : 'text-danger'; ?>">
                                                                    KES <?php echo number_format($landlord['wallet_balance'], 2); ?>
                                                                </span>
                                                            </td>
                                                            <td>
                                                                <div class="dropdown">
                                                                    <button class="btn btn-soft-secondary btn-sm dropdown-toggle" 
                                                                            type="button" data-bs-toggle="dropdown">
                                                                        Actions
                                                                    </button>
                                                                    <ul class="dropdown-menu dropdown-menu-end">
                                                                        <li>
                                                                            <a class="dropdown-item" href="landlord_wallet_details.php?id=<?php echo $landlord['id']; ?>">
                                                                                <i class="ri-eye-line align-bottom me-2 text-muted"></i>View Details
                                                                            </a>
                                                                        </li>
                                                                        <li>
                                                                            <a class="dropdown-item" href="process_withdrawal.php?landlord_id=<?php echo $landlord['id']; ?>">
                                                                                <i class="ri-money-dollar-circle-line align-bottom me-2 text-muted"></i>Process Withdrawal
                                                                            </a>
                                                                        </li>
                                                                    </ul>
                                                                </div>
                                                            </td>
                                                        </tr>
                                                    <?php endwhile; ?>
                                                <?php else: ?>
                                                    <tr>
                                                        <td colspan="7" class="text-center py-4">
                                                            <div class="text-muted">
                                                                <i class="ri-inbox-line fs-48"></i>
                                                                <p class="mt-2">No landlords 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>
