<?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'];
$stmt = $conn_rbe->prepare("SELECT role FROM rbe_roles WHERE user_id = ? LIMIT 1");
$stmt->execute([$user_id]);
$role = $stmt->fetchColumn();

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

$tenant_id = isset($_GET['tenant_id']) ? intval($_GET['tenant_id']) : 0;
if (!$tenant_id) {
    exit("No tenant specified.");
}

// Confirm permission
if (!$is_admin) {
    $stmt = $conn_rbe->prepare("SELECT 1 FROM tenant_landlord_map WHERE tenant_id = ? AND landlord_id = ?");
    $stmt->execute([$tenant_id, $user_id]);
    if (!$stmt->fetch()) {
        exit("Access denied.");
    }
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $fullname = trim($_POST['fullname']);
    $email = trim($_POST['email']);
    $phone = trim($_POST['phone']);

    if ($fullname && $email) {
        $stmt = $conn_rbe->prepare("UPDATE rbe_users SET fullname = ?, email = ?, phone = ? WHERE id = ?");
        $stmt->execute([$fullname, $email, $phone, $tenant_id]);

        // Allow admin to reassign landlord
        if ($is_admin && isset($_POST['landlord_id'])) {
            $landlord_id = intval($_POST['landlord_id']);
            $stmt = $conn_rbe->prepare("UPDATE tenant_landlord_map SET landlord_id = ? WHERE tenant_id = ?");
            $stmt->execute([$landlord_id, $tenant_id]);
        }

        $message = "✅ Tenant details updated successfully.";
    } else {
        $message = "❌ Full name and email are required.";
    }
}

// Fetch tenant details
$stmt = $conn_rbe->prepare("SELECT fullname, email, phone FROM rbe_users WHERE id = ?");
$stmt->execute([$tenant_id]);
$tenant = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$tenant) exit("Tenant not found.");

// Get current landlord
$current_landlord_id = 0;
$stmt = $conn_rbe->prepare("SELECT landlord_id FROM tenant_landlord_map WHERE tenant_id = ?");
$stmt->execute([$tenant_id]);
if ($row = $stmt->fetch()) {
    $current_landlord_id = $row['landlord_id'];
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Edit Tenant – RBE</title>
    <style>
        body {
            background: #0a1a2f;
            color: #ffffff;
            font-family: Arial, sans-serif;
            padding: 40px;
        }

        .container {
            background: #122c4c;
            max-width: 500px;
            margin: auto;
            padding: 30px;
            border-radius: 12px;
            box-shadow: 0 0 20px rgba(0,0,0,0.4);
        }

        h2 {
            text-align: center;
            color: #7ed957;
            margin-bottom: 30px;
        }

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

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

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

        button:hover {
            background: #00cc77;
        }

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

        a.back-link {
            color: #7ed957;
            display: inline-block;
            margin-top: 20px;
            text-align: center;
            width: 100%;
            text-decoration: none;
        }

        a.back-link:hover {
            color: #00cc77;
        }
    </style>
</head>
<body>

<div class="container">
    <h2>👤 Edit Tenant</h2>

    <?php if (isset($message)): ?>
        <div class="message"><?= htmlspecialchars($message) ?></div>
    <?php endif; ?>

    <form method="post">
        <label for="fullname">Full Name:</label>
        <input type="text" name="fullname" id="fullname" value="<?= htmlspecialchars($tenant['fullname']) ?>" required>

        <label for="email">Email Address:</label>
        <input type="email" name="email" id="email" value="<?= htmlspecialchars($tenant['email']) ?>" required>

        <label for="phone">Phone Number:</label>
        <input type="text" name="phone" id="phone" value="<?= htmlspecialchars($tenant['phone']) ?>">

        <?php if ($is_admin): ?>
            <label for="landlord_id">Assigned Landlord:</label>
            <select name="landlord_id" required>
                <option value="">Select Landlord</option>
                <?php
                $stmt = $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 ($row = $stmt->fetch()) {
                    $selected = ($row['user_id'] == $current_landlord_id) ? 'selected' : '';
                    echo "<option value='{$row['user_id']}' $selected>" . htmlspecialchars($row['fullname']) . "</option>";
                }
                ?>
            </select>
        <?php endif; ?>

        <button type="submit">💾 Update Tenant</button>
    </form>

    <a class="back-link" href="manage-tenants.php">⬅ Back to Tenant Management</a>
</div>

</body>
</html>
