<?php
// Wallet settings API (JSON)
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

header('Content-Type: application/json');

require_once __DIR__ . '/../../core/db_connect.php';
require_once __DIR__ . '/../../core/auth.php';

if (!current_user_id()) { echo json_encode(['status'=>'error','message'=>'Not logged in']); exit; }

$role = current_user_role($conn_rbe);
$action = $_GET['action'] ?? $_POST['action'] ?? '';

try {
  if ($action === 'get_wallet_settings') {
    $landlord_id = landlord_scope_id();
    if ($role === 'tenant') { throw new Exception('Access denied'); }
    if (!$landlord_id) throw new Exception('Missing landlord');

    $st = $conn_rbe->prepare('SELECT use_wallet FROM rbe_users WHERE id=?');
    $st->execute([$landlord_id]);
    $landlord_use = (int)$st->fetchColumn();

    $st = $conn_rbe->prepare('SELECT t.tenant_id, u.fullname, t.use_wallet FROM tenant_landlord_map t JOIN rbe_users u ON u.id=t.tenant_id WHERE t.landlord_id=? ORDER BY u.fullname');
    $st->execute([$landlord_id]);
    $tenants = $st->fetchAll(PDO::FETCH_ASSOC);

    echo json_encode(['status'=>'success','data' => ['landlord_use_wallet'=>$landlord_use, 'tenants'=>$tenants]]);
    exit;
  }

  if ($action === 'save_wallet_settings') {
    if (!in_array($role, ['admin','landlord'], true)) throw new Exception('Access denied');
    $landlord_id = ($role === 'admin' && isset($_POST['landlord_id']) && $_POST['landlord_id'] !== '') ? (int)$_POST['landlord_id'] : current_user_id();
    $use_wallet  = isset($_POST['use_wallet']) ? (int)$_POST['use_wallet'] : 0;
    $tenant_flags = isset($_POST['tenants']) && is_array($_POST['tenants']) ? $_POST['tenants'] : [];

    $conn_rbe->prepare('UPDATE rbe_users SET use_wallet=? WHERE id=?')->execute([$use_wallet, $landlord_id]);
    $conn_rbe->prepare('UPDATE tenant_landlord_map SET use_wallet=0 WHERE landlord_id=?')->execute([$landlord_id]);
    foreach ($tenant_flags as $tid => $flag) {
      $conn_rbe->prepare('UPDATE tenant_landlord_map SET use_wallet=1 WHERE tenant_id=? AND landlord_id=?')->execute([(int)$tid, $landlord_id]);
    }
    echo json_encode(['status'=>'success','message'=>'Wallet settings saved']);
    exit;
  }

  echo json_encode(['status'=>'error','message'=>'Invalid action']);
} catch (Throwable $e) {
  echo json_encode(['status'=>'error','message'=>$e->getMessage()]);
}

?>

