<?php
// wallet/tenant/deposit.php — Tenant wallet top-up (styled)
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

if (session_status() === PHP_SESSION_NONE) {
  session_start();
}

require_once __DIR__ . '/../../core/db_connect.php';
require_once __DIR__ . '/../../core/auth.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);

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

// Tenants may only top up their own wallet
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.');
}

// Include sidebar where appropriate
$__has_sidebar = false;
if ($role === 'admin') { $__has_sidebar = true; @include __DIR__ . '/../../admin-nav.php'; }
elseif ($role === 'landlord') { $__has_sidebar = true; @include __DIR__ . '/../../landlord-nav.php'; }

// 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
      $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">
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>Top Up Wallet</title>
  <link rel="stylesheet" href="/assets/css/theme.css">
  <style>
    body { margin: 0; }
    <?php if ($__has_sidebar): ?>
    body { margin-left: 240px; }
    body.sidebar-collapsed { margin-left: 72px; }
    @media (max-width:900px){ body{ margin-left:0; } body.sidebar-collapsed{ margin-left:0; } }
    <?php endif; ?>
    .container { max-width: 1100px; margin: 0 auto; padding: 24px; }
    .card { max-width: 520px; margin: 0 auto; }
    .header-card { display:flex; align-items:center; justify-content:space-between; gap:12px; max-width:1100px; }
    .actions { display:flex; gap:10px; flex-wrap:wrap; }
    .msg { margin: 10px 0; padding: 12px 14px; border-radius: 10px; }
    .success { background: rgba(126,217,87,.12); color: var(--accent); border:1px solid rgba(126,217,87,.35); }
    .error { background: rgba(255,91,91,.12); color: var(--danger); border:1px solid rgba(255,91,91,.35); }
  </style>
</head>
<body>
  <div class="container">
    <div class="card header-card">
      <h1 class="mb-0">Top Up Wallet</h1>
      <div class="actions">
        <?php if ($role === 'admin'): ?>
          <a class="btn secondary" href="/admin-dashboard.php">Back to Admin</a>
        <?php elseif ($role === 'landlord'): ?>
          <a class="btn secondary" href="/landlord-dashboard.php">Back to Dashboard</a>
        <?php else: ?>
          <a class="btn secondary" href="/tenant-dashboard.php">Back to Dashboard</a>
        <?php endif; ?>
      </div>
    </div>

    <div class="card">
      <?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>

        <div style="display:flex; gap:10px; margin-top:10px;">
          <button type="submit" class="btn">Deposit</button>
          <?php if ($role !== 'tenant'): ?>
            <a class="btn secondary" href="/tenant-dashboard.php?tenant_id=<?= (int)$tenant_id ?>">View Tenant</a>
          <?php endif; ?>
        </div>

        <?php if (isset($amount) && $amount > 0): $net = max($amount * 0.95, 0); ?>
          <p class="muted" style="margin-top:10px;">Processing fee 5%. Net credited to landlord: R <?= number_format($net, 2) ?>.</p>
        <?php else: ?>
          <p class="muted" style="margin-top:10px;">A 5% processing fee applies.</p>
        <?php endif; ?>
      </form>
    </div>
  </div>

  <script>
    // Subtle fade-in like other views
    document.addEventListener('DOMContentLoaded', ()=>{
      document.querySelectorAll('.card').forEach((c,i)=> setTimeout(()=> c.style.opacity = 1, i * 80));
    });
  </script>

</body>
</html>

