<?php
// STEP 1: Handle all setup, security, and global data
require_once 'dashboard-logic.php';

// STEP 2: Set the page-specific title
$page_title = 'My Wallet';

// STEP 3: Display the header/layout
require_once 'header.php'; 

// --- PAGE-SPECIFIC LOGIC ---
// Note: $conn and $user_id are available from dashboard-logic.php

// Auto-create wallet if it doesn't exist (robust logic from previous version)
$stmt = $conn->prepare("SELECT id, balance FROM user_wallets WHERE user_id = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$wallet_result = $stmt->get_result();
$wallet = $wallet_result->fetch_assoc();
$stmt->close();

if (!$wallet) {
    $stmt_create = $conn->prepare("INSERT INTO user_wallets (user_id, balance) VALUES (?, 0.00)");
    $stmt_create->bind_param("i", $user_id);
    $stmt_create->execute();
    $stmt_create->close();
    $wallet = ['id' => $conn->insert_id, 'balance' => 0.00];
}

$wallet_balance = $wallet['balance'];

// --- NEW: Handle transaction filtering ---
$filter_type = $_GET['filter_type'] ?? '';
$where_clauses = ["user_id = ?"];
$params = [$user_id];
$types = 'i';

if (!empty($filter_type)) {
    $where_clauses[] = "type = ?";
    $params[] = $filter_type;
    $types .= 's';
}
$where_sql = "WHERE " . implode(' AND ', $where_clauses);

// Fetch transaction history for this user
$stmt_trans = $conn->prepare("SELECT type, amount, description, reference_id, created_at FROM wallet_transactions $where_sql ORDER BY created_at DESC");
$stmt_trans->bind_param($types, ...$params);
$stmt_trans->execute();
$transactions_result = $stmt_trans->get_result();
$transactions = $transactions_result->fetch_all(MYSQLI_ASSOC);
$stmt_trans->close();

// Helper function to get styling info for each transaction type
function get_transaction_style($type) {
    switch ($type) {
        case 'Deposit': return ['icon' => 'bi-arrow-down-circle-fill', 'color' => 'success'];
        case 'Refund': return ['icon' => 'bi-arrow-counterclockwise', 'color' => 'info'];
        case 'Payment': return ['icon' => 'bi-cart-dash-fill', 'color' => 'danger'];
        case 'Withdrawal': return ['icon' => 'bi-arrow-up-circle-fill', 'color' => 'warning'];
        default: return ['icon' => 'bi-question-circle-fill', 'color' => 'secondary'];
    }
}
?>

<div class="pt-3 pb-2 mb-4 border-bottom">
    <h1 class="h2"><i class="bi bi-wallet2 me-2"></i>My Wallet</h1>
</div>

<div class="row">
    <div class="col-lg-4 mb-4">
        <div class="card shadow-sm border-0 h-100">
            <div class="card-body text-center p-4">
                <p class="text-muted mb-1 mt-2">Current Balance</p>
                <h1 class="display-4 fw-bold mb-4" style="color: var(--bs-primary);"><?php echo format_price($wallet_balance); ?></h1>
                <div class="d-grid gap-2">
                    <a href="top-up.php" class="btn btn-primary btn-lg"><i class="bi bi-plus-circle-fill me-2"></i> Top-Up Balance</a>
                    <a href="withdraw.php" class="btn btn-outline-secondary">Request Withdrawal</a>
                </div>
            </div>
        </div>
    </div>

    <div class="col-lg-8">
        <div class="card shadow-sm border-0">
            <div class="card-header bg-white border-0 pt-3 d-flex justify-content-between align-items-center">
                <h5 class="mb-0">Transaction History</h5>
                <form method="GET" class="d-flex gap-2">
                    <select name="filter_type" class="form-select form-select-sm" style="width: 150px;">
                        <option value="">All Types</option>
                        <option value="Deposit" <?php if($filter_type == 'Deposit') echo 'selected'; ?>>Deposits</option>
                        <option value="Payment" <?php if($filter_type == 'Payment') echo 'selected'; ?>>Payments</option>
                        <option value="Refund" <?php if($filter_type == 'Refund') echo 'selected'; ?>>Refunds</option>
                        <option value="Withdrawal" <?php if($filter_type == 'Withdrawal') echo 'selected'; ?>>Withdrawals</option>
                    </select>
                    <button type="submit" class="btn btn-sm btn-secondary">Filter</button>
                </form>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-hover align-middle">
                        <tbody>
                            <?php if (empty($transactions)): ?>
                                <tr>
                                    <td colspan="3" class="text-center p-5">
                                        <i class="bi bi-search fs-2 text-muted"></i>
                                        <p class="mt-2 mb-0 text-muted">No transactions found.</p>
                                    </td>
                                </tr>
                            <?php else: ?>
                                <?php foreach ($transactions as $tx): 
                                    $style = get_transaction_style($tx['type']);
                                    $is_credit = in_array($tx['type'], ['Deposit', 'Refund']);
                                ?>
                                    <tr>
                                        <td class="text-center" style="width: 60px;">
                                            <i class="bi <?php echo $style['icon']; ?> fs-2 text-<?php echo $style['color']; ?>"></i>
                                        </td>
                                        <td>
                                            <strong class="d-block"><?php echo htmlspecialchars($tx['type']); ?></strong>
                                            <small class="text-muted"><?php echo htmlspecialchars($tx['description']); ?></small>
                                        </td>
                                        <td class="text-end">
                                            <strong class="text-nowrap <?php echo $is_credit ? 'text-success' : 'text-danger'; ?>">
                                                <?php echo $is_credit ? '+' : '-'; ?>
                                                <?php echo format_price($tx['amount']); ?>
                                            </strong>
                                            <small class="d-block text-muted text-nowrap"><?php echo date('M d, Y', strtotime($tx['created_at'])); ?></small>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<?php 
require_once 'footer.php'; 
?>
