<?php
require_once 'functions.php';
requireAuth();

$user = getCurrentUser();
$db = getDB();

// Pagination
$page = max(1, intval($_GET['page'] ?? 1));
$limit = 20;
$offset = ($page - 1) * $limit;

// Filters
$type = $_GET['type'] ?? '';
$status = $_GET['status'] ?? '';
$dateFrom = $_GET['date_from'] ?? '';
$dateTo = $_GET['date_to'] ?? '';

// Build query
$where = "WHERE user_id = ?";
$params = [$user['id']];
$types = 'i';

if ($type) {
    $where .= " AND transaction_type = ?";
    $params[] = $type;
    $types .= 's';
}
if ($status) {
    $where .= " AND status = ?";
    $params[] = $status;
    $types .= 's';
}
if ($dateFrom) {
    $where .= " AND created_at >= ?";
    $params[] = $dateFrom . ' 00:00:00';
    $types .= 's';
}
if ($dateTo) {
    $where .= " AND created_at <= ?";
    $params[] = $dateTo . ' 23:59:59';
    $types .= 's';
}

// Get total count
$countStmt = $db->prepare("SELECT COUNT(*) as total FROM transactions $where");
$countStmt->bind_param($types, ...$params);
$countStmt->execute();
$totalRecords = $countStmt->get_result()->fetch_assoc()['total'];
$totalPages = ceil($totalRecords / $limit);

// Get transactions
$query = "SELECT * FROM transactions $where ORDER BY created_at DESC LIMIT ? OFFSET ?";
$params[] = $limit;
$params[] = $offset;
$types .= 'ii';

$stmt = $db->prepare($query);
$stmt->bind_param($types, ...$params);
$stmt->execute();
$transactions = $stmt->get_result();

$flash = getFlash();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Transaction History - <?php echo SITE_NAME; ?></title>
    <link rel="stylesheet" href="assets/css/style.css">
</head>
<body>
    <?php include 'includes/client-sidebar.php'; ?>
    
    <div class="main-content">
        <?php include 'includes/client-header.php'; ?>
        
        <div class="page-content">
            <?php if ($flash): ?>
                <div class="alert alert-<?php echo $flash['type']; ?> fade-in">
                    <span><?php echo $flash['type'] === 'success' ? '✓' : '⚠'; ?></span> <?php echo e($flash['message']); ?>
                </div>
            <?php endif; ?>
            
            <!-- Filters -->
            <div class="card" style="margin-bottom: 24px;">
                <div class="card-body">
                    <form method="GET" action="" style="display: grid; grid-template-columns: repeat(4, 1fr) auto; gap: 12px; align-items: end;">
                        <div class="form-group" style="margin-bottom: 0;">
                            <label class="form-label">Transaction Type</label>
                            <select name="type" class="form-control">
                                <option value="">All Types</option>
                                <option value="credit" <?php echo $type === 'credit' ? 'selected' : ''; ?>>Credit</option>
                                <option value="debit" <?php echo $type === 'debit' ? 'selected' : ''; ?>>Debit</option>
                                <option value="transfer" <?php echo $type === 'transfer' ? 'selected' : ''; ?>>Transfer</option>
                                <option value="fee" <?php echo $type === 'fee' ? 'selected' : ''; ?>>Fee</option>
                            </select>
                        </div>
                        <div class="form-group" style="margin-bottom: 0;">
                            <label class="form-label">Status</label>
                            <select name="status" class="form-control">
                                <option value="">All Statuses</option>
                                <option value="pending" <?php echo $status === 'pending' ? 'selected' : ''; ?>>Pending</option>
                                <option value="completed" <?php echo $status === 'completed' ? 'selected' : ''; ?>>Completed</option>
                                <option value="failed" <?php echo $status === 'failed' ? 'selected' : ''; ?>>Failed</option>
                                <option value="cancelled" <?php echo $status === 'cancelled' ? 'selected' : ''; ?>>Cancelled</option>
                            </select>
                        </div>
                        <div class="form-group" style="margin-bottom: 0;">
                            <label class="form-label">From</label>
                            <input type="date" name="date_from" class="form-control" value="<?php echo e($dateFrom); ?>">
                        </div>
                        <div class="form-group" style="margin-bottom: 0;">
                            <label class="form-label">To</label>
                            <input type="date" name="date_to" class="form-control" value="<?php echo e($dateTo); ?>">
                        </div>
                        <div style="display: flex; gap: 8px;">
                            <button type="submit" class="btn btn-primary">Filter</button>
                            <a href="transactions.php" class="btn btn-secondary">Reset</a>
                        </div>
                    </form>
                </div>
            </div>
            <style>
                /* Professional Transaction Status Badges */
.status-badge {
    display: inline-block;
    padding: 4px 12px;
    border-radius: 50px; /* Fully rounded 'pill' shape */
    font-size: 11px;
    font-weight: 700;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

/* Status: Completed (Success) */
.status-badge.completed {
    background-color: #dcfce7; 
    color: #166534;
    border: 1px solid #bbf7d0;
}

/* Status: Pending (Warning/Neutral) */
.status-badge.pending {
    background-color: #fef3c7; 
    color: #92400e;
    border: 1px solid #fde68a;
}

/* Status: Failed/Cancelled (Danger) */
.status-badge.failed, 
.status-badge.cancelled {
    background-color: #fee2e2; 
    color: #991b1b;
    border: 1px solid #fecaca;
}

/* Status: On Hold (Info/Secondary) */
.status-badge.on_hold {
    background-color: #e0f2fe; 
    color: #075985;
    border: 1px solid #bae6fd;
}
            </style>
            <!-- Transactions Table -->
            <div class="card">
                <div class="card-body" style="padding: 0;">
                    <div class="table-container">
                        <table class="data-table">
                            <thead>
                                <tr>
                                    <th>Reference</th>
                                    <th>Type</th>
                                    <th>Description</th>
                                    <th>Beneficiary</th>
                                    <th>Amount</th>
                                    <th>Status</th>
                                    <th>Date</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if ($transactions->num_rows > 0): ?>
                                    <?php while ($tx = $transactions->fetch_assoc()): ?>
                                        <tr>
                                            <td><code style="font-size: 11px;"><?php echo e($tx['reference_number']); ?></code></td>
                                            <td>
                                                <span class="status-badge <?php 
                                                    echo $tx['transaction_type'] === 'credit' ? 'success' : 
                                                        ($tx['transaction_type'] === 'debit' ? 'danger' : 
                                                        ($tx['transaction_type'] === 'fee' ? 'warning' : 'info')); 
                                                ?>" style="font-size: 11px;">
                                                    <?php echo ucfirst(e($tx['transaction_type'])); ?>
                                                </span>
                                            </td>
                                            <td><?php echo e($tx['description'] ?? '-'); ?></td>
                                            <td><?php echo e($tx['beneficiary_name'] ?? '-'); ?></td>
                                            <td style="font-weight: 700; <?php echo in_array($tx['transaction_type'], ['credit']) ? 'color: var(--success);' : 'color: var(--danger);' ?>">
                                                <?php echo in_array($tx['transaction_type'], ['credit', 'refund']) ? '+' : '-'; ?><?php echo formatCurrency($tx['amount']); ?>
                                            </td>
                                            <td>
    <span class="status-badge <?php echo strtolower(e($tx['status'])); ?>">
        <?php echo ucfirst(e($tx['status'])); ?>
    </span>
</td>
                                            <td style="font-size: 12px;"><?php echo formatDate($tx['created_at']); ?></td>
                                        </tr>
                                    <?php endwhile; ?>
                                <?php else: ?>
                                    <tr>
                                        <td colspan="7">
                                            <div class="empty-state" style="padding: 40px;">
                                                <div class="empty-state-icon">📋</div>
                                                <h3>No Transactions Found</h3>
                                                <p>No transactions match your current filters.</p>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                    
                    <!-- Pagination -->
                    <?php if ($totalPages > 1): ?>
                    <div style="padding: 16px 24px; border-top: 1px solid var(--gray-200);">
                        <div class="pagination">
                            <?php if ($page > 1): ?>
                                <a href="?page=<?php echo $page - 1; ?>&type=<?php echo e($type); ?>&status=<?php echo e($status); ?>&date_from=<?php echo e($dateFrom); ?>&date_to=<?php echo e($dateTo); ?>">← Prev</a>
                            <?php endif; ?>
                            
                            <?php for ($i = max(1, $page - 2); $i <= min($totalPages, $page + 2); $i++): ?>
                                <?php if ($i === $page): ?>
                                    <span><?php echo $i; ?></span>
                                <?php else: ?>
                                    <a href="?page=<?php echo $i; ?>&type=<?php echo e($type); ?>&status=<?php echo e($status); ?>&date_from=<?php echo e($dateFrom); ?>&date_to=<?php echo e($dateTo); ?>"><?php echo $i; ?></a>
                                <?php endif; ?>
                            <?php endfor; ?>
                            
                            <?php if ($page < $totalPages): ?>
                                <a href="?page=<?php echo $page + 1; ?>&type=<?php echo e($type); ?>&status=<?php echo e($status); ?>&date_from=<?php echo e($dateFrom); ?>&date_to=<?php echo e($dateTo); ?>">Next →</a>
                            <?php endif; ?>
                        </div>
                        <p style="text-align: center; font-size: 12px; color: var(--gray); margin-top: 8px;">
                            Showing <?php echo (($page - 1) * $limit) + 1; ?> - <?php echo min($page * $limit, $totalRecords); ?> of <?php echo $totalRecords; ?> transactions
                        </p>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
    
    <script src="assets/js/main.js"></script>
</body>
</html>
