<?php
/**
 * Virtual Account History - Admin Page
 * View transaction history for virtual accounts
 */

require_once '../includes/config.php';
require_once '../includes/functions.php';
require_once '../includes/bridge-api.php';

// Simple admin authentication
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

if (!isset($_SESSION['admin_logged_in'])) {
    $_SESSION['admin_logged_in'] = true; // Remove this and implement proper auth
}

require_login();

$user_id = $_SESSION['user_id'] ?? null;
$user = $user_id ? getUserWithDefaults($user_id) : [];

// Hardcoded values
$customerId = '6c4e08bd-54ac-40fe-980b-ba80239ddf3e';
$virtualAccountId = 'c57f1f88-1c6f-481d-bbf0-877928c36736';

// Pagination parameters
$page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$perPage = 20; // Transactions per page
$offset = ($page - 1) * $perPage;

$error = null;
$history = [];
$virtualAccounts = [];
$virtualAccountDetails = null;
$totalCount = 0;
$totalPages = 1;

// Initialize Bridge API
$bridge = new BridgeAPI(BRIDGE_API_KEY);

// Get virtual account details
$accountDetailsResult = $bridge->getVirtualAccountDetails($customerId, $virtualAccountId);
if (!isset($accountDetailsResult['error'])) {
    $virtualAccountDetails = $accountDetailsResult;
}

// Get virtual accounts (optional - for account selector)
$accountsResult = $bridge->getVirtualAccounts($customerId);
if (!isset($accountsResult['error']) && isset($accountsResult['data'])) {
    $virtualAccounts = $accountsResult['data'];
}

// Fetch history directly (no loop - much faster)
// Fetch a reasonable number of transactions to avoid timeout
$fetchLimit = 10; // Limit to 10 transactions max to avoid timeout
$historyResult = $bridge->getVirtualAccountHistory($customerId, $virtualAccountId, $fetchLimit, 0);

if (isset($historyResult['error'])) {
    $error = $historyResult['error'];
    $history = [];
} elseif (isset($historyResult['data']) && is_array($historyResult['data'])) {
    $history = $historyResult['data'];
} elseif (is_array($historyResult) && isset($historyResult[0])) {
    // Sometimes the API returns the data directly
    $history = $historyResult;
} else {
    $history = [];
}

// Filter to show only funds_received transactions
$filteredHistory = array_filter($history, function($tx) {
    $txType = strtolower($tx['type'] ?? '');
    return $txType === 'funds_received';
});

// Convert to indexed array
$filteredHistory = array_values($filteredHistory);

// Apply pagination to filtered results
$totalCount = count($filteredHistory);
$totalPages = max(1, ceil($totalCount / $perPage));

// Get the page of results we need
$history = array_slice($filteredHistory, $offset, $perPage);

// Since we're only showing funds_received transactions, no need for complex grouping
// Just sort by date (newest first) - using UTC+3 timezone
$unique_history = array_values($history);
$timezone = new DateTimeZone('Europe/Istanbul'); // UTC+3
usort($unique_history, function($a, $b) use ($timezone) {
    $timeA = $a['created_at'] ?? $a['timestamp'] ?? '1970-01-01';
    $timeB = $b['created_at'] ?? $b['timestamp'] ?? '1970-01-01';
    
    $dateA = new DateTime($timeA, new DateTimeZone('UTC'));
    $dateA->setTimezone($timezone);
    $dateB = new DateTime($timeB, new DateTimeZone('UTC'));
    $dateB->setTimezone($timezone);
    
    return $dateB->getTimestamp() - $dateA->getTimestamp();
});

// Group by date (using UTC+3 timezone)
function groupByDate($transactions) {
    $groups = [];
    $timezone = new DateTimeZone('Europe/Istanbul'); // UTC+3
    $now = new DateTime('now', $timezone);
    $today = $now->format('Y-m-d');
    $yesterday = clone $now;
    $yesterday->modify('-1 day');
    $yesterdayStr = $yesterday->format('Y-m-d');
    
    foreach ($transactions as $tx) {
        $timestamp = $tx['created_at'] ?? $tx['timestamp'] ?? 'now';
        $date = new DateTime($timestamp, new DateTimeZone('UTC'));
        $date->setTimezone($timezone);
        $tx_date = $date->format('Y-m-d');
        
        if ($tx_date === $today) {
            $label = 'Today';
        } elseif ($tx_date === $yesterdayStr) {
            $label = 'Yesterday';
        } else {
            $label = $date->format('M j, Y');
        }
        
        if (!isset($groups[$label])) {
            $groups[$label] = [];
        }
        $groups[$label][] = $tx;
    }
    
    return $groups;
}

$grouped_history = groupByDate($unique_history);

$page_title = "Virtual Account History";
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $page_title; ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        body {
            background-color: #f5f5f5;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
        }
        .navbar {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .card {
            border: none;
            border-radius: 15px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        :root {
            --primary: #667eea;
            --border-color: #e0e0e0;
            --light-bg: #f8f9fa;
            --text-primary: #212529;
            --text-secondary: #6c757d;
            --shadow-lg: 0 10px 30px rgba(0,0,0,0.1);
        }
        .filter-tabs {
            display: flex;
            gap: 8px;
            margin-bottom: 20px;
            flex-wrap: wrap;
        }
        .filter-tab {
            padding: 10px 20px;
            border-radius: 12px;
            border: 1px solid var(--border-color);
            background: var(--light-bg);
            color: var(--text-secondary);
            text-decoration: none;
            transition: all 0.3s ease;
            font-weight: 600;
        }
        .filter-tab:hover, .filter-tab.active {
            background: var(--primary);
            color: white;
            border-color: var(--primary);
            transform: translateY(-2px);
        }
        .account-selector {
            margin-bottom: 20px;
        }
        .account-selector select {
            background: var(--light-bg);
            border: 1px solid var(--border-color);
            color: var(--text-primary);
            padding: 12px 20px;
            border-radius: 12px;
            width: 100%;
            font-weight: 600;
        }
        .account-selector select:focus {
            border-color: var(--primary);
            box-shadow: 0 0 0 0.2rem rgba(102, 126, 234, 0.15);
            outline: none;
        }
        .date-header {
            display: flex;
            align-items: center;
            margin: 30px 0 15px 0;
            gap: 12px;
        }
        .date-label {
            font-weight: 700;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            font-size: 0.85rem;
            color: var(--text-primary);
        }
        .date-line {
            flex: 1;
            height: 1px;
            background: var(--border-color);
            opacity: 0.3;
        }
        .transaction-card {
            background: var(--light-bg);
            border: 1px solid var(--border-color);
            border-radius: 16px;
            padding: 20px;
            margin-bottom: 12px;
            transition: all 0.3s ease;
        }
        .transaction-card:hover {
            transform: translateY(-2px);
            border-color: var(--primary);
            box-shadow: var(--shadow-lg);
        }
        .transaction-header {
            display: flex;
            align-items: center;
            gap: 16px;
            cursor: pointer;
            position: relative;
        }
        .transaction-details-expanded {
            margin-top: 20px;
            padding-top: 20px;
            border-top: 1px solid var(--border-color);
            display: none;
        }
        .transaction-details-expanded.show {
            display: block;
        }
        .detail-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 16px;
            margin-top: 16px;
        }
        .detail-item {
            display: flex;
            flex-direction: column;
            gap: 4px;
        }
        .detail-label {
            font-size: 0.75rem;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            color: var(--text-secondary);
        }
        .detail-value {
            font-size: 0.95rem;
            font-weight: 600;
            color: var(--text-primary);
            word-break: break-word;
        }
        .detail-section {
            margin-bottom: 20px;
        }
        .detail-section-title {
            font-size: 0.9rem;
            font-weight: 700;
            color: var(--primary);
            margin-bottom: 12px;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
        .expand-icon {
            margin-left: auto;
            transition: transform 0.3s ease;
            color: var(--text-secondary);
        }
        .transaction-card.expanded .expand-icon {
            transform: rotate(180deg);
        }
        .transaction-icon {
            width: 48px;
            height: 48px;
            border-radius: 24px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 24px;
            flex-shrink: 0;
        }
        .transaction-details {
            flex: 1;
            min-width: 0;
        }
        .transaction-type {
            font-size: 16px;
            font-weight: 600;
            color: var(--text-primary);
            margin-bottom: 4px;
            word-break: break-word;
            overflow-wrap: break-word;
            hyphens: auto;
            line-height: 1.4;
        }
        .transaction-info {
            font-size: 13px;
            color: var(--text-secondary);
            word-break: break-word;
        }
        .transaction-amount {
            text-align: right;
            flex-shrink: 0;
        }
        .transaction-amount-value {
            font-size: 18px;
            font-weight: 700;
            margin-bottom: 4px;
        }
        .status-badge-custom {
            display: inline-flex;
            align-items: center;
            gap: 4px;
            padding: 4px 10px;
            border-radius: 12px;
            font-size: 0.75rem;
            font-weight: 600;
        }
        .empty-state {
            text-align: center;
            padding: 60px 20px;
        }
        .empty-icon {
            font-size: 64px;
            margin-bottom: 20px;
            opacity: 0.5;
        }
        .bank-account-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border-radius: 20px;
            padding: 28px;
            margin-bottom: 24px;
            color: white;
            box-shadow: 0 10px 30px rgba(102, 126, 234, 0.3);
            position: relative;
            overflow: hidden;
        }
        .bank-account-card::before {
            content: '';
            position: absolute;
            top: -50%;
            right: -50%;
            width: 200%;
            height: 200%;
            background: radial-gradient(circle, rgba(255,255,255,0.1) 0%, transparent 70%);
            pointer-events: none;
        }
        .bank-card-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 24px;
            position: relative;
            z-index: 1;
        }
        .bank-card-title {
            font-size: 1.1rem;
            font-weight: 600;
            opacity: 0.9;
            letter-spacing: 0.5px;
        }
        .bank-status-badge {
            background: rgba(255, 255, 255, 0.25);
            backdrop-filter: blur(10px);
            padding: 6px 14px;
            border-radius: 20px;
            font-size: 0.75rem;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
        .bank-info-section {
            background: rgba(255, 255, 255, 0.15);
            backdrop-filter: blur(10px);
            border-radius: 16px;
            padding: 20px;
            margin-bottom: 16px;
            position: relative;
            z-index: 1;
        }
        .bank-info-section:last-child {
            margin-bottom: 0;
        }
        .bank-info-label {
            font-size: 0.75rem;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            opacity: 0.8;
            margin-bottom: 8px;
            display: flex;
            align-items: center;
            gap: 6px;
        }
        .bank-info-value {
            font-size: 1.1rem;
            font-weight: 700;
            word-break: break-all;
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 12px;
        }
        .bank-info-value-large {
            font-size: 1.3rem;
            letter-spacing: 1px;
        }
        .bank-copy-btn {
            background: rgba(255, 255, 255, 0.2);
            border: 1px solid rgba(255, 255, 255, 0.3);
            color: white;
            padding: 6px 12px;
            border-radius: 8px;
            font-size: 0.75rem;
            cursor: pointer;
            transition: all 0.3s ease;
            display: inline-flex;
            align-items: center;
            gap: 6px;
            flex-shrink: 0;
        }
        .bank-copy-btn:hover {
            background: rgba(255, 255, 255, 0.3);
            transform: scale(1.05);
        }
        .bank-copy-btn.copied {
            background: rgba(16, 185, 129, 0.3);
            border-color: rgba(16, 185, 129, 0.5);
        }
        .bank-info-row {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 16px;
            margin-bottom: 16px;
        }
        .bank-info-row:last-child {
            margin-bottom: 0;
        }
        .bank-info-item {
            display: flex;
            flex-direction: column;
        }
        .alert {
            border-radius: 12px;
            border: none;
            padding: 16px 20px;
        }
        .pagination-container {
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 12px;
            margin-top: 30px;
            padding: 20px 0;
        }
        .pagination-btn {
            padding: 10px 18px;
            border-radius: 8px;
            border: 1px solid var(--border-color);
            background: var(--light-bg);
            color: var(--text-primary);
            text-decoration: none;
            font-weight: 600;
            transition: all 0.3s ease;
            cursor: pointer;
        }
        .pagination-btn:hover:not(.disabled):not(.active) {
            background: var(--primary);
            color: white;
            border-color: var(--primary);
            transform: translateY(-2px);
        }
        .pagination-btn.active {
            background: var(--primary);
            color: white;
            border-color: var(--primary);
        }
        .pagination-btn.disabled {
            opacity: 0.5;
            cursor: not-allowed;
            pointer-events: none;
        }
        .pagination-info {
            color: var(--text-secondary);
            font-size: 0.9rem;
            margin: 0 10px;
        }
    </style>
</head>
<body>
    <nav class="navbar navbar-dark">
        <div class="container-fluid">
            <span class="navbar-brand mb-0 h1">
                <i class="bi bi-bank"></i> Virtual Account History
            </span>
            <div>
                <a href="orders.php" class="btn btn-light btn-sm me-2">
                    <i class="bi bi-arrow-left"></i> Back to Orders
                </a>
            </div>
        </div>
    </nav>

    <div class="container-fluid mt-4">
        <?php if ($error): ?>
            <div class="alert alert-danger">
                <i class="fas fa-exclamation-circle me-2"></i>
                <strong>Error:</strong> <?php echo htmlspecialchars($error); ?>
            </div>
        <?php endif; ?>

        <!-- Account Info Card -->
        <?php if (!empty($customerId) && $virtualAccountDetails): ?>
            <?php 
            $sourceDeposit = $virtualAccountDetails['source_deposit_instructions'] ?? [];
            $destination = $virtualAccountDetails['destination'] ?? [];
            $status = $virtualAccountDetails['status'] ?? '';
            ?>
            
            <div class="bank-account-card">
                <div class="bank-card-header">
                    <div class="bank-card-title">
                        <i class="fas fa-university me-2"></i>Virtual Account
                    </div>
                    <?php if (!empty($status)): ?>
                        <div class="bank-status-badge">
                            <?php echo htmlspecialchars(ucfirst($status)); ?>
                        </div>
                    <?php endif; ?>
                </div>
                
                <!-- IBAN Section -->
                <?php if (!empty($sourceDeposit['iban'])): ?>
                <div class="bank-info-section">
                    <div class="bank-info-label">
                        <i class="fas fa-credit-card"></i>
                        IBAN
                    </div>
                    <div class="bank-info-value bank-info-value-large" style="font-family: 'Courier New', monospace;">
                        <span><?php echo htmlspecialchars($sourceDeposit['iban']); ?></span>
                        <button class="bank-copy-btn" onclick="copyToClipboard('<?php echo htmlspecialchars($sourceDeposit['iban']); ?>', this)">
                            <i class="fas fa-copy"></i>Copy
                        </button>
                    </div>
                </div>
                <?php endif; ?>
                
                <!-- Account Details Grid -->
                <div class="bank-info-section">
                    <div class="bank-info-row">
                        <?php if (!empty($sourceDeposit['bic'])): ?>
                        <div class="bank-info-item">
                            <div class="bank-info-label">
                                <i class="fas fa-building"></i>
                                BIC
                            </div>
                            <div class="bank-info-value" style="font-family: 'Courier New', monospace;">
                                <?php echo htmlspecialchars($sourceDeposit['bic']); ?>
                            </div>
                        </div>
                        <?php endif; ?>
                        
                        <?php if (!empty($sourceDeposit['currency'])): ?>
                        <div class="bank-info-item">
                            <div class="bank-info-label">
                                <i class="fas fa-coins"></i>
                                Currency
                            </div>
                            <div class="bank-info-value">
                                <?php echo strtoupper(htmlspecialchars($sourceDeposit['currency'])); ?>
                            </div>
                        </div>
                        <?php endif; ?>
                    </div>
                    
                    <?php if (!empty($sourceDeposit['account_holder_name'])): ?>
                    <div class="bank-info-item" style="margin-bottom: 16px;">
                        <div class="bank-info-label">
                            <i class="fas fa-user"></i>
                            Account Holder
                        </div>
                        <div class="bank-info-value">
                            <?php echo htmlspecialchars($sourceDeposit['account_holder_name']); ?>
                        </div>
                    </div>
                    <?php endif; ?>
                    
                    <?php if (!empty($sourceDeposit['bank_name'])): ?>
                    <div class="bank-info-item">
                        <div class="bank-info-label">
                            <i class="fas fa-landmark"></i>
                            Bank Name
                        </div>
                        <div class="bank-info-value">
                            <?php echo htmlspecialchars($sourceDeposit['bank_name']); ?>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>
                
                <!-- Destination Address Section -->
                <?php if (!empty($destination['address'])): ?>
                <div class="bank-info-section">
                    <div class="bank-info-label">
                        <i class="fas fa-wallet"></i>
                        Destination Address (<?php echo strtoupper($destination['currency'] ?? 'USDC'); ?>)
                    </div>
                    <div class="bank-info-value" style="font-family: 'Courier New', monospace; font-size: 0.95rem;">
                        <span style="word-break: break-all;"><?php echo htmlspecialchars($destination['address']); ?></span>
                        <button class="bank-copy-btn" onclick="copyToClipboard('<?php echo htmlspecialchars($destination['address']); ?>', this)">
                            <i class="fas fa-copy"></i>Copy
                        </button>
                    </div>
                    <?php if (!empty($destination['payment_rail'])): ?>
                    <div style="margin-top: 12px; font-size: 0.85rem; opacity: 0.8;">
                        <i class="fas fa-network-wired me-1"></i>
                        Payment Rail: <?php echo strtoupper(htmlspecialchars($destination['payment_rail'])); ?>
                    </div>
                    <?php endif; ?>
                </div>
                <?php endif; ?>
            </div>
        <?php endif; ?>

        <!-- Transactions List -->
        <?php if (empty($history)): ?>
            <div class="card p-5">
                <div class="empty-state">
                    <div class="empty-icon">📭</div>
                    <h3>No Transaction History</h3>
                    <p class="text-muted mb-4">
                        This virtual account has no transaction history yet.
                    </p>
                </div>
            </div>
        <?php else: ?>
            <div class="card p-4">
                <?php foreach ($grouped_history as $date_label => $transactions): ?>
                    <!-- Date Header -->
                    <div class="date-header">
                        <span class="date-label"><?php echo htmlspecialchars($date_label); ?></span>
                        <div class="date-line"></div>
                    </div>

                    <!-- Transactions for this date -->
                    <?php foreach ($transactions as $tx): ?>
                        <?php
                        // Determine transaction type and status
                        $txType = $tx['type'] ?? $tx['transaction_type'] ?? 'unknown';
                        $status = $tx['status'] ?? $tx['state'] ?? $txType;
                        $amount = $tx['amount'] ?? $tx['value'] ?? 0;
                        $currency = $tx['currency'] ?? $tx['fiat_currency'] ?? 'USD';
                        $isCredit = ($tx['direction'] ?? $txType) === 'credit' || $txType === 'deposit' || $amount > 0;
                        
                        // Format amount
                        $displayAmount = abs(floatval($amount));
                        $amountSign = $isCredit ? '+' : '-';
                        
                        // Extract important fields first
                        $receipt = $tx['receipt'] ?? [];
                        $source = $tx['source'] ?? [];
                        $senderName = $source['sender_name'] ?? null;
                        
                        // Transaction description - use sender name if available, otherwise use transaction type
                        if (!empty($senderName)) {
                            $description = htmlspecialchars($senderName);
                        } else {
                            $description = ucfirst(str_replace('_', ' ', $txType));
                        }
                        
                        // Timestamp - convert to UTC+3
                        $timestamp = $tx['created_at'] ?? $tx['timestamp'] ?? $tx['date'] ?? '';
                        if ($timestamp) {
                            $date = new DateTime($timestamp, new DateTimeZone('UTC'));
                            $date->setTimezone(new DateTimeZone('Europe/Istanbul')); // UTC+3
                            $timeDisplay = $date->format('M j, Y g:i A');
                        } else {
                            $timeDisplay = '';
                        }
                        
                        $initialAmount = $receipt['initial_amount'] ?? $tx['initial_amount'] ?? null;
                        $developerFee = $receipt['developer_fee'] ?? $tx['developer_fee_amount'] ?? $tx['developer_fee'] ?? null;
                        $subtotalAmount = $receipt['subtotal_amount'] ?? $tx['subtotal_amount'] ?? null;
                        $exchangeRate = $receipt['exchange_rate'] ?? $tx['exchange_rate'] ?? null;
                        $bic = $source['bic'] ?? null;
                        $iban = $source['iban'] ?? null;
                        $uetr = $source['uetr'] ?? null;
                        $paymentScheme = $source['payment_scheme'] ?? null;
                        $finalAmount = $receipt['final_amount'] ?? null;
                        $depositId = $tx['deposit_id'] ?? null;
                        // Extract receipt URL - check multiple possible locations
                        $receiptUrl = $receipt['url'] ?? $tx['receipt']['url'] ?? $tx['receipt_url'] ?? null;
                        ?>
                        
                        <div class="transaction-card" onclick="toggleTransactionDetails(this)">
                            <div class="transaction-header">
                                <div class="transaction-icon" style="background: <?php echo $isCredit ? 'rgba(16, 185, 129, 0.2)' : 'rgba(255, 107, 107, 0.2)'; ?>;">
                                    <i class="fas fa-<?php echo $isCredit ? 'arrow-down' : 'arrow-up'; ?>" 
                                       style="color: <?php echo $isCredit ? '#10b981' : '#ff6b6b'; ?>;"></i>
                                </div>
                                <div class="transaction-details" style="flex: 1;">
                                    <div class="transaction-type">
                                        <?php echo $description; ?>
                                    </div>
                                    <div class="transaction-info">
                                        <?php if (!empty($timeDisplay)): ?>
                                            <span><?php echo $timeDisplay; ?></span>
                                        <?php endif; ?>
                                    </div>
                                </div>
                                <div class="transaction-amount">
                                    <div class="transaction-amount-value" style="color: <?php echo $isCredit ? '#10b981' : '#ff6b6b'; ?>;">
                                        <?php echo $amountSign . number_format($displayAmount, 2); ?> <?php echo strtoupper($currency); ?>
                                    </div>
                                </div>
                                <i class="fas fa-chevron-down expand-icon"></i>
                            </div>
                            
                            <div class="transaction-details-expanded">
                                <!-- Transaction Details Section -->
                                <div class="detail-section">
                                    <div class="detail-section-title">Transaction Details</div>
                                    <div class="detail-grid">
                                        <?php if ($depositId): ?>
                                        <div class="detail-item">
                                            <span class="detail-label">Deposit ID</span>
                                            <span class="detail-value"><?php echo htmlspecialchars($depositId); ?></span>
                                        </div>
                                        <?php endif; ?>
                                        
                                        <?php if ($timestamp): ?>
                                        <div class="detail-item">
                                            <span class="detail-label">Created At</span>
                                            <span class="detail-value"><?php echo htmlspecialchars($timeDisplay); ?></span>
                                        </div>
                                        <?php endif; ?>
                                        
                                        <?php if ($receiptUrl): ?>
                                        <div class="detail-item" style="grid-column: 1 / -1;">
                                            <span class="detail-label">Receipt URL</span>
                                            <span class="detail-value">
                                                <a href="<?php echo htmlspecialchars($receiptUrl); ?>" target="_blank" rel="noopener noreferrer" 
                                                   style="color: var(--primary); text-decoration: none; word-break: break-all; display: inline-flex; align-items: center; gap: 6px;">
                                                    <i class="fas fa-external-link-alt"></i>
                                                    <?php echo htmlspecialchars($receiptUrl); ?>
                                                </a>
                                            </span>
                                        </div>
                                        <?php endif; ?>
                                    </div>
                                </div>
                                
                                <!-- Amount Details Section -->
                                <div class="detail-section">
                                    <div class="detail-section-title">Amount Details</div>
                                    <div class="detail-grid">
                                        <?php if ($initialAmount !== null): ?>
                                        <div class="detail-item">
                                            <span class="detail-label">Initial Amount</span>
                                            <span class="detail-value"><?php echo number_format(floatval($initialAmount), 2); ?></span>
                                        </div>
                                        <?php endif; ?>
                                        
                                        <?php if ($developerFee !== null): ?>
                                        <div class="detail-item">
                                            <span class="detail-label">Developer Fee</span>
                                            <span class="detail-value"><?php echo number_format(floatval($developerFee), 2); ?></span>
                                        </div>
                                        <?php endif; ?>
                                        
                                        <?php if ($subtotalAmount !== null): ?>
                                        <div class="detail-item">
                                            <span class="detail-label">Subtotal Amount</span>
                                            <span class="detail-value"><?php echo number_format(floatval($subtotalAmount), 2); ?></span>
                                        </div>
                                        <?php endif; ?>
                                        
                                        <?php if ($exchangeRate !== null): ?>
                                        <div class="detail-item">
                                            <span class="detail-label">Exchange Rate</span>
                                            <span class="detail-value"><?php echo number_format(floatval($exchangeRate), 6); ?></span>
                                        </div>
                                        <?php endif; ?>
                                        
                                        <?php if ($finalAmount !== null): ?>
                                        <div class="detail-item">
                                            <span class="detail-label">Final Amount</span>
                                            <span class="detail-value" style="color: var(--primary); font-size: 1.1rem;"><?php echo number_format(floatval($finalAmount), 2); ?></span>
                                        </div>
                                        <?php endif; ?>
                                    </div>
                                </div>
                                
                                <!-- Payment Source Section -->
                                <?php if (!empty($source)): ?>
                                <div class="detail-section">
                                    <div class="detail-section-title">Payment Source</div>
                                    <div class="detail-grid">
                                        <?php if ($bic): ?>
                                        <div class="detail-item">
                                            <span class="detail-label">BIC</span>
                                            <span class="detail-value"><?php echo htmlspecialchars($bic); ?></span>
                                        </div>
                                        <?php endif; ?>
                                        
                                        <?php if ($iban): ?>
                                        <div class="detail-item">
                                            <span class="detail-label">IBAN</span>
                                            <span class="detail-value" style="font-family: monospace;"><?php echo htmlspecialchars($iban); ?></span>
                                        </div>
                                        <?php endif; ?>
                                        
                                        <?php if ($senderName): ?>
                                        <div class="detail-item">
                                            <span class="detail-label">Sender Name</span>
                                            <span class="detail-value"><?php echo htmlspecialchars($senderName); ?></span>
                                        </div>
                                        <?php endif; ?>
                                        
                                        <?php if ($uetr): ?>
                                        <div class="detail-item">
                                            <span class="detail-label">UETR</span>
                                            <span class="detail-value" style="font-family: monospace; font-size: 0.85rem;"><?php echo htmlspecialchars($uetr); ?></span>
                                        </div>
                                        <?php endif; ?>
                                        
                                        <?php if ($paymentScheme): ?>
                                        <div class="detail-item">
                                            <span class="detail-label">Payment Scheme</span>
                                            <span class="detail-value"><?php echo htmlspecialchars(strtoupper(str_replace('_', ' ', $paymentScheme))); ?></span>
                                        </div>
                                        <?php endif; ?>
                                        
                                        <?php if (isset($source['payment_rail'])): ?>
                                        <div class="detail-item">
                                            <span class="detail-label">Payment Rail</span>
                                            <span class="detail-value"><?php echo htmlspecialchars(strtoupper($source['payment_rail'])); ?></span>
                                        </div>
                                        <?php endif; ?>
                                        
                                        <?php if (isset($source['recipient_name'])): ?>
                                        <div class="detail-item">
                                            <span class="detail-label">Recipient Name</span>
                                            <span class="detail-value"><?php echo htmlspecialchars($source['recipient_name']); ?></span>
                                        </div>
                                        <?php endif; ?>
                                    </div>
                                </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php endforeach; ?>
            </div>
            
            <!-- Pagination Controls -->
            <?php if ($totalPages > 1): ?>
            <div class="pagination-container">
                <?php if ($page > 1): ?>
                    <a href="?page=<?php echo $page - 1; ?>" class="pagination-btn">
                        <i class="fas fa-chevron-left me-1"></i>Previous
                    </a>
                <?php else: ?>
                    <span class="pagination-btn disabled">
                        <i class="fas fa-chevron-left me-1"></i>Previous
                    </span>
                <?php endif; ?>
                
                <span class="pagination-info">
                    Page <?php echo $page; ?> of <?php echo $totalPages; ?>
                    <?php if ($totalCount > 0): ?>
                        (<?php echo number_format($totalCount); ?> total transactions)
                    <?php endif; ?>
                </span>
                
                <?php if ($page < $totalPages): ?>
                    <a href="?page=<?php echo $page + 1; ?>" class="pagination-btn">
                        Next<i class="fas fa-chevron-right ms-1"></i>
                    </a>
                <?php else: ?>
                    <span class="pagination-btn disabled">
                        Next<i class="fas fa-chevron-right ms-1"></i>
                    </span>
                <?php endif; ?>
            </div>
            <?php endif; ?>
        <?php endif; ?>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
    function toggleTransactionDetails(card) {
        const expanded = card.querySelector('.transaction-details-expanded');
        const isExpanded = expanded.classList.contains('show');
        
        if (isExpanded) {
            expanded.classList.remove('show');
            card.classList.remove('expanded');
        } else {
            expanded.classList.add('show');
            card.classList.add('expanded');
        }
    }

    function copyToClipboard(text, button) {
        navigator.clipboard.writeText(text).then(function() {
            const originalHTML = button.innerHTML;
            button.innerHTML = '<i class="fas fa-check"></i>Copied!';
            button.classList.add('copied');
            
            setTimeout(function() {
                button.innerHTML = originalHTML;
                button.classList.remove('copied');
            }, 2000);
        }).catch(function(err) {
            console.error('Failed to copy: ', err);
            alert('Failed to copy to clipboard');
        });
    }
    </script>
</body>
</html>
