<?php
// ==========================
// transaction_history.php - DemoBank
// ==========================

require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/currency_helper.php'; // Optional helper for getCurrencySymbol

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

// Ensure user is logged in
$user_id = $_SESSION['user_id'] ?? null;
if (!$user_id) {
    header("Location: /auth/login.php");
    exit;
}

// Database connection
$conn = db();
if (!$conn) die("Database connection failed");

// Fetch all user accounts
$accounts = [];
$stmt = $conn->prepare("SELECT id, currency FROM accounts WHERE user_id=?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$res = $stmt->get_result();
while ($acc = $res->fetch_assoc()) {
    $accounts[$acc['id']] = $acc['currency'];
}
$stmt->close();

if (empty($accounts)) {
    $accounts = [0 => 'USD']; // fallback
}

// Fetch transactions for user accounts (latest 50)
$account_ids = implode(',', array_keys($accounts));
$query = "
    SELECT t.*, a.currency AS account_currency
    FROM transactions t
    INNER JOIN accounts a ON t.account_id = a.id
    WHERE t.account_id IN ($account_ids)
    ORDER BY t.created_at DESC
    LIMIT 50
";
$result = $conn->query($query);

// Currency symbols map
$currencySymbols = [
    'USD' => '$',
    'EUR' => '€',
    'GBP' => '£',
    'JPY' => '¥',
    'CNY' => '¥',
    'NGN' => '₦',
    'GHS' => '₵',
    'INR' => '₹',
    'CAD' => 'C$',
    'AUD' => 'A$'
];

// --------------------------
// Capture content for layout
// --------------------------
ob_start();
?>

<h1>Transaction History</h1>

<?php if ($result && $result->num_rows > 0): ?>
    <table style="width:100%;border-collapse:collapse;">
        <thead>
            <tr style="background:#1a73e8;color:white;">
                <th style="padding:10px;border:1px solid #ddd;">Date</th>
                <th style="padding:10px;border:1px solid #ddd;">Type</th>
                <th style="padding:10px;border:1px solid #ddd;">Description</th>
                <th style="padding:10px;border:1px solid #ddd;">Amount</th>
                <th style="padding:10px;border:1px solid #ddd;">Status</th>
                <th style="padding:10px;border:1px solid #ddd;">Reference</th>
            </tr>
        </thead>
        <tbody>
<?php while ($row = $result->fetch_assoc()): 

    // ✅ FIXED: Use DB type instead of sender/recipient
    $type = strtolower($row['type'] ?? 'credit');
    $is_credit = ($type === 'credit');
    $type_text = ucfirst($type);

    // Currency
    $currency_code = $row['account_currency'] ?? 'USD';
    $symbol = $currencySymbols[$currency_code] ?? $currency_code;

    // Amount display
    $amount_display = ($is_credit ? '' : '-') . $symbol . number_format($row['amount'], 2);

    // Status
    $status = ucfirst($row['status'] ?? 'completed');
?>
<tr style="background-color: <?= $is_credit ? '#e8fff0' : '#fff5f5'; ?>;">
    <td style="padding:10px;border:1px solid #ddd;"><?= htmlspecialchars($row['created_at']); ?></td>
    <td style="padding:10px;border:1px solid #ddd;"><?= $type_text; ?></td>
    <td style="padding:10px;border:1px solid #ddd;"><?= htmlspecialchars($row['description'] ?? 'Transfer'); ?></td>
    <td style="padding:10px;border:1px solid #ddd;"><?= $amount_display; ?></td>
    <td style="padding:10px;border:1px solid #ddd;"><?= $status; ?></td>
    <td style="padding:10px;border:1px solid #ddd;"> <?= htmlspecialchars($row['reference'] ?? 'N/A'); ?></td>
</tr>
<?php endwhile; ?>
        </tbody>
    </table>
<?php else: ?>
    <p>No transactions found.</p>
<?php endif; ?>

<?php
$content = ob_get_clean();

// Render layout
renderLayout("Transaction History", $content, $conn);