<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

session_start();
require_once 'db_connect.php';

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

$user_id = $_SESSION['user_id'];

// Get user role
$stmt = $conn_rbe->prepare("SELECT role FROM rbe_roles WHERE user_id = ? LIMIT 1");
$stmt->execute([$user_id]);
$role = $stmt->fetchColumn();

if (!in_array($role, ['admin', 'landlord'])) {
    exit('Access denied.');
}

$is_admin = $role === 'admin';
$filter_landlord_id = $is_admin ? intval($_GET['filter_landlord_id'] ?? 0) : $_SESSION['user_id'];


// Handle Add Tenant
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_tenant'])) {
    $fullname = trim($_POST['fullname'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $landlord_id = $is_admin ? intval($_POST['landlord_id'] ?? 0) : $user_id;

    if ($fullname && $email && $landlord_id) {
        $stmt = $conn_rbe->prepare("SELECT id FROM rbe_users WHERE email = ? LIMIT 1");
        $stmt->execute([$email]);
        $new_user_id = (int)($stmt->fetchColumn() ?: 0);

        if ($new_user_id > 0) {
            $stmt = $conn_rbe->prepare("UPDATE rbe_users SET fullname=?, phone=?, is_active=1, is_deleted=0 WHERE id=?");
            $stmt->execute([$fullname, $phone, $new_user_id]);
        } else {
            $stmt = $conn_rbe->prepare("INSERT INTO rbe_users (fullname, email, phone, must_set_password, is_active, is_deleted) VALUES (?, ?, ?, 1, 1, 0)");
            $stmt->execute([$fullname, $email, $phone]);
            $new_user_id = (int)$conn_rbe->lastInsertId();
        }

        $stmt = $conn_rbe->prepare("INSERT IGNORE INTO rbe_roles (user_id, role) VALUES (?, 'tenant')");
        $stmt->execute([$new_user_id]);

        $stmt = $conn_rbe->prepare("INSERT INTO tenant_landlord_map (tenant_id, landlord_id) VALUES (?, ?)");
        $stmt->execute([$new_user_id, $landlord_id]);

        $message = "✅ New tenant added and linked to landlord.";
    } else {
        $message = "❌ Full name, email, and landlord selection are required.";
    }
}

// Handle Delete Tenant
if (isset($_GET['delete']) && is_numeric($_GET['delete'])) {
    $delete_id = intval($_GET['delete']);

    if (!$is_admin) {
        $stmt = $conn_rbe->prepare("SELECT 1 FROM tenant_landlord_map WHERE tenant_id = ? AND landlord_id = ?");
        $stmt->execute([$delete_id, $filter_landlord_id]);
        if (!$stmt->fetch()) {
            exit('Access denied to delete this tenant.');
        }
    }

    $conn_rbe->prepare("DELETE FROM tenant_landlord_map WHERE tenant_id = ?")->execute([$delete_id]);
    $conn_rbe->prepare("DELETE FROM rbe_roles WHERE user_id = ?")->execute([$delete_id]);
    $conn_rbe->prepare("DELETE FROM rbe_users WHERE id = ?")->execute([$delete_id]);

    $message = "🗑️ Tenant deleted successfully.";
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Manage Tenants – RBE</title>
    <style>
        body {
            background: #0a1a2f;
            color: #ffffff;
            font-family: Arial, sans-serif;
            padding: 40px;
            margin: 0;
        }

        h1, h2 {
            color: #7ed957;
            margin-top: 0;
            margin-bottom: 20px;
            text-align: center;
        }

        .nav-btn {
            background: #7ed957;
            color: #000;
            padding: 10px 20px;
            border-radius: 8px;
            text-decoration: none;
            font-weight: bold;
            display: inline-block;
            margin-bottom: 30px;
        }

        .container {
            max-width: 90%;
            margin: auto;
        }

        form {
            background: #122c4c;
            padding: 25px;
            border-radius: 12px;
            box-shadow: 0 0 15px rgba(0,0,0,0.4);
            margin-bottom: 30px;
        }

        label {
            font-weight: bold;
            margin-top: 10px;
            display: block;
            color: #fff;
        }

        input[type="text"],
        input[type="email"],
        select {
            width: 100%;
            padding: 12px;
            margin-top: 8px;
            margin-bottom: 18px;
            border: none;
            border-radius: 8px;
            background: #1b3a4d;
            color: #fff;
        }

        button {
            background: #7ed957;
            color: #000;
            font-weight: bold;
            padding: 12px;
            border: none;
            border-radius: 10px;
            cursor: pointer;
            font-size: 16px;
        }

        button:hover {
            background: #00cc77;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            background: #122c4c;
            border-radius: 12px;
            overflow: hidden;
            box-shadow: 0 0 10px rgba(0,0,0,0.4);
        }

        th, td {
            border: 1px solid #7ed957;
            padding: 12px;
            text-align: left;
        }

        th {
            background: #1b3a4d;
            color: #7ed957;
        }

        tr:nth-child(even) {
            background: #1b3a4d;
        }

        .message {
            background: #1b3a4d;
            color: #7ed957;
            font-weight: bold;
            padding: 12px;
            border-radius: 8px;
            margin-bottom: 20px;
            text-align: center;
        }

        .action-links a {
            margin-right: 10px;
            text-decoration: none;
            font-weight: bold;
        }

        .action-links a.view { color: #7ed957; }
        .action-links a.edit { color: #00ccff; }
        .action-links a.delete { color: #ff5555; }
    </style>
</head>
<body>

<div class="container">
    <a href="<?= $is_admin ? 'admin-dashboard.php' : 'landlord-dashboard.php' ?>" class="nav-btn">⬅ Back to Dashboard</a>
    <h1>Manage Tenants</h1>

    <?php if (isset($message)) echo "<div class='message'>" . htmlspecialchars($message) . "</div>"; ?>

    <form method="post" action="">
        <h2>➕ Add New Tenant</h2>
        <input type="text" name="fullname" placeholder="Full Name" required>
        <input type="email" name="email" placeholder="Email" required>
        <input type="text" name="phone" placeholder="Phone">

        <?php if ($is_admin): ?>
            <label for="landlord_id">Assign to Landlord:</label>
            <select name="landlord_id" required>
                <option value="">Select Landlord</option>
                <?php
                $landlords = $conn_rbe->query("
                    SELECT r.user_id, u.fullname 
                    FROM rbe_roles r 
                    JOIN rbe_users u ON r.user_id = u.id 
                    WHERE r.role='landlord'
                ");
                while ($l = $landlords->fetch()) {
                    echo "<option value='{$l['user_id']}'>".htmlspecialchars($l['fullname'])."</option>";
                }
                ?>
            </select>
        <?php else: ?>
            <input type="hidden" name="landlord_id" value="<?= $filter_landlord_id ?>">
        <?php endif; ?>

        <button type="submit" name="add_tenant">Add Tenant</button>
    </form>

    <?php if ($is_admin): ?>
        <form method="get">
            <label for="filter_landlord_id">🔎 Filter by Landlord:</label>
            <select name="filter_landlord_id" onchange="this.form.submit()">
                <option value="0">All</option>
                <?php
                $stmt = $conn_rbe->query("SELECT id, fullname FROM rbe_users WHERE id IN (SELECT user_id FROM rbe_roles WHERE role = 'landlord')");
                while ($l = $stmt->fetch()) {
                    $selected = ($filter_landlord_id == $l['id']) ? "selected" : "";
                    echo "<option value='{$l['id']}' $selected>" . htmlspecialchars($l['fullname']) . "</option>";
                }
                ?>
            </select>
        </form>
    <?php endif; ?>

    <h2>👥 Current Tenants</h2>
    <table>
        <tr>
            <th>User ID</th>
            <th>Full Name</th>
            <th>Email</th>
            <th>Phone</th>
            <th>Landlord</th>
            <th>Actions</th>
        </tr>
        <?php
        if ($is_admin) {
            $query = "
                SELECT r.user_id, u.fullname, u.email, u.phone, m.landlord_id, lu.fullname AS landlord_name
                FROM rbe_roles r
                JOIN rbe_users u ON r.user_id = u.id
                LEFT JOIN tenant_landlord_map m ON r.user_id = m.tenant_id
                LEFT JOIN rbe_users lu ON m.landlord_id = lu.id
                WHERE r.role = 'tenant'
            ";
            if ($filter_landlord_id > 0) {
                $query .= " AND m.landlord_id = " . intval($filter_landlord_id);
            }
            $stmt = $conn_rbe->query($query);
        } else {
            $stmt = $conn_rbe->prepare("
                SELECT r.user_id, u.fullname, u.email, u.phone
                FROM rbe_roles r
                JOIN rbe_users u ON r.user_id = u.id
                JOIN tenant_landlord_map m ON r.user_id = m.tenant_id
                WHERE r.role = 'tenant' AND m.landlord_id = ?
            ");
            $stmt->execute([$filter_landlord_id]);
        }

        while ($row = $stmt->fetch()) {
            echo "<tr>
                <td>{$row['user_id']}</td>
                <td>{$row['fullname']}</td>
                <td>{$row['email']}</td>
                <td>{$row['phone']}</td>";

            if ($is_admin) {
                echo "<td>" . ($row['landlord_name'] ?? 'Unassigned') . "</td>";
            } else {
                echo "<td>Your Tenant</td>";
            }

            echo "<td class='action-links'>
                
                <a class='edit' href='edit-tenant.php?tenant_id={$row['user_id']}'>Edit</a> |
                <a class='delete' href='?delete={$row['user_id']}' onclick=\"return confirm('Are you sure you want to delete this tenant?')\">Delete</a>
            </td></tr>";
        }
        ?>
    </table>
</div>

</body>
</html>

