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

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

// Check if user is landlord
$user_role = $_SESSION['role_name'] ?? '';
if ($user_role !== 'Landlord') {
    header('Location: index.php');
    exit();
}

$user_id = $_SESSION['user_id'];

// Get user details
$sql_user = "SELECT * FROM users WHERE id = ?";
$stmt_user = $conn->prepare($sql_user);
$stmt_user->bind_param("i", $user_id);
$stmt_user->execute();
$result_user = $stmt_user->get_result();
$user = $result_user->fetch_assoc();

// Total Properties
$sql_properties = "SELECT COUNT(*) as total FROM properties WHERE owner_id = ?";
$stmt_prop = $conn->prepare($sql_properties);
$stmt_prop->bind_param("i", $user_id);
$stmt_prop->execute();
$result_prop = $stmt_prop->get_result();
$total_properties = $result_prop->fetch_assoc()['total'] ?? 0;

// Total Units
$sql_units = "SELECT COUNT(DISTINCT u.id) as total 
              FROM units u
              JOIN properties p ON u.property_id = p.id
              WHERE p.owner_id = ?";
$stmt_units = $conn->prepare($sql_units);
$stmt_units->bind_param("i", $user_id);
$stmt_units->execute();
$result_units = $stmt_units->get_result();
$total_units = $result_units->fetch_assoc()['total'] ?? 0;

// Occupied Units
$sql_occupied = "SELECT COUNT(DISTINCT u.id) as total 
                FROM units u
                JOIN properties p ON u.property_id = p.id
                WHERE p.owner_id = ? AND u.status = 'occupied'";
$stmt_occupied = $conn->prepare($sql_occupied);
$stmt_occupied->bind_param("i", $user_id);
$stmt_occupied->execute();
$result_occupied = $stmt_occupied->get_result();
$occupied_units = $result_occupied->fetch_assoc()['total'] ?? 0;

$occupancy_rate = $total_units > 0 ? round(($occupied_units / $total_units) * 100, 1) : 0;

// Monthly Rental Income (Current Month)
$current_month = date('Y-m');
$sql_income = "SELECT SUM(rp.amount) as total 
               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
               WHERE p.owner_id = ? 
               AND rp.payment_status = 'COMPLETED'
               AND DATE_FORMAT(rp.payment_date, '%Y-%m') = ?";
$stmt_income = $conn->prepare($sql_income);
$stmt_income->bind_param("is", $user_id, $current_month);
$stmt_income->execute();
$result_income = $stmt_income->get_result();
$monthly_income = $result_income->fetch_assoc()['total'] ?? 0;

// Total Expenses (Current Month)
$sql_expenses = "SELECT SUM(e.amount) as total 
                 FROM expenses e
                 JOIN properties p ON e.property_id = p.id
                 WHERE p.owner_id = ? 
                 AND e.status = 'paid'
                 AND DATE_FORMAT(e.incurred_date, '%Y-%m') = ?";
$stmt_exp = $conn->prepare($sql_expenses);
$stmt_exp->bind_param("is", $user_id, $current_month);
$stmt_exp->execute();
$result_exp = $stmt_exp->get_result();
$monthly_expenses = $result_exp->fetch_assoc()['total'] ?? 0;

// Wallet Balance
$sql_wallet = "SELECT 
                    COALESCE(SUM(rp.amount), 0) as total_collected,
                    COALESCE(SUM(e.amount), 0) as total_expenses
                FROM properties p
                LEFT JOIN units u ON p.id = u.property_id
                LEFT JOIN leases l ON u.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 p.owner_id = ?";
$stmt_wallet = $conn->prepare($sql_wallet);
$stmt_wallet->bind_param("i", $user_id);
$stmt_wallet->execute();
$result_wallet = $stmt_wallet->get_result();
$wallet = $result_wallet->fetch_assoc();
$wallet_balance = ($wallet['total_collected'] ?? 0) - ($wallet['total_expenses'] ?? 0);

// Recent Payments
$sql_recent_payments = "SELECT rp.*, u.unit_number, p.name as property_name
                        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
                        WHERE p.owner_id = ? AND rp.payment_status = 'COMPLETED'
                        ORDER BY rp.payment_date DESC LIMIT 5";
$stmt_payments = $conn->prepare($sql_recent_payments);
$stmt_payments->bind_param("i", $user_id);
$stmt_payments->execute();
$result_payments = $stmt_payments->get_result();

// Recent Expenses
$sql_recent_expenses = "SELECT e.*, p.name as property_name
                        FROM expenses e
                        JOIN properties p ON e.property_id = p.id
                        WHERE p.owner_id = ? AND e.status = 'paid'
                        ORDER BY e.incurred_date DESC LIMIT 5";
$stmt_expenses = $conn->prepare($sql_recent_expenses);
$stmt_expenses->bind_param("i", $user_id);
$stmt_expenses->execute();
$result_expenses = $stmt_expenses->get_result();
?>
<?php include 'layouts/main.php'; ?>

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

                    <div class="row">
                        <div class="col-xl-3 col-md-6">
                            <div class="card card-animate">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-grow-1 overflow-hidden">
                                            <p class="text-uppercase fw-medium text-muted text-truncate mb-0">My Properties</p>
                                        </div>
                                        <div class="flex-shrink-0">
                                            <div class="avatar-sm">
                                                <span class="avatar-title bg-soft-primary rounded-circle fs-3">
                                                    <i class="ri-building-line text-primary"></i>
                                                </span>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="d-flex align-items-end justify-content-between mt-4">
                                        <div>
                                            <h4 class="fs-22 fw-semibold ff-secondary mb-4">
                                                <?php echo number_format($total_properties); ?>
                                            </h4>
                                            <a href="my_properties.php" class="text-decoration-underline">View all properties</a>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-xl-3 col-md-6">
                            <div class="card card-animate">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-grow-1 overflow-hidden">
                                            <p class="text-uppercase fw-medium text-muted text-truncate mb-0">Occupancy Rate</p>
                                        </div>
                                        <div class="flex-shrink-0">
                                            <div class="avatar-sm">
                                                <span class="avatar-title bg-soft-success rounded-circle fs-3">
                                                    <i class="ri-home-4-line text-success"></i>
                                                </span>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="d-flex align-items-end justify-content-between mt-4">
                                        <div>
                                            <h4 class="fs-22 fw-semibold ff-secondary mb-4">
                                                <?php echo $occupancy_rate; ?>%
                                            </h4>
                                            <span class="badge bg-soft-success text-success mb-0">
                                                <?php echo $occupied_units; ?> / <?php echo $total_units; ?> units
                                            </span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-xl-3 col-md-6">
                            <div class="card card-animate">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-grow-1 overflow-hidden">
                                            <p class="text-uppercase fw-medium text-muted text-truncate mb-0">Monthly Income</p>
                                        </div>
                                        <div class="flex-shrink-0">
                                            <div class="avatar-sm">
                                                <span class="avatar-title bg-soft-info rounded-circle fs-3">
                                                    <i class="ri-money-dollar-circle-line text-info"></i>
                                                </span>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="d-flex align-items-end justify-content-between mt-4">
                                        <div>
                                            <h4 class="fs-22 fw-semibold ff-secondary mb-4">
                                                KES <?php echo number_format($monthly_income, 0); ?>
                                            </h4>
                                            <a href="my_rental_income.php" class="text-decoration-underline">View income</a>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-xl-3 col-md-6">
                            <div class="card card-animate">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-grow-1 overflow-hidden">
                                            <p class="text-uppercase fw-medium text-muted text-truncate mb-0">Wallet Balance</p>
                                        </div>
                                        <div class="flex-shrink-0">
                                            <div class="avatar-sm">
                                                <span class="avatar-title bg-soft-warning rounded-circle fs-3">
                                                    <i class="ri-wallet-line text-warning"></i>
                                                </span>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="d-flex align-items-end justify-content-between mt-4">
                                        <div>
                                            <h4 class="fs-22 fw-semibold ff-secondary mb-4">
                                                KES <?php echo number_format($wallet_balance, 0); ?>
                                            </h4>
                                            <a href="my_wallet.php" class="text-decoration-underline">View wallet</a>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-xl-6">
                            <div class="card">
                                <div class="card-header align-items-center d-flex">
                                    <h4 class="card-title mb-0 flex-grow-1">Recent Payments</h4>
                                    <a href="my_rental_income.php" class="btn btn-soft-primary btn-sm">View All</a>
                                </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>Amount</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if ($result_payments && $result_payments->num_rows > 0): ?>
                                                    <?php while($payment = $result_payments->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>
                                                                <span class="fw-semibold text-success">KES <?php echo number_format($payment['amount'], 2); ?></span>
                                                            </td>
                                                        </tr>
                                                    <?php endwhile; ?>
                                                <?php else: ?>
                                                    <tr>
                                                        <td colspan="3" class="text-center py-4">
                                                            <div class="text-muted">No payments found</div>
                                                        </td>
                                                    </tr>
                                                <?php endif; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-xl-6">
                            <div class="card">
                                <div class="card-header align-items-center d-flex">
                                    <h4 class="card-title mb-0 flex-grow-1">Recent Expenses</h4>
                                    <a href="my_property_expenses.php" class="btn btn-soft-primary btn-sm">View All</a>
                                </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</th>
                                                    <th>Category</th>
                                                    <th>Amount</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if ($result_expenses && $result_expenses->num_rows > 0): ?>
                                                    <?php while($expense = $result_expenses->fetch_assoc()): ?>
                                                        <tr>
                                                            <td><?php echo date('M d, Y', strtotime($expense['incurred_date'])); ?></td>
                                                            <td><?php echo htmlspecialchars($expense['property_name']); ?></td>
                                                            <td>
                                                                <span class="badge bg-soft-info"><?php echo htmlspecialchars($expense['category']); ?></span>
                                                            </td>
                                                            <td>
                                                                <span class="fw-semibold text-danger">KES <?php echo number_format($expense['amount'], 2); ?></span>
                                                            </td>
                                                        </tr>
                                                    <?php endwhile; ?>
                                                <?php else: ?>
                                                    <tr>
                                                        <td colspan="4" class="text-center py-4">
                                                            <div class="text-muted">No expenses found</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>
