<?php
/**
 * User - Transactions
 */
require_once __DIR__ . '/../config.php';
require_login();

$page_title = 'Transaction History';
$user_id = $_SESSION['user_id'];

$transactions = [];
try {
    $stmt = db()->prepare("SELECT * FROM transactions WHERE user_id = ? ORDER BY created_at DESC");
    $stmt->execute([$user_id]);
    $transactions = $stmt->fetchAll();
} catch (PDOException $e) {}

include __DIR__ . '/includes/header.php';
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <h2 class="fw-bold mb-0">Transaction History</h2>
</div>

<div class="card border-0 shadow-sm">
    <?php if (empty($transactions)): ?>
    <div class="card-body text-center py-5">
        <i class="bi bi-receipt text-muted" style="font-size: 4rem;"></i>
        <h4 class="mt-3">No Transactions Yet</h4>
        <p class="text-muted">You haven't made any transactions.</p>
    </div>
    <?php else: ?>
    <div class="table-responsive">
        <table class="table table-hover mb-0">
            <thead class="table-light">
                <tr>
                    <th>Transaction #</th>
                    <th>Type</th>
                    <th>Amount</th>
                    <th>Gateway</th>
                    <th>Status</th>
                    <th>Date</th>
                    <th>Invoice</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($transactions as $tx): ?>
                <tr>
                    <td><?php echo $tx['transaction_number']; ?></td>
                    <td><?php echo ucfirst(str_replace('_', ' ', $tx['transaction_type'])); ?></td>
                    <td class="fw-bold"><?php echo format_currency($tx['total_amount']); ?></td>
                    <td><?php echo ucfirst($tx['payment_gateway'] ?? 'N/A'); ?></td>
                    <td>
                        <span class="badge bg-<?php 
                            echo $tx['status'] === 'success' ? 'success' : 
                                ($tx['status'] === 'pending' ? 'warning' : 'danger'); 
                        ?>"><?php echo ucfirst($tx['status']); ?></span>
                    </td>
                    <td><?php echo format_date($tx['created_at']); ?></td>
                    <td>
                        <?php if ($tx['status'] === 'success'): ?>
                        <a href="invoice.php?id=<?php echo $tx['id']; ?>" class="btn btn-sm btn-outline-primary">
                            <i class="bi bi-download"></i>
                        </a>
                        <?php endif; ?>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php endif; ?>
</div>

<?php include __DIR__ . '/includes/footer.php'; ?>
