<?php
// dashboard.php
require 'config/db.php';


// 1. Verificación de Sesión
if (!isset($_SESSION['user_id'])) { 
    header("Location: login.php"); 
    exit; 
}

$current_user_id = $_SESSION['user_id'];
$username = $_SESSION['username']; 

try {
    // 1. Datos del Usuario (Incluimos balance, XP, verificación y ROL)
    $stmt = $pdo->prepare("SELECT balance, created_at, is_verified, seller_xp, role FROM users WHERE id = ? LIMIT 1");
    $stmt->execute([$current_user_id]);
    $user_data = $stmt->fetch();

    if (!$user_data) {
        session_destroy();
        header("Location: login.php");
        exit;
    }

    // 2. Lógica de Rating & Reviews
    $stmt_avg = $pdo->prepare("SELECT AVG(rating) as average, COUNT(*) as total FROM reviews WHERE seller_id = ?");
    $stmt_avg->execute([$current_user_id]);
    $rating_stats = $stmt_avg->fetch();
    $rating_average = round($rating_stats['average'] ?? 0, 1);

    // 3. Estadísticas de Actividad
    $unread_msgs = $pdo->prepare("SELECT COUNT(*) FROM messages WHERE receiver_id = ? AND is_read = 0");
    $unread_msgs->execute([$current_user_id]);
    $unread_count = $unread_msgs->fetchColumn();

    $active_listings = $pdo->prepare("SELECT COUNT(*) FROM products WHERE seller_id = ? AND status = 'available'");
    $active_listings->execute([$current_user_id]);
    $my_listings = $active_listings->fetchColumn();

    $total_purchases = $pdo->prepare("SELECT COUNT(*) FROM orders WHERE buyer_id = ?");
    $total_purchases->execute([$current_user_id]);
    $my_purchases = $total_purchases->fetchColumn();

    $completed_sales = $pdo->prepare("SELECT COUNT(*) FROM orders WHERE seller_id = ? AND status = 'completed'");
    $completed_sales->execute([$current_user_id]);
    $my_sales_count = $completed_sales->fetchColumn();

    // 4. Mensajes Recientes
    $stmt_msg = $pdo->prepare("
        SELECT m.*, u.username as sender_name 
        FROM messages m 
        JOIN users u ON m.sender_id = u.id 
        WHERE m.receiver_id = ? 
        ORDER BY m.created_at DESC LIMIT 1
    ");
    $stmt_msg->execute([$current_user_id]);
    $last_chat = $stmt_msg->fetch();

} catch (PDOException $e) {
    die("Database Error: " . $e->getMessage());
}

$page_title = "Dashboard";
include 'includes/header.php'; 
?>

<style>
    :root {
        --v-bg: #0d1117;
        --v-card: #161b22;
        --v-accent: #00ff88;
        --v-border: #30363d;
        --v-text-gray: #8b949e;
    }

    .v-container { max-width: 1400px; margin: 30px auto; padding: 0 20px; display: grid; grid-template-columns: 320px 1fr; gap: 30px; }
    .v-sidebar { display: flex; flex-direction: column; gap: 20px; }
    
    .profile-sidebar { background: var(--v-card); padding: 40px 20px; border-radius: 15px; border: 1px solid var(--v-border); text-align: center; }
    .avatar { width: 100px; height: 100px; background: var(--v-accent); border-radius: 50%; display: flex; align-items: center; justify-content: center; margin: 0 auto 15px; font-size: 40px; color: black; font-weight: 900; border: 5px solid rgba(255,255,255,0.05); }
    
    .level-bar-container { margin: 20px 0; text-align: left; }
    .level-info { display: flex; justify-content: space-between; font-size: 10px; font-weight: 800; text-transform: uppercase; margin-bottom: 8px; }
    .level-progress { height: 6px; background: #0d1117; border-radius: 10px; overflow: hidden; border: 1px solid var(--v-border); }
    .level-fill { height: 100%; background: var(--v-accent); width: <?php echo ($user_data['seller_xp'] % 100); ?>%; box-shadow: 0 0 10px var(--v-accent); }

    .v-nav-group { background: var(--v-card); border: 1px solid var(--v-border); border-radius: 15px; padding: 15px; }
    .nav-item { padding: 12px 15px; border-radius: 8px; text-decoration: none; color: var(--v-text-gray); display: flex; align-items: center; gap: 12px; font-size: 13px; transition: 0.2s; margin-bottom: 5px; }
    .nav-item:hover { background: rgba(255,255,255,0.05); color: white; }
    .nav-item.active { background: var(--v-accent); color: black; font-weight: bold; }
    .nav-label { font-size: 10px; color: #444; font-weight: 800; text-transform: uppercase; padding: 0 15px 10px; display: block; }

    .v-main-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 25px; align-content: start; }
    .v-card { background: var(--v-card); border: 1px solid var(--v-border); border-radius: 15px; padding: 25px; }
    
    .stat-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 15px; }
    .stat-pill { background: rgba(0,0,0,0.2); padding: 20px 10px; border-radius: 12px; border: 1px solid var(--v-border); text-align: center; text-decoration: none; transition: 0.3s; display: block; }
    .stat-pill:hover { border-color: var(--v-accent); background: rgba(0, 255, 136, 0.05); }
    .stat-pill span { display: block; font-size: 10px; color: var(--v-text-gray); text-transform: uppercase; margin-bottom: 8px; }
    .stat-pill strong { font-size: 20px; color: white; }

    .v-input { width: 100%; background: #0d1117; border: 1px solid var(--v-border); color: white; padding: 12px; border-radius: 8px; margin-top: 10px; outline: none; }
    .v-btn-primary { width: 100%; background: #21262d; color: white; border: 1px solid var(--v-border); padding: 12px; border-radius: 8px; cursor: pointer; font-weight: bold; display: flex; align-items: center; justify-content: center; gap: 10px; transition: 0.3s; }
    .v-btn-primary:hover { background: white; color: black; }
</style>

<div class="v-container">
    <aside class="v-sidebar">
        <div class="profile-sidebar">
            <div class="avatar"><?php echo strtoupper(substr($username, 0, 1)); ?></div>
            <h2 style="margin:0; font-size: 20px;"><?php echo htmlspecialchars($username); ?> 
                <?php if($user_data['role'] === 'admin'): ?><span style="color: #ffcc00;">👑</span><?php endif; ?>
                <?php if($user_data['is_verified']): ?><span style="color: var(--v-accent);">✔️</span><?php endif; ?>
            </h2>
            <p style="font-size: 11px; color: var(--v-text-gray); margin-top: 5px;">Member since <?php echo date('M Y', strtotime($user_data['created_at'])); ?></p>

            <div class="level-bar-container">
                <div class="level-info">
                    <span style="color: var(--v-accent);">Level 1 Seller</span>
                    <span><?php echo ($user_data['seller_xp'] % 100); ?> / 100 XP</span>
                </div>
                <div class="level-progress"><div class="level-fill"></div></div>
            </div>
            
            <div style="font-size: 14px;">
                <?php for($i=1; $i<=5; $i++) echo ($i <= $rating_average) ? "<span style='color:#ffcc00;'>★</span>" : "☆"; ?>
                <div style="font-size: 11px; margin-top: 5px; color: var(--v-text-gray);">(<?php echo $rating_stats['total']; ?> reviews)</div>
            </div>
        </div>

        <div class="v-nav-group">
            <span class="nav-label">Main Menu</span>
            <a href="dashboard.php" class="nav-item active"><i class="fa-solid fa-gauge"></i> Overview</a>
            <a href="messages.php" class="nav-item"><i class="fa-solid fa-envelope"></i> Inbox (<?php echo $unread_count; ?>)</a>
            <a href="my_orders.php" class="nav-item"><i class="fa-solid fa-cart-shopping"></i> My Purchases</a>
            
            <?php if($user_data['role'] === 'seller' || $user_data['role'] === 'admin'): ?>
                <a href="my_inventory.php" class="nav-item"><i class="fa-solid fa-boxes-stacked"></i> My Inventory</a>
                <a href="my_sales.php" class="nav-item"><i class="fa-solid fa-sack-dollar"></i> My Sales</a>
                <a href="publish.php" class="nav-item" style="color: var(--v-accent); font-weight: 800;">
                    <i class="fa-solid fa-circle-plus"></i> PUBLISH ITEM
                </a>
            <?php endif; ?>

            <hr style="border: 0; border-top: 1px solid var(--v-border); margin: 15px 0;">
            <a href="logout.php" class="nav-item" style="color: #ff4d4d;"><i class="fa-solid fa-power-off"></i> LOGOUT</a>
        </div>
    </aside>

    <main class="v-main-grid">
        
        <?php if($user_data['is_verified'] == 0): ?>
        <div class="v-card" style="grid-column: span 2; border-color: #ffcc00; background: rgba(255, 204, 0, 0.02);">
            <div style="display: flex; justify-content: space-between; align-items: center;">
                <div>
                    <strong style="color: #ffcc00;"><i class="fa-solid fa-envelope"></i> Verify your Email</strong>
                    <p style="font-size: 12px; color: var(--v-text-gray); margin: 5px 0;">Enter the 6-digit code to activate your vault.</p>
                    <form action="verify_process.php" method="POST" style="display: flex; gap: 10px; margin-top: 10px;">
                        <input type="text" name="code" placeholder="000000" class="v-input" style="width: 120px; margin: 0; text-align: center; border-color: #ffcc00;">
                        <button type="submit" style="background: #ffcc00; color: black; border: none; padding: 0 20px; border-radius: 8px; font-weight: bold; cursor: pointer;">Verify Now</button>
                    </form>
                </div>
                <a href="verify_process.php?resend=1" style="color: #ffcc00; font-size: 11px; text-decoration: underline;">Resend Code</a>
            </div>
        </div>
        <?php endif; ?>

        <div class="v-card" style="grid-column: span 2;">
            <h4 style="margin: 0 0 20px; font-size: 11px; color: var(--v-text-gray); text-transform: uppercase; letter-spacing: 1px;">Vault Status</h4>
            <div class="stat-grid">
                <a href="wallet.php" class="stat-pill" style="border-color: var(--v-accent);">
                    <span>Your Balance</span>
                    <strong style="color: var(--v-accent);">$<?php echo number_format($user_data['balance'], 2); ?></strong>
                </a>
                <a href="my_inventory.php" class="stat-pill">
                    <span>Active Items</span>
                    <strong><?php echo $my_listings; ?></strong>
                </a>
                <div class="stat-pill">
                    <span>Purchases</span>
                    <strong><?php echo $my_purchases; ?></strong>
                </div>
                <div class="stat-pill">
                    <span>Sold</span>
                    <strong><?php echo $my_sales_count; ?></strong>
                </div>
            </div>
        </div>

        <div class="v-card">
            <h4 style="margin: 0 0 20px; font-size: 11px; color: var(--v-text-gray); text-transform: uppercase;">Recent Chat</h4>
            <?php if($last_chat): ?>
            <div style="display: flex; align-items: center; gap: 15px; background: rgba(0,0,0,0.2); padding: 15px; border-radius: 12px; border: 1px solid var(--v-border);">
                <div style="width: 45px; height: 45px; background: #333; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-weight: bold; color: var(--v-accent);">
                    <?php echo strtoupper(substr($last_chat['sender_name'], 0, 1)); ?>
                </div>
                <div style="flex: 1;">
                    <div style="font-size: 13px; font-weight: bold; color: white;">@<?php echo htmlspecialchars($last_chat['sender_name']); ?></div>
                    <div style="font-size: 11px; color: #666; margin-top: 3px;"><?= htmlspecialchars(substr($last_chat['message'], 0, 35)) ?>...</div>
                </div>
                <a href="messages.php" style="color: var(--v-accent);"><i class="fa-solid fa-chevron-right"></i></a>
            </div>
            <?php else: ?>
                <p style="font-size: 12px; color: #444; text-align: center; padding: 10px;">No messages yet.</p>
            <?php endif; ?>
        </div>

        <div class="v-card">
            <h4 style="margin: 0 0 20px; font-size: 11px; color: var(--v-text-gray); text-transform: uppercase;">Account Security</h4>
            <form action="update_profile.php" method="POST">
                <label style="font-size: 10px; color: #555; text-transform: uppercase; font-weight: 800;">Change Password</label>
                <input type="password" name="new_password" class="v-input" placeholder="New password">
                <button type="submit" class="v-btn-primary" style="margin-top: 15px;">
                    <i class="fa-solid fa-key"></i> Update Password
                </button>
            </form>
            <div style="margin-top: 20px; font-size: 11px; color: #555; display: flex; align-items: center; gap: 8px;">
                <i class="fa-solid fa-shield-halved" style="color: <?php echo $user_data['is_verified'] ? 'var(--v-accent)' : '#ffcc00'; ?>;"></i> 
                Verification status: <strong style="color: white;"><?php echo $user_data['is_verified'] ? 'VERIFIED' : 'PENDING'; ?></strong>
            </div>
        </div>

    </main>
</div>

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