<?php
/**
 * Tom's Java Jive - Customer Wallet
 */

$pageTitle = "My Wallet - Tom's Java Jive";
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/auth.php';

CustomerAuth::require();
$customer = CustomerAuth::getFullUser();
$currentPage = 'wallet';

// Pagination
$page = max(1, intval($_GET['page'] ?? 1));

$total = db()->count('wallet_transactions', 'customer_id = :id', ['id' => $customer['customer_id']]);
$pagination = paginate($total, $page, 15);

$transactions = db()->fetchAll(
    "SELECT * FROM wallet_transactions WHERE customer_id = :id ORDER BY created_at DESC LIMIT :limit OFFSET :offset",
    ['id' => $customer['customer_id'], 'limit' => $pagination['per_page'], 'offset' => $pagination['offset']]
);

$extraHead = '<link rel="stylesheet" href="/assets/css/account.css?v='. filemtime(__DIR__ . '/../assets/css/account.css') .'">';
require_once __DIR__ . '/../includes/header.php';
require_once __DIR__ . '/includes/sidebar.php';
?>

<div class="account-header">
    <h1>My Wallet</h1>
    <p class="text-muted">View your wallet balance and transaction history</p>
</div>

<!-- Wallet Balance Card -->
<div class="section-card" style="background: linear-gradient(135deg, var(--color-primary), #c4420f); color: white;">
    <div class="section-card-body" style="padding: 2rem;">
        <div style="display: flex; justify-content: space-between; align-items: center;">
            <div>
                <div style="font-size: 0.875rem; opacity: 0.9; margin-bottom: 0.5rem;">Available Balance</div>
                <div style="font-size: 2.5rem; font-weight: 700;"><?= formatCurrency($customer['wallet_balance'] ?? 0) ?></div>
            </div>
            <div style="background: rgba(255,255,255,0.2); padding: 1.5rem; border-radius: var(--radius-lg);">
                <i class="fas fa-wallet" style="font-size: 2.5rem;"></i>
            </div>
        </div>
        
        <div style="display: flex; gap: 1rem; margin-top: 1.5rem;">
            <div style="flex: 1; background: rgba(255,255,255,0.15); padding: 1rem; border-radius: var(--radius-md); text-align: center;">
                <div style="font-size: 1.25rem; font-weight: 600;"><?= number_format($customer['reward_points'] ?? 0) ?></div>
                <div style="font-size: 0.75rem; opacity: 0.9;">Reward Points</div>
            </div>
            <div style="flex: 1; background: rgba(255,255,255,0.15); padding: 1rem; border-radius: var(--radius-md); text-align: center;">
                <div style="font-size: 1.25rem; font-weight: 600;"><?= formatCurrency(($customer['reward_points'] ?? 0) * 0.01) ?></div>
                <div style="font-size: 0.75rem; opacity: 0.9;">Points Value</div>
            </div>
        </div>
    </div>
</div>

<!-- Info Cards -->
<div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 1rem; margin-bottom: 1.5rem;">
    <div class="section-card">
        <div class="section-card-body text-center">
            <i class="fas fa-gift" style="font-size: 2rem; color: var(--color-primary); margin-bottom: 0.75rem;"></i>
            <h4 style="margin: 0 0 0.5rem;">Have a Gift Card?</h4>
            <p class="text-muted" style="font-size: 0.875rem; margin-bottom: 1rem;">Redeem your gift card to add funds to your wallet</p>
            <button class="btn btn-secondary" onclick="Modal.open('redeemModal')">
                <i class="fas fa-plus"></i> Redeem Gift Card
            </button>
        </div>
    </div>
    <div class="section-card">
        <div class="section-card-body text-center">
            <i class="fas fa-star" style="font-size: 2rem; color: var(--color-warning); margin-bottom: 0.75rem;"></i>
            <h4 style="margin: 0 0 0.5rem;">Earn More Points</h4>
            <p class="text-muted" style="font-size: 0.875rem; margin-bottom: 1rem;">Earn 1 point for every $1 spent. 100 points = $1</p>
            <a href="/shop.php" class="btn btn-primary">
                <i class="fas fa-shopping-cart"></i> Shop Now
            </a>
        </div>
    </div>
</div>

<!-- Transaction History -->
<div class="section-card">
    <div class="section-card-header">
        <h3><i class="fas fa-history"></i> Transaction History</h3>
    </div>
    <div class="section-card-body" style="padding: 0;">
        <?php if (empty($transactions)): ?>
            <div class="text-center" style="padding: 3rem;">
                <i class="fas fa-receipt" style="font-size: 3rem; color: var(--color-text-muted); margin-bottom: 1rem;"></i>
                <p class="text-muted">No transactions yet</p>
            </div>
        <?php else: ?>
            <table class="table">
                <thead>
                    <tr>
                        <th>Date</th>
                        <th>Description</th>
                        <th>Type</th>
                        <th style="text-align: right;">Amount</th>
                        <th style="text-align: right;">Balance</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($transactions as $tx): ?>
                        <tr>
                            <td><?= formatDate($tx['created_at']) ?></td>
                            <td><?= htmlspecialchars($tx['description'] ?? ucfirst($tx['type'])) ?></td>
                            <td>
                                <?php
                                $typeIcon = match($tx['type']) {
                                    'deposit', 'gift_card', 'refund' => 'fa-arrow-down',
                                    'purchase', 'withdrawal' => 'fa-arrow-up',
                                    default => 'fa-exchange-alt'
                                };
                                $typeColor = $tx['amount'] > 0 ? 'success' : 'error';
                                ?>
                                <span class="badge badge-<?= $typeColor ?>">
                                    <i class="fas <?= $typeIcon ?>"></i> <?= ucfirst(str_replace('_', ' ', $tx['type'])) ?>
                                </span>
                            </td>
                            <td style="text-align: right; font-weight: 600; color: <?= $tx['amount'] > 0 ? 'var(--color-success)' : 'var(--color-error)' ?>;">
                                <?= $tx['amount'] > 0 ? '+' : '' ?><?= formatCurrency($tx['amount']) ?>
                            </td>
                            <td style="text-align: right;"><?= formatCurrency($tx['balance_after']) ?></td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        <?php endif; ?>
    </div>
</div>

<?php if ($pagination['total_pages'] > 1): ?>
    <div style="display: flex; justify-content: center; gap: 0.5rem; margin-top: 2rem;">
        <?php for ($i = 1; $i <= $pagination['total_pages']; $i++): ?>
            <a href="/account/wallet.php?page=<?= $i ?>" 
               class="btn <?= $i === $page ? 'btn-primary' : 'btn-secondary' ?>">
                <?= $i ?>
            </a>
        <?php endfor; ?>
    </div>
<?php endif; ?>

<!-- Redeem Gift Card Modal -->
<div class="modal-overlay" id="redeemModal">
    <div class="modal">
        <div class="modal-header">
            <h3 class="modal-title">Redeem Gift Card</h3>
            <button type="button" class="modal-close" onclick="Modal.close('redeemModal')">&times;</button>
        </div>
        <form action="/api/redeem-gift-card.php" method="POST" id="redeemForm">
            <div class="modal-body">
                <div class="form-group">
                    <label class="form-label">Gift Card Code</label>
                    <input type="text" name="code" class="form-input" required placeholder="XXXX-XXXX-XXXX" style="text-transform: uppercase; text-align: center; font-size: 1.25rem; letter-spacing: 2px;">
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="Modal.close('redeemModal')">Cancel</button>
                <button type="submit" class="btn btn-primary">
                    <i class="fas fa-gift"></i> Redeem
                </button>
            </div>
        </form>
    </div>
</div>

<script>
document.getElementById('redeemForm').addEventListener('submit', async function(e) {
    e.preventDefault();
    const code = this.querySelector('[name="code"]').value.trim();
    
    try {
        const response = await fetch('/api/redeem-gift-card.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ code })
        });
        const data = await response.json();
        
        if (data.error) {
            alert(data.error);
        } else {
            alert('Success! ' + data.message);
            window.location.reload();
        }
    } catch (err) {
        alert('Failed to redeem gift card. Please try again.');
    }
});
</script>

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