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

// -----------------------------
// Access Control
// -----------------------------
if (!isset($_SESSION['user_id'])) {
    exit("Access denied: not logged in.");
}

$current_user_id = (int)$_SESSION['user_id'];

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

if (!$role) exit("Access denied: no role.");

$landlord_id = (int)($_POST['landlord_id'] ?? 0);

if ($role === 'landlord') {
    $landlord_id = $current_user_id;
} elseif ($role !== 'admin') {
    exit("Access denied: insufficient permissions.");
}

if ($landlord_id <= 0) {
    exit("Invalid landlord ID.");
}

// -----------------------------
// Handle Global Toggle
// -----------------------------
if (isset($_POST['use_wallet']) && empty($_POST['tenants'])) {
    $use_wallet = $_POST['use_wallet'] ? 1 : 0;
    $stmt = $conn_rbe->prepare("UPDATE rbe_users SET use_wallet = ? WHERE id = ?");
    $stmt->execute([$use_wallet, $landlord_id]);
}

// -----------------------------
// Handle Per-Tenant Toggles
// -----------------------------
if (!empty($_POST['tenants'])) {
    // Reset all first
    $stmt = $conn_rbe->prepare("UPDATE tenant_landlord_map SET use_wallet = 0 WHERE landlord_id = ?");
    $stmt->execute([$landlord_id]);

    // Enable selected tenants
    foreach ($_POST['tenants'] as $tenant_id => $flag) {
        $stmt = $conn_rbe->prepare("
            UPDATE tenant_landlord_map 
            SET use_wallet = 1 
            WHERE tenant_id = ? AND landlord_id = ?
        ");
        $stmt->execute([(int)$tenant_id, $landlord_id]);
    }
}

// -----------------------------
// Redirect back
// -----------------------------
if ($role === 'admin') {
    header("Location: ../landlord-dashboard.php?landlord_id=" . $landlord_id);
} else {
    header("Location: ../landlord-dashboard.php");
}
exit();
