<?php
session_start();
require_once 'db_connect.php';

// Check admin access
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}
$user_id = $_SESSION['user_id'];
$stmt = $conn_rbe->prepare("SELECT role FROM rbe_roles WHERE user_id = ? LIMIT 1");
$stmt->execute([$user_id]);
if ($stmt->fetchColumn() !== 'admin') {
    exit('Access denied.');
}

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

    // Delete login tokens
    $conn_rbe->prepare("DELETE FROM login_tokens WHERE user_id = ?")->execute([$delete_id]);

    // Delete roles
    $conn_rbe->prepare("DELETE FROM rbe_roles WHERE user_id = ?")->execute([$delete_id]);

    // Delete rbe_users
    $conn_rbe->prepare("DELETE FROM rbe_users WHERE id = ?")->execute([$delete_id]);

    // Delete related properties
    $conn_rbe->prepare("DELETE FROM properties WHERE landlord_id = ?")->execute([$delete_id]);


    $message = "🗑️ Landlord deleted successfully.";
}

// Handle Add Landlord
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_landlord'])) {
    $fullname = trim($_POST['fullname'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $phone = trim($_POST['phone'] ?? '');

    if ($fullname && $email) {
        // Step 1: find or create the standalone RBE user
        $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();
        }

        // Step 2: Assign landlord role
        $stmt = $conn_rbe->prepare("INSERT INTO rbe_roles (user_id, role) VALUES (?, 'landlord')");
        $stmt->execute([$new_user_id]);

        // Step 3: Create login token
        $token = bin2hex(random_bytes(32));
        $expires = date('Y-m-d H:i:s', strtotime('+30 minutes'));
        $stmt = $conn_rbe->prepare("INSERT INTO login_tokens (user_id, token, expires_at) VALUES (?, ?, ?)");
        $stmt->execute([$new_user_id, $token, $expires]);

        // Step 4: Email token link
        $link = RBE_V1_BASE_URL . "/set-password.php?token=" . urlencode($token);
        $subject = "Set up your RBE landlord account";
        $body = "Hi $fullname,\n\nPlease set your password using the link below:\n$link\n\nThis link expires in 30 minutes.";
        $headers = "From: " . RBE_MAIL_FROM;

        if (mail($email, $subject, $body, $headers)) {
            $message = "✅ Landlord added and email sent to $email.";
        } else {
            $message = "⚠️ Landlord added, but failed to send email.";
        }

    } else {
        $message = "❌ Full name and email are required.";
    }
}
?>


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Manage Landlords – RBE Admin</title>
    <style>
        body {
            background: #0a1a2f;
            color: #ffffff;
            font-family: Arial, sans-serif;
            padding: 40px;
            margin: 0;
        }

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

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

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

        .nav-btn:hover {
            background: #00cc77;
        }

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

        input[type="text"],
        input[type="email"] {
            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;
            width: 100%;
        }

        button:hover {
            background: #00cc77;
        }

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

        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;
        }

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

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

<div class="container">
    <a href="admin-dashboard.php" class="nav-btn">⬅ Back to Dashboard</a>
    <h1>Manage Landlords</h1>

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

    <form method="post" action="">
        <h2>➕ Add New Landlord</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">
        <button type="submit" name="add_landlord">Add Landlord</button>
    </form>

<div class="containera">
    <h2>👤 Current Landlords</h2>
    <table>
        <tr>
            <th>User ID</th>
            <th>Full Name</th>
            <th>Email</th>
            <th>Phone</th>
            <th>Actions</th>
        </tr>
        <?php
        $stmt = $conn_rbe->query("SELECT r.user_id, u.fullname, u.email, u.phone FROM rbe_roles r JOIN rbe_users u ON r.user_id = u.id WHERE r.role = 'landlord'");
        while ($row = $stmt->fetch()) {
            $userId = htmlspecialchars($row['user_id']);
            $fullname = htmlspecialchars($row['fullname']);
            $email = htmlspecialchars($row['email']);
            $phone = htmlspecialchars($row['phone']);

            echo "<tr>
                <td>$userId</td>
                <td>$fullname</td>
                <td>$email</td>
                <td>$phone</td>
                <td class='action-links'>
                    <a class='view' href='landlord-dashboard.php?landlord_id=$userId'>View</a> |
                    <a class='edit' href='edit-landlord.php?id=$userId'>Edit</a> |
                    <a class='delete' href='manage-landlords.php?delete=$userId' onclick=\"return confirm('Are you sure you want to delete this landlord?')\">Delete</a>
                </td>
            </tr>";
        }
        ?>
    </table>
</div>

</body>
</html>
