<?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 Add Property
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_property'])) {
    $landlord_id = intval($_POST['landlord_id'] ?? 0);
    $name = trim($_POST['property_number'] ?? '');
    $address = trim($_POST['address'] ?? '');
    if ($landlord_id && $name && $address) {
        $sq_meters = floatval($_POST['square_meters'] ?? 0);
$stmt = $conn_rbe->prepare("INSERT INTO properties (landlord_id, property_number, address, square_meters) VALUES (?, ?, ?, ?)");
$stmt->execute([$landlord_id, $name, $address, $sq_meters]);

        $message = "✅ Property added.";
    } else {
        $message = "❌ All fields are required.";
    }
}

// Handle Edit Property
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['edit_property'])) {
    $prop_id = intval($_POST['prop_id'] ?? 0);
    $landlord_id = intval($_POST['landlord_id'] ?? 0);
    $name = trim($_POST['property_number'] ?? '');
    $address = trim($_POST['address'] ?? '');
    if ($prop_id && $landlord_id && $name && $address) {
        $sq_meters = floatval($_POST['square_meters'] ?? 0);
$stmt = $conn_rbe->prepare("UPDATE properties SET landlord_id = ?, property_number = ?, address = ?, square_meters = ? WHERE id = ?");
$stmt->execute([$landlord_id, $name, $address, $sq_meters, $prop_id]);

        $message = "✅ Property updated.";
    } else {
        $message = "❌ All fields are required for edit.";
    }
}

// Fetch landlords for dropdown
$landlords = $conn_rbe->query("SELECT u.id, u.fullname, u.email FROM rbe_users u JOIN rbe_roles r ON u.id = r.user_id WHERE r.role = 'landlord'")->fetchAll(PDO::FETCH_ASSOC);

// Fetch all properties
$properties = $conn_rbe->query("SELECT p.id, u.fullname AS landlord_name, p.property_number, p.address, p.square_meters, p.created_at, p.landlord_id FROM properties p LEFT JOIN rbe_users u ON p.landlord_id = u.id")->fetchAll(PDO::FETCH_ASSOC);

// If editing, get property details
$edit_property = null;
if (isset($_GET['edit_id'])) {
    $edit_id = intval($_GET['edit_id']);
    $stmt = $conn_rbe->prepare("SELECT * FROM properties WHERE id = ?");
    $stmt->execute([$edit_id]);
    $edit_property = $stmt->fetch(PDO::FETCH_ASSOC);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Manage Properties – RBE Admin</title>
    <style>
        body {
            background: #0a1a2f;
            color: #ffffff;
            font-family: Arial, sans-serif;
            padding: 40px;
            margin: 0;
        }

        .container {
            max-width: 90%;
            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"],
        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;
            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;
        }

        .actions a {
            text-decoration: none;
            font-weight: bold;
            color: #7ed957;
        }

        .cancel-link {
            display: inline-block;
            margin-top: 10px;
            color: #7ed957;
            text-decoration: none;
        }

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

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

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

    <?php if ($edit_property): ?>
        <form method="post" action="">
            <h2>✏️ Edit Property ID: <?= $edit_property['id'] ?></h2>
            <input type="hidden" name="prop_id" value="<?= $edit_property['id'] ?>">

            <label for="landlord_id">Landlord:</label>
            <select name="landlord_id" required>
                <option value="">Select Landlord</option>
                <?php foreach ($landlords as $l): ?>
                    <option value="<?= $l['id'] ?>" <?= $l['id'] == $edit_property['landlord_id'] ? 'selected' : '' ?>>
                        <?= htmlspecialchars($l['fullname']) ?> (<?= htmlspecialchars($l['email']) ?>)
                    </option>
                <?php endforeach; ?>
            </select>

            <label for="property_number">Property Number:</label>
            <input type="text" name="property_number" placeholder="Property Number" value="<?= htmlspecialchars($edit_property['property_number']) ?>" required>

            <label for="address">Property Address:</label>
            <input type="text" name="address" placeholder="Property Address" value="<?= htmlspecialchars($edit_property['address']) ?>" required>
            <label for="square_meters">Total Area (m²):</label>
<input type="text" name="square_meters" placeholder="e.g. 123.45" value="<?= isset($edit_property) ? htmlspecialchars($edit_property['square_meters']) : '' ?>" required>

            <button type="submit" name="edit_property">💾 Update Property</button>
            <a class="cancel-link" href="properties.php">Cancel</a>
        </form>
    <?php else: ?>
        <form method="post" action="">
            <h2>➕ Add New Property</h2>

            <label for="landlord_id">Landlord:</label>
            <select name="landlord_id" required>
                <option value="">Select Landlord</option>
                <?php foreach ($landlords as $l): ?>
                    <option value="<?= $l['id'] ?>"><?= htmlspecialchars($l['fullname']) ?> (<?= htmlspecialchars($l['email']) ?>)</option>
                <?php endforeach; ?>
            </select>

            <label for="property_number">Property Number:</label>
            <input type="text" name="property_number" placeholder="Property Number" required>

            <label for="address">Property Address:</label>
            <input type="text" name="address" placeholder="Property Address" required>
            <label for="square_meters">Total Area (m²):</label>
<input type="text" name="square_meters" placeholder="e.g. 123.45" value="<?= isset($edit_property) ? htmlspecialchars($edit_property['square_meters']) : '' ?>" required>


            <button type="submit" name="add_property">Add Property</button>
        </form>
    <?php endif; ?>

    <h2>🏠 Existing Properties</h2>
    <table>
        <tr>
            <th>ID</th>
            <th>Landlord</th>
            <th>Property Number</th>
            <th>Address</th>
            <th>Area (m²)</th>
            <th>Created At</th>
            <th>Actions</th>
        </tr>
        <?php foreach ($properties as $row): ?>
            <tr>
                <td><?= $row['id'] ?></td>
                <td><?= htmlspecialchars($row['landlord_name']) ?></td>
                <td><?= htmlspecialchars($row['property_number']) ?></td>
                <td><?= htmlspecialchars($row['address']) ?></td>
                <td><?= rtrim(rtrim($row['square_meters'], '0'), '.') ?></td>
                <td><?= $row['created_at'] ?></td>
                <td class="actions">
                    <a href="properties.php?edit_id=<?= $row['id'] ?>">Edit</a>
                </td>
            </tr>
        <?php endforeach; ?>
    </table>
</div>

</body>
</html>
