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

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

CustomerAuth::require();

$customer = CustomerAuth::getFullUser();

// Get recent orders
$recentOrders = db()->fetchAll(
    "SELECT * FROM orders WHERE customer_id = :id ORDER BY created_at DESC LIMIT 5",
    ['id' => $customer['customer_id']]
);

// Get order stats
$orderStats = db()->fetch(
    "SELECT COUNT(*) as total_orders, COALESCE(SUM(total), 0) as total_spent 
     FROM orders WHERE customer_id = :id AND payment_status = 'paid'",
    ['id' => $customer['customer_id']]
);

// Get wishlist count
$wishlistCount = db()->count('wishlist', 'customer_id = :id', ['id' => $customer['customer_id']]);

// Get recent wallet transactions
$walletTransactions = db()->fetchAll(
    "SELECT * FROM wallet_transactions WHERE customer_id = :id ORDER BY created_at DESC LIMIT 5",
    ['id' => $customer['customer_id']]
);

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

<section class="section" style="padding-top: 2rem;">
    <div class="container">
        <?php if (hasFlash('success')): ?>
            <div class="alert alert-success mb-2">
                <i class="fas fa-check-circle"></i> <?= getFlash('success') ?>
            </div>
        <?php endif; ?>
        
        <div class="account-layout">
            <!-- Sidebar -->
            <aside class="account-sidebar">
                <div class="account-sidebar-user">
                    <div class="account-avatar">
                        <?= strtoupper(substr($customer['name'] ?? $customer['email'], 0, 1)) ?>
                    </div>
                    <h3><?= htmlspecialchars($customer['name'] ?? 'Customer') ?></h3>
                    <p><?= htmlspecialchars($customer['email']) ?></p>
                </div>

                <ul class="account-nav">
                    <li><a href="/account/" class="active"><i class="fas fa-tachometer-alt"></i> Dashboard</a></li>
                    <li><a href="/account/orders.php"><i class="fas fa-shopping-bag"></i> My Orders</a></li>
                    <li><a href="/account/wishlist.php"><i class="fas fa-heart"></i> Wishlist</a></li>
                    <li><a href="/account/wallet.php"><i class="fas fa-wallet"></i> Wallet</a></li>
                    <li><a href="/account/addresses.php"><i class="fas fa-map-marker-alt"></i> Addresses</a></li>
                    <li><a href="/account/profile.php"><i class="fas fa-user"></i> Profile</a></li>
                    <li><a href="/account/reviews.php"><i class="fas fa-star"></i> My Reviews</a></li>
                    <li><a href="/logout.php" class="danger"><i class="fas fa-sign-out-alt"></i> Logout</a></li>
                </ul>
            </aside>
            
            <!-- Main Content -->
            <div class="account-content">
                <div class="account-header">
                    <h1>Welcome back, <?= htmlspecialchars($customer['name'] ?? 'Coffee Lover') ?>!</h1>
                    <p class="text-muted">Here's an overview of your account activity.</p>
                </div>
                
                <!-- Stats Grid -->
                <div class="dashboard-grid">
                    <div class="dashboard-stat">
                        <div class="dashboard-stat-icon primary">
                            <i class="fas fa-shopping-bag"></i>
                        </div>
                        <div class="dashboard-stat-value"><?= $orderStats['total_orders'] ?? 0 ?></div>
                        <div class="dashboard-stat-label">Total Orders</div>
                    </div>
                    <div class="dashboard-stat">
                        <div class="dashboard-stat-icon success">
                            <i class="fas fa-dollar-sign"></i>
                        </div>
                        <div class="dashboard-stat-value"><?= formatCurrency($orderStats['total_spent'] ?? 0) ?></div>
                        <div class="dashboard-stat-label">Total Spent</div>
                    </div>
                    <div class="dashboard-stat">
                        <div class="dashboard-stat-icon warning">
                            <i class="fas fa-wallet"></i>
                        </div>
                        <div class="dashboard-stat-value"><?= formatCurrency($customer['wallet_balance'] ?? 0) ?></div>
                        <div class="dashboard-stat-label">Wallet Balance</div>
                    </div>
                    <div class="dashboard-stat">
                        <div class="dashboard-stat-icon primary">
                            <i class="fas fa-star"></i>
                        </div>
                        <div class="dashboard-stat-value"><?= number_format($customer['reward_points'] ?? 0) ?></div>
                        <div class="dashboard-stat-label">Reward Points</div>
                    </div>
                </div>
                
                <!-- Recent Orders -->
                <div class="section-card">
                    <div class="section-card-header">
                        <h3><i class="fas fa-clock"></i> Recent Orders</h3>
                        <a href="/account/orders.php" class="btn btn-sm btn-secondary">View All</a>
                    </div>
                    <div class="section-card-body">
                        <?php if (empty($recentOrders)): ?>
                            <p class="text-muted text-center" style="padding: 2rem 0;">
                                <i class="fas fa-shopping-bag" style="font-size: 2rem; opacity: 0.5; display: block; margin-bottom: 1rem;"></i>
                                No orders yet. <a href="/shop.php">Start shopping!</a>
                            </p>
                        <?php else: ?>
                            <?php foreach ($recentOrders as $order): ?>
                                <div class="order-item">
                                    <div class="order-info">
                                        <h4><a href="/account/order.php?id=<?= $order['order_id'] ?>">Order #<?= htmlspecialchars($order['order_number']) ?></a></h4>
                                        <p><?= formatDate($order['created_at']) ?> · <?= count(json_decode($order['items'], true)) ?> items</p>
                                    </div>
                                    <div style="text-align: right;">
                                        <div style="font-weight: 600; margin-bottom: 0.25rem;"><?= formatCurrency($order['total']) ?></div>
                                        <?php
                                        $statusClass = match($order['order_status']) {
                                            'pending' => 'warning',
                                            'confirmed', 'processing' => 'primary',
                                            'shipped' => 'primary',
                                            'delivered' => 'success',
                                            'cancelled', 'refunded' => 'error',
                                            default => 'primary'
                                        };
                                        ?>
                                        <span class="badge badge-<?= $statusClass ?>"><?= ucfirst($order['order_status']) ?></span>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
                </div>
                
                <!-- Wallet Activity -->
                <?php if (!empty($walletTransactions)): ?>
                <div class="section-card">
                    <div class="section-card-header">
                        <h3><i class="fas fa-wallet"></i> Recent Wallet Activity</h3>
                        <a href="/account/wallet.php" class="btn btn-sm btn-secondary">View All</a>
                    </div>
                    <div class="section-card-body">
                        <?php foreach ($walletTransactions as $tx): ?>
                            <div class="order-item">
                                <div class="order-info">
                                    <h4><?= htmlspecialchars($tx['description'] ?? ucfirst($tx['type'])) ?></h4>
                                    <p><?= formatDateTime($tx['created_at']) ?></p>
                                </div>
                                <div style="text-align: right;">
                                    <div style="font-weight: 600; color: <?= $tx['amount'] > 0 ? 'var(--color-success)' : 'var(--color-error)' ?>;">
                                        <?= $tx['amount'] > 0 ? '+' : '' ?><?= formatCurrency($tx['amount']) ?>
                                    </div>
                                    <small class="text-muted">Balance: <?= formatCurrency($tx['balance_after']) ?></small>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</section>

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