<?php
/**
 * Componente Premium Lock - Overlay de Bloqueio para recursos premium
 * 
 * Uso:
 * <?php premiumLockStart('pro', 'Relatórios Avançados'); ?>
 *     <!-- Conteúdo que será bloqueado -->
 * <?php premiumLockEnd(); ?>
 * 
 * Ou com mais opções:
 * <?php premiumLock([
 *     'required_plan' => 'pro',
 *     'title' => 'Relatórios Avançados',
 *     'description' => 'Acesse análises detalhadas...',
 *     'features' => ['Feature 1', 'Feature 2'],
 *     'upgrade_url' => '/pages/upgrade.php',
 *     'size' => 'normal' // ou 'sm', 'inline'
 * ]); ?>
 */

/**
 * Verifica se o usuário tem acesso ao plano requerido
 */
function hasAccess($requiredPlan) {
    // Hierarquia de planos (do menor para o maior)
    $planHierarchy = [
        'free' => 0,
        'starter' => 1,
        'pro' => 2,
        'enterprise' => 3
    ];
    
    // Pegar plano atual do usuário/loja
    $currentPlan = getCurrentUserPlan();
    
    $currentLevel = $planHierarchy[$currentPlan] ?? 0;
    $requiredLevel = $planHierarchy[$requiredPlan] ?? 0;
    
    return $currentLevel >= $requiredLevel;
}

/**
 * Retorna o plano atual do usuário/loja
 */
function getCurrentUserPlan() {
    // Se for superadmin, tem acesso total
    if (function_exists('isSuperAdmin') && isSuperAdmin()) {
        return 'enterprise';
    }
    
    // Pegar da sessão ou do banco
    if (isset($_SESSION['store']['plan_id'])) {
        return $_SESSION['store']['plan_id'];
    }
    
    // Tentar pegar do banco se tiver store_id
    if (isset($_SESSION['store']['id'])) {
        try {
            $pdo = getDB();
            $stmt = $pdo->prepare("SELECT plan_id FROM stores WHERE id = ?");
            $stmt->execute([$_SESSION['store']['id']]);
            $plan = $stmt->fetchColumn();
            return $plan ?: 'free';
        } catch (Exception $e) {
            return 'free';
        }
    }
    
    return 'free';
}

/**
 * Retorna informações do plano
 */
function getPlanInfo($planId) {
    $plans = [
        'free' => [
            'name' => 'Gratuito',
            'color' => '#888'
        ],
        'starter' => [
            'name' => 'Starter',
            'color' => '#22C55E'
        ],
        'pro' => [
            'name' => 'Pro',
            'color' => '#D4AF37'
        ],
        'enterprise' => [
            'name' => 'Enterprise',
            'color' => '#8B5CF6'
        ]
    ];
    
    return $plans[$planId] ?? $plans['free'];
}

/**
 * Inicia bloco de conteúdo premium (para usar com ob_start)
 */
function premiumLockStart($requiredPlan, $title = 'Recurso Premium') {
    global $_premiumLockConfig;
    $_premiumLockConfig = [
        'required_plan' => $requiredPlan,
        'title' => $title
    ];
    
    if (!hasAccess($requiredPlan)) {
        ob_start();
    }
}

/**
 * Finaliza bloco de conteúdo premium
 */
function premiumLockEnd($options = []) {
    global $_premiumLockConfig;
    
    $requiredPlan = $_premiumLockConfig['required_plan'] ?? 'pro';
    $title = $_premiumLockConfig['title'] ?? 'Recurso Premium';
    
    if (!hasAccess($requiredPlan)) {
        $content = ob_get_clean();
        $planInfo = getPlanInfo($requiredPlan);
        
        $description = $options['description'] ?? "Este recurso está disponível no plano {$planInfo['name']} ou superior.";
        $features = $options['features'] ?? [];
        $upgradeUrl = $options['upgrade_url'] ?? '/pages/upgrade.php';
        $size = $options['size'] ?? 'normal';
        
        $sizeClass = '';
        if ($size === 'sm') $sizeClass = 'premium-sm';
        if ($size === 'inline') $sizeClass = 'premium-inline';
        
        ?>
        <div class="premium-locked <?= $sizeClass ?>">
            <div class="premium-content">
                <?= $content ?>
            </div>
            <div class="premium-overlay">
                <div class="premium-card">
                    <div class="premium-card-icon">
                        <iconify-icon icon="solar:lock-keyhole-bold"></iconify-icon>
                    </div>
                    <h3 class="premium-card-title"><?= htmlspecialchars($title) ?></h3>
                    <p class="premium-card-description"><?= htmlspecialchars($description) ?></p>
                    
                    <div class="premium-card-plan">
                        <iconify-icon icon="solar:crown-bold"></iconify-icon>
                        Requer plano <?= htmlspecialchars($planInfo['name']) ?>
                    </div>
                    
                    <?php if (!empty($features)): ?>
                    <ul class="premium-card-features">
                        <?php foreach ($features as $feature): ?>
                        <li>
                            <iconify-icon icon="solar:check-circle-bold"></iconify-icon>
                            <?= htmlspecialchars($feature) ?>
                        </li>
                        <?php endforeach; ?>
                    </ul>
                    <?php endif; ?>
                    
                    <a href="<?= htmlspecialchars($upgradeUrl) ?>" class="btn-upgrade">
                        <iconify-icon icon="solar:rocket-bold"></iconify-icon>
                        Fazer Upgrade
                    </a>
                </div>
            </div>
        </div>
        <?php
    }
}

/**
 * Renderiza um bloco premium lock completo (versão simplificada)
 */
function premiumLock($options) {
    $requiredPlan = $options['required_plan'] ?? 'pro';
    $title = $options['title'] ?? 'Recurso Premium';
    $description = $options['description'] ?? null;
    $features = $options['features'] ?? [];
    $upgradeUrl = $options['upgrade_url'] ?? '/pages/upgrade.php';
    $size = $options['size'] ?? 'normal';
    $content = $options['content'] ?? '';
    
    if (hasAccess($requiredPlan)) {
        echo $content;
        return;
    }
    
    $planInfo = getPlanInfo($requiredPlan);
    if (!$description) {
        $description = "Este recurso está disponível no plano {$planInfo['name']} ou superior.";
    }
    
    $sizeClass = '';
    if ($size === 'sm') $sizeClass = 'premium-sm';
    if ($size === 'inline') $sizeClass = 'premium-inline';
    
    ?>
    <div class="premium-locked <?= $sizeClass ?>">
        <div class="premium-content">
            <?= $content ?>
        </div>
        <div class="premium-overlay">
            <div class="premium-card">
                <div class="premium-card-icon">
                    <iconify-icon icon="solar:lock-keyhole-bold"></iconify-icon>
                </div>
                <h3 class="premium-card-title"><?= htmlspecialchars($title) ?></h3>
                <p class="premium-card-description"><?= htmlspecialchars($description) ?></p>
                
                <div class="premium-card-plan">
                    <iconify-icon icon="solar:crown-bold"></iconify-icon>
                    Requer plano <?= htmlspecialchars($planInfo['name']) ?>
                </div>
                
                <?php if (!empty($features)): ?>
                <ul class="premium-card-features">
                    <?php foreach ($features as $feature): ?>
                    <li>
                        <iconify-icon icon="solar:check-circle-bold"></iconify-icon>
                        <?= htmlspecialchars($feature) ?>
                    </li>
                    <?php endforeach; ?>
                </ul>
                <?php endif; ?>
                
                <a href="<?= htmlspecialchars($upgradeUrl) ?>" class="btn-upgrade">
                    <iconify-icon icon="solar:rocket-bold"></iconify-icon>
                    Fazer Upgrade
                </a>
            </div>
        </div>
    </div>
    <?php
}

/**
 * Verifica se deve mostrar o lock (helper para condicionais)
 */
function shouldLock($requiredPlan) {
    return !hasAccess($requiredPlan);
}
