<?php
// addons/seller_level/main.php
require_once __DIR__ . '/../../config/db.php';

/**
 * Muestra la barra de progreso en el perfil
 */
if (!function_exists('get_seller_xp_bar')) {
    function get_seller_xp_bar($user_id, $pdo) {
        $stmt = $pdo->prepare("SELECT seller_xp, seller_level FROM users WHERE id = ?");
        $stmt->execute([$user_id]);
        $user = $stmt->fetch();

        if (!$user) return '';

        $current_xp = (int)$user['seller_xp'];
        $level = (int)$user['seller_level'];
        
        // Cada nivel pide 100 XP más (Lvl 1: 100, Lvl 2: 200, etc.)
        $xp_needed = $level * 100; 
        $percentage = min(($current_xp / $xp_needed) * 100, 100);

        return '
        <div style="margin-top: 15px; text-align: left; padding: 0 10px;">
            <div style="display: flex; justify-content: space-between; font-size: 11px; margin-bottom: 5px; color: var(--text-gray);">
                <span style="font-weight: bold; color: var(--primary);">LEVEL ' . $level . ' SELLER</span>
                <span>' . $current_xp . ' / ' . $xp_needed . ' XP</span>
            </div>
            <div style="width: 100%; height: 6px; background: rgba(255,255,255,0.05); border-radius: 10px; border: 1px solid var(--border); overflow: hidden;">
                <div style="width: ' . $percentage . '%; height: 100%; background: var(--primary); box-shadow: 0 0 8px var(--primary); transition: width 0.6s ease;"></div>
            </div>
        </div>';
    }
}

/**
 * Suma XP con protección contra spam de ventas baratas
 */
if (!function_exists('add_seller_xp')) {
    function add_seller_xp($user_id, $total_price, $pdo) {
        $stmt = $pdo->prepare("SELECT seller_xp, seller_level FROM users WHERE id = ?");
        $stmt->execute([$user_id]);
        $user = $stmt->fetch();
        
        if (!$user) return;

        // --- BALANCEO DE XP ---
        // Base: 10 XP por el hecho de vender.
        // Extra: 1 XP por cada $2 USD de la venta.
        // CAP: Máximo 200 XP por cada transacción única.
        $calculated_xp = 10 + (floor($total_price / 2));
        $xp_gain = min($calculated_xp, 200); 

        $new_xp = (int)$user['seller_xp'] + $xp_gain;
        $level = (int)$user['seller_level'];
        $xp_needed = $level * 100;

        // Subida de nivel múltiple (por si gana mucha XP de golpe)
        while ($new_xp >= $xp_needed) {
            $new_xp -= $xp_needed;
            $level++;
            $xp_needed = $level * 100;
        }

        $upd = $pdo->prepare("UPDATE users SET seller_xp = ?, seller_level = ? WHERE id = ?");
        $upd->execute([$new_xp, $level, $user_id]);
    }
}