<?php
// wallet/tenant/deposit.php
session_start();
require_once __DIR__ . "/../../db_connect.php";

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

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

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

if ($role === 'tenant' && $tenant_id !== $current_user_id) {
    exit("Access denied: tenants can only top up their own wallet.");
}

// Resolve landlord
$stmt = $conn_rbe->prepare("SELECT landlord_id FROM tenant_landlord_map WHERE tenant_id = ? LIMIT 1");
$stmt->execute([$tenant_id]);
$landlord_id = (int)$stmt->fetchColumn();
if (!$landlord_id) exit("Error: no landlord assigned.");

// Messages
$success_msg = $error_msg = "";

// Handle deposit
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $amount = round((float)($_POST['amount'] ?? 0), 2);

    if ($amount <= 0) {
        $error_msg = "Please enter a valid amount.";
    } else {
        try {
            $conn_rbe->beginTransaction();

            $fee = round($amount * 0.05, 2);
            $landlord_credit = $amount - $fee;

            // Record in tenant_wallet_deposits
            $stmt = $conn_rbe->prepare("
                INSERT INTO tenant_wallet_deposits (tenant_id, landlord_id, amount, fee)
                VALUES (?, ?, ?, ?)
            ");
            $stmt->execute([$tenant_id, $landlord_id, $amount, $fee]);

            // Record in wallet_transactions (tenant + landlord only)
            $stmt = $conn_rbe->prepare("
                INSERT INTO wallet_transactions (user_type, user_id, transaction_type, amount, description)
                VALUES 
                ('tenant', ?, 'deposit', ?, 'Tenant wallet deposit'),
                ('landlord', ?, 'deposit', ?, 'Landlord credited after tenant deposit')
            ");
            $stmt->execute([$tenant_id, $amount, $landlord_id, $landlord_credit]);

            $conn_rbe->commit();
            $success_msg = "Deposit of R " . number_format($amount, 2) . " successful.";
        } catch (Exception $e) {
            $conn_rbe->rollBack();
            $error_msg = "Error: " . $e->getMessage();
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Top Up Wallet</title>
  <style>
    body { font-family: Arial, sans-serif; background: #051a25; color: #fff; padding: 20px; }
    .card { background: #122c4c; padding: 20px; border-radius: 12px; max-width: 500px; margin: auto; }
    h1 { color: #7ed957; }
    input[type="number"] { padding: 10px; width: 100%; margin: 10px 0; border-radius: 8px; border: none; }
    button { background: #7ed957; color: #000; padding: 10px 20px; border: none; border-radius: 8px; font-weight: bold; cursor: pointer; }
    button:hover { background: #00cc77; }
    .msg { margin: 10px 0; padding: 10px; border-radius: 8px; }
    .success { background: #1b3a4d; color: #7ed957; }
    .error { background: #3a1b1b; color: #ff7777; }
  </style>
</head>
<body>
  <div class="card">
    <h1>💳 Top Up Wallet</h1>
    <?php if ($success_msg): ?>
      <div class="msg success"><?= htmlspecialchars($success_msg) ?></div>
    <?php elseif ($error_msg): ?>
      <div class="msg error"><?= htmlspecialchars($error_msg) ?></div>
    <?php endif; ?>

    <form method="post">
      <label for="amount">Deposit Amount (R):</label>
      <input type="number" name="amount" id="amount" min="1" step="0.01" required>
      <button type="submit">Deposit</button>
    </form>

    <p style="margin-top:10px;">
      <a href="../../tenant-dashboard.php" style="color:#7ed957;">⬅ Back to Tenant Dashboard</a>
    </p>
  </div>
</body>
</html>
