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

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

$user_id = $_SESSION['user_id'];

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

if ($role !== 'admin') {
    exit('❌ Access denied.');
}

// Validate meter ID
$meter_id = isset($_GET['id']) ? intval($_GET['id']) : 0;
if (!$meter_id) {
    echo "Invalid meter ID.";
    exit();
}

// Fetch current meter
$stmt = $conn_rbe->prepare("SELECT * FROM water_meters WHERE id = ?");
$stmt->execute([$meter_id]);
$meter = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$meter) {
    echo "Meter not found.";
    exit();
}

// Handle reassignment form
$success = $error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $new_property = intval($_POST['property_id'] ?? 0);
    $new_landlord = intval($_POST['landlord_id'] ?? 0);
    $new_tenant = intval($_POST['tenant_id'] ?? 0);

    if ($new_property && $new_landlord && $new_tenant) {
        $update = $conn_rbe->prepare("UPDATE water_meters SET property_id = ?, landlord_id = ?, tenant_id = ? WHERE id = ?");
        $update->execute([$new_property, $new_landlord, $new_tenant, $meter_id]);

        header("Location: landlord-dashboard.php?landlord_id=$new_landlord&tenant_id=$new_tenant&meter_reassigned=1");
        exit();
    } else {
        $error = "Property, landlord, and tenant are all required.";
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Reassign Water Meter</title>
    <style>
        body {
            background: #0a1a2f;
            color: white;
            font-family: Arial, sans-serif;
            padding: 30px;
        }
        .card {
            background: #122c4c;
            padding: 25px;
            border-radius: 12px;
            max-width: 500px;
            margin: auto;
        }
        label, select, input {
            display: block;
            width: 100%;
            margin-bottom: 15px;
        }
        select, input {
            padding: 10px;
            border-radius: 8px;
            border: none;
        }
        button {
            background: #7ed957;
            color: black;
            padding: 12px;
            border-radius: 8px;
            font-weight: bold;
            border: none;
            cursor: pointer;
            width: 100%;
        }
        button:hover {
            background: #00cc77;
        }
        .success { color: #7ed957; font-weight: bold; margin-bottom: 15px; }
        .error { color: #ff6666; font-weight: bold; margin-bottom: 15px; }
    </style>
</head>
<body>

<div class="card">
    <h2>🔄 Reassign Water Meter</h2>

    <p><strong>Serial:</strong> <?= htmlspecialchars($meter['serial_number']) ?></p>
    <p><strong>Description:</strong> <?= htmlspecialchars($meter['description']) ?></p>

    <?php if ($success): ?>
        <p class="success"><?= $success ?></p>
    <?php elseif ($error): ?>
        <p class="error"><?= $error ?></p>
    <?php endif; ?>

    <form method="post">
        <label for="property_id">🏘️ Assign to Property:</label>
        <select name="property_id" required>
            <option value="">-- Select Property --</option>
            <?php
            $stmt = $conn_rbe->query("SELECT id, property_number FROM properties ORDER BY property_number ASC");
            while ($prop = $stmt->fetch()) {
                $selected = ($prop['id'] == $meter['property_id']) ? 'selected' : '';
                echo "<option value='{$prop['id']}' $selected>{$prop['property_number']}</option>";
            }
            ?>
        </select>

        <label for="landlord_id">👤 Assign to Landlord:</label>
        <select name="landlord_id" required>
            <option value="">-- Select Landlord --</option>
            <?php
            $stmt = $conn_rbe->query("
                SELECT u.id, u.fullname 
                FROM rbe_users u 
                WHERE u.id IN (SELECT user_id FROM rbe_roles WHERE role = 'landlord')
                ORDER BY u.fullname ASC
            ");
            while ($ll = $stmt->fetch()) {
                $selected = ($ll['id'] == $meter['landlord_id']) ? 'selected' : '';
                echo "<option value='{$ll['id']}' $selected>{$ll['fullname']}</option>";
            }
            ?>
        </select>

        <label for="tenant_id">👥 Assign to Tenant:</label>
        <select name="tenant_id" required>
            <option value="">-- Select Tenant --</option>
            <?php
            $stmt = $conn_rbe->query("
                SELECT u.id, u.fullname 
                FROM rbe_users u 
                WHERE u.id IN (SELECT user_id FROM rbe_roles WHERE role = 'tenant')
                ORDER BY u.fullname ASC
            ");
            while ($t = $stmt->fetch()) {
                $selected = ($t['id'] == $meter['tenant_id']) ? 'selected' : '';
                echo "<option value='{$t['id']}' $selected>{$t['fullname']}</option>";
            }
            ?>
        </select>

        <button type="submit">💾 Reassign Meter</button>
    </form>
</div>

</body>
</html>
