<?php
session_start();
require 'config/db.php';
require_once 'includes/functions.php';

// 1. Security: Check if logged in
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

$user_id = $_SESSION['user_id'];
$user_name = $_SESSION['user_name'];

// 2. Fetch Real-Time User Data (Wallet & Code)
$uStmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
$uStmt->execute([$user_id]);
$userData = $uStmt->fetch();

// Fallback if user data fetch fails
if (!$userData) {
    $userData = ['wallet_balance' => 0, 'referral_code' => 'ERROR'];
}

// 3. Fetch Recent Orders
$stmt = $pdo->prepare("SELECT * FROM orders WHERE user_id = ? ORDER BY created_at DESC LIMIT 5");
$stmt->execute([$user_id]);
$orders = $stmt->fetchAll(PDO::FETCH_ASSOC);

// 4. Fetch Open Tickets Count
$ticket_count = $pdo->query("SELECT COUNT(*) FROM tickets WHERE user_id=$user_id AND status='open'")->fetchColumn();

include 'includes/header.php';
?>

<style>
    /* Header */
    .dashboard-header { margin-top: 30px; margin-bottom: 20px; display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 10px; }
    .dashboard-header h1 { margin: 0; font-size: 28px; color: #2c3e50; }
    
    /* --- WALLET HERO SECTION --- */
    .wallet-hero {
        background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%); /* Deep Blue/Purple */
        border-radius: 15px;
        padding: 30px;
        color: white;
        display: flex;
        justify-content: space-between;
        align-items: center;
        box-shadow: 0 10px 20px rgba(37, 117, 252, 0.3);
        margin-bottom: 40px;
        position: relative;
        overflow: hidden;
        flex-wrap: wrap; /* Allow wrapping on mobile */
    }
    
    .wallet-balance { flex: 1; min-width: 200px; }
    .wallet-balance h3 { margin: 0; font-size: 14px; text-transform: uppercase; opacity: 0.9; letter-spacing: 1px; font-weight: 600; }
    .wallet-balance .amount { font-size: 42px; font-weight: 800; margin: 10px 0; display: block; }
    .wallet-balance .status { background: rgba(255,255,255,0.2); padding: 5px 12px; border-radius: 20px; font-size: 13px; display: inline-block; }

    .referral-cta {
        background: rgba(255, 255, 255, 0.15);
        backdrop-filter: blur(5px);
        padding: 20px;
        border-radius: 10px;
        text-align: right;
        border: 1px solid rgba(255,255,255,0.2);
        max-width: 400px;
        min-width: 280px;
        margin-top: 10px;
    }
    .referral-cta p { margin: 0 0 15px; font-size: 15px; line-height: 1.4; }
    .referral-cta strong { color: #f1c40f; font-weight: 800; }
    
    .btn-white { background: white; color: #2575fc; padding: 10px 20px; border-radius: 5px; text-decoration: none; font-weight: bold; display: inline-block; transition: transform 0.2s; box-shadow: 0 4px 6px rgba(0,0,0,0.1); }
    .btn-white:hover { transform: scale(1.05); background: #f8f9fa; }

    /* Grid Actions */
    .dash-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 20px; margin-bottom: 40px; }
    .dash-card { background: white; padding: 25px; border-radius: 12px; box-shadow: 0 5px 15px rgba(0,0,0,0.05); text-align: center; transition: transform 0.2s; border: 1px solid #eee; }
    .dash-card:hover { transform: translateY(-5px); border-color: #3498db; box-shadow: 0 10px 20px rgba(0,0,0,0.1); }
    .dash-card i { font-size: 32px; margin-bottom: 15px; display: block; }
    .dash-card h3 { margin: 5px 0; font-size: 18px; color: #333; font-weight: 700; }
    .dash-card a { text-decoration: none; color: inherit; display: block; height: 100%; }
    .dash-card p { color: #777; font-size: 14px; margin-top: 5px; }

    /* Order Styles */
    .order-card { background: #fff; border-radius: 8px; padding: 20px; margin-bottom: 20px; border: 1px solid #eee; border-left: 5px solid #ddd; box-shadow: 0 2px 5px rgba(0,0,0,0.02); }
    .order-card.completed { border-left-color: #2ecc71; }
    .order-card.processing { border-left-color: #3498db; }
    .order-card.pending { border-left-color: #f1c40f; }
    .order-card.cancelled { border-left-color: #e74c3c; }
    
    .key-display { background: #f0f9eb; padding: 15px; border: 1px dashed #2ecc71; margin-top: 15px; font-family: monospace; color: #333; border-radius: 5px; word-break: break-all; font-size: 14px; }
    
    /* Mobile Fixes */
    @media(max-width: 768px) {
        .wallet-hero { flex-direction: column; text-align: center; padding: 25px; }
        .wallet-balance { margin-bottom: 20px; text-align: center; }
        .referral-cta { text-align: center; margin-top: 0; width: 100%; max-width: 100%; }
        .dashboard-header { flex-direction: column; gap: 15px; text-align: center; }
    }
</style>

<div class="container" style="min-height: 80vh; padding-bottom: 50px;">
    
    <div class="dashboard-header">
        <div>
            <h1>Hello, <?php echo htmlspecialchars($user_name); ?> 👋</h1>
            <p style="opacity: 0.8; font-size: 16px; margin-top: 5px;">Manage your orders and subscriptions.</p>
        </div>
        <div>
            <a href="logout.php" class="btn" style="background: #ffebee; color: #c0392b; padding: 10px 25px; text-decoration: none; border-radius: 5px; font-weight:bold; border: 1px solid #ffcdd2;">Logout</a>
        </div>
    </div>

    <div class="wallet-hero">
        <div class="wallet-balance">
            <h3>My Wallet Balance</h3>
            <a href="add_funds.php">Add Funds</a>
            <span class="amount">₹<?php echo number_format($userData['wallet_balance'], 2); ?></span>
            <span class="status"><i class="fas fa-check-circle"></i> Available to Spend</span>
        </div>
        
        <div class="referral-cta">
            <p><i class="fas fa-gift"></i> Want free software? <br>Invite friends & earn <strong>₹50</strong> per signup!</p>
            <a href="referrals.php" class="btn-white"><i class="fas fa-share-alt"></i> Refer Now</a>
        </div>
    </div>

    <div class="dash-grid">
        <div class="dash-card">
            <a href="index.php">
                <i class="fas fa-shopping-bag" style="color: #e67e22;"></i>
                <h3>New Order</h3>
                <p>Browse catalog</p>
            </a>
        </div>

        <div class="dash-card">
            <a href="wishlist.php">
                <i class="fas fa-heart" style="color: #e74c3c;"></i>
                <h3>Wishlist</h3>
                <p>Saved items</p>
            </a>
        </div>

        <div class="dash-card">
            <a href="support.php">
                <i class="fas fa-headset" style="color: #3498db;"></i>
                <h3>Support</h3>
                <p style="color: #666;">
                    <?php echo $ticket_count > 0 ? "<span style='color:orange; font-weight:bold;'>$ticket_count Active</span>" : "No issues"; ?>
                </p>
            </a>
        </div>

        <div class="dash-card">
            <a href="account_settings.php">
                <i class="fas fa-user-cog" style="color: #9b59b6;"></i>
                <h3>Settings</h3>
                <p>Edit Profile</p>
            </a>
        </div>
    </div>

    <div style="margin-top: 50px; padding: 0 5px;">
        <h2 style="border-bottom: 2px solid #eee; padding-bottom: 15px; margin-bottom: 25px; color: #2c3e50; font-size: 22px;">Recent Activity</h2>

        <?php if (count($orders) > 0): ?>
            
            <?php foreach ($orders as $order): ?>
                <div class="order-card <?php echo $order['status']; ?>">
                    <div style="display: flex; justify-content: space-between; flex-wrap: wrap; align-items: center;">
                        <div>
                            <h3 style="margin: 0 0 5px 0; font-size: 18px;">Order #<?php echo $order['id']; ?></h3>
                            <small style="color: #777; font-size: 13px;">
                                <i class="far fa-clock"></i> <?php echo date('d M Y, h:i A', strtotime($order['created_at'])); ?> • 
                                <strong><?php echo ucfirst(str_replace('_', ' ', $order['payment_method'])); ?></strong>
                            </small>
                        </div>
                        <div style="text-align: right;">
                            <span style="font-weight: 800; font-size: 20px; color: #2c3e50;">
                                <?php echo convertPrice($order['total_amount']); ?>
                            </span>
                            <br>
                            <span style="font-size: 11px; font-weight: bold; text-transform: uppercase; padding: 4px 10px; border-radius: 4px; display: inline-block; margin-top: 5px; background: 
                                <?php echo ($order['status']=='completed'?'#e8f5e9':($order['status']=='pending'?'#fff3e0':'#ffebee')); ?>; 
                                color: <?php echo ($order['status']=='completed'?'#27ae60':($order['status']=='pending'?'#f39c12':'#e74c3c')); ?>">
                                <?php echo $order['status']; ?>
                            </span>
                        </div>
                    </div>

                    <div style="margin-top: 15px; border-top: 1px solid #eee; padding-top: 15px;">
                        <?php 
                        $iStmt = $pdo->prepare("
                            SELECT p.name, v.name as variant 
                            FROM order_items oi 
                            JOIN products p ON oi.product_id = p.id 
                            JOIN product_variants v ON oi.variant_id = v.id 
                            WHERE oi.order_id = ?
                        ");
                        $iStmt->execute([$order['id']]);
                        $items = $iStmt->fetchAll();
                        foreach($items as $item) {
                            echo "<div style='color:#555; font-size:14px; margin-bottom:5px; display:flex; align-items:center;'>
                                    <i class='fas fa-check-circle' style='color:#2ecc71; margin-right:8px;'></i> 
                                    <strong>" . htmlspecialchars($item['name']) . "</strong> 
                                    <span style='color:#999; margin-left:5px;'>(" . htmlspecialchars($item['variant']) . ")</span>
                                  </div>";
                        }
                        ?>
                    </div>

                    <?php if (!empty($order['user_note'])): ?>
                        <div class="key-display">
                            <strong style="color:#27ae60; display:block; margin-bottom:5px;"><i class="fas fa-key"></i> Access Details:</strong>
                            <?php echo nl2br(htmlspecialchars($order['user_note'])); ?>
                        </div>
                    <?php endif; ?>
                    
                    <div style="margin-top: 20px; text-align: right; display: flex; justify-content: flex-end; gap: 10px;">
                        
                        <?php if ($order['status'] == 'completed'): ?>
                            <a href="invoice.php?id=<?php echo $order['id']; ?>" target="_blank" style="font-size: 13px; color: #27ae60; text-decoration: none; font-weight: bold; border: 1px solid #27ae60; padding: 6px 12px; border-radius: 5px;">
                                <i class="fas fa-file-invoice"></i> Invoice
                            </a>
                        <?php else: ?>
                            <span style="font-size: 12px; color: #999; border: 1px dashed #ccc; padding: 6px 12px; border-radius: 5px; cursor: not-allowed; background: #f9f9f9;" title="Invoice available after payment verification">
                                <i class="fas fa-clock"></i> Invoice Pending
                            </span>
                        <?php endif; ?>

                        <a href="support.php?order_id=<?php echo $order['id']; ?>" style="font-size: 13px; color: #3498db; text-decoration: none; font-weight: bold; border: 1px solid #3498db; padding: 6px 12px; border-radius: 5px;">
                            <i class="fas fa-question-circle"></i> Report Issue
                        </a>
                    </div>

                </div>
            <?php endforeach; ?>

        <?php else: ?>
            <div style="text-align: center; padding: 50px 20px; background: #f9f9f9; border-radius: 12px; border: 1px dashed #ddd;">
                <i class="fas fa-shopping-basket" style="font-size: 50px; color: #ccc; margin-bottom: 15px; display: block;"></i>
                <p style="color: #777; margin-bottom: 25px; font-size: 16px;">You haven't purchased anything yet.</p>
                <a href="index.php" class="btn" style="display: inline-block; padding: 12px 35px; background: #2c3e50; color: white; text-decoration: none; border-radius: 50px; font-weight: bold; transition: transform 0.2s;">Start Shopping</a>
            </div>
        <?php endif; ?>

    </div>
</div>

<?php include 'includes/footer.php'; ?>