<?php
// wallet/landlord/history.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'];
$landlord_id = (int)($_GET['landlord_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 === 'landlord' && $landlord_id !== $current_user_id) {
    exit("Access denied: landlords can only view their own history.");
}

// Fetch landlord info
$stmt = $conn_rbe->prepare("SELECT fullname FROM rbe_users WHERE id = ?");
$stmt->execute([$landlord_id]);
$landlord_name = $stmt->fetchColumn() ?: "Unknown";

// --- Fetch tenant deposit credits ---
$stmt = $conn_rbe->prepare("
    SELECT 
        wt.created_at,
        'deposit' AS type,
        td.amount AS tenant_deposit,
        td.fee,
        wt.amount AS credited_amount,
        u.fullname AS tenant_name
    FROM wallet_transactions wt
    LEFT JOIN tenant_wallet_deposits td 
        ON td.landlord_id = wt.user_id 
       AND td.amount - td.fee = wt.amount
    LEFT JOIN rbe_users u 
        ON td.tenant_id = u.id
    WHERE wt.user_type = 'landlord' AND wt.user_id = ?
");
$stmt->execute([$landlord_id]);
$deposit_rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

// --- Fetch landlord payouts (withdrawals) ---
$stmt = $conn_rbe->prepare("
    SELECT 
        created_at,
        'withdrawal' AS type,
        amount,
        NULL AS tenant_deposit,
        NULL AS fee,
        NULL AS tenant_name
    FROM landlord_wallet_payouts
    WHERE landlord_id = ?
");
$stmt->execute([$landlord_id]);
$payout_rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

// --- Merge and sort all transactions by date ---
$transactions = array_merge($deposit_rows, $payout_rows);
usort($transactions, function ($a, $b) {
    return strtotime($b['created_at']) <=> strtotime($a['created_at']);
});
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Wallet History - <?= htmlspecialchars($landlord_name) ?></title>
  <style>
    body { font-family: Arial, sans-serif; background: #051a25; color: #fff; padding: 20px; }
    .card { background: #122c4c; padding: 20px; border-radius: 12px; max-width: 1000px; margin: auto; }
    h1 { color: #7ed957; margin-bottom: 15px; }
    table { width: 100%; border-collapse: collapse; margin-top: 10px; }
    th, td { padding: 10px; border: 1px solid #7ed957; text-align: center; }
    th { background: #1b3a4d; color: #7ed957; }
    tr:nth-child(even) { background: #0b1f33; }
    .btn { background: #7ed957; color: #000; padding: 8px 16px; border-radius: 8px; text-decoration: none; font-weight: bold; }
    .btn:hover { background: #00cc77; }
    .deposit { color: #7ed957; font-weight: bold; }
    .withdrawal { color: #ff7777; font-weight: bold; }
  </style>
</head>
<body>
  <div class="card">
    <h1>💼 Wallet History – <?= htmlspecialchars($landlord_name) ?></h1>

    <?php if (empty($transactions)): ?>
      <p>No transactions yet.</p>
    <?php else: ?>
      <table>
        <tr>
          <th>Date</th>
          <th>Type</th>
          <th>Tenant</th>
          <th>Deposit (R)</th>
          <th>Fee (R)</th>
          <th>Credited (R)</th>
          <th>Withdrawal (R)</th>
        </tr>
        <?php foreach ($transactions as $t): ?>
          <tr>
            <td><?= htmlspecialchars($t['created_at']) ?></td>
            <td class="<?= $t['type'] ?>"><?= ucfirst($t['type']) ?></td>
            <td><?= htmlspecialchars($t['tenant_name'] ?? '—') ?></td>
            <td><?= $t['tenant_deposit'] ? number_format($t['tenant_deposit'], 2) : '—' ?></td>
            <td><?= $t['fee'] ? number_format($t['fee'], 2) : '—' ?></td>
            <td><?= $t['credited_amount'] ? number_format($t['credited_amount'], 2) : '—' ?></td>
            <td><?= $t['type'] === 'withdrawal' ? number_format($t['amount'], 2) : '—' ?></td>
          </tr>
        <?php endforeach; ?>
      </table>
    <?php endif; ?>

    <p style="margin-top:15px;">
      <a class="btn" href="../../landlord-dashboard.php">⬅ Back to Landlord Dashboard</a>
    </p>
  </div>
</body>
</html>
