<?php
/**
 * Componente Premium Lock - Overlay de Bloqueio para recursos premium
 * Versao para Dashboard do Lojista
 */

function hasFeatureAccess(string $feature): bool {
    global $pdo;
    
    $storeId = $_SESSION['store_id'] ?? null;
    if (!$storeId) return false;
    
    try {
        if (!$pdo) $pdo = getDB();
        
        $stmt = $pdo->prepare("
            SELECT p.$feature 
            FROM stores s 
            JOIN plans p ON s.plan_id = p.id 
            WHERE s.id = ?
        ");
        $stmt->execute([$storeId]);
        $result = $stmt->fetchColumn();
        
        return (bool) $result;
    } catch (Exception $e) {
        return false;
    }
}

function getStorePlanInfo(): array {
    global $pdo;
    
    $storeId = $_SESSION['store_id'] ?? null;
    if (!$storeId) return null;
    
    try {
        if (!$pdo) $pdo = getDB();
        
        $stmt = $pdo->prepare("
            SELECT p.* 
            FROM stores s 
            JOIN plans p ON s.plan_id = p.id 
            WHERE s.id = ?
        ");
        $stmt->execute([$storeId]);
        return $stmt->fetch(PDO::FETCH_ASSOC);
    } catch (Exception $e) {
        return null;
    }
}

function getFeatureName(string $feature): string {
    $names = [
        'custom_domain' => 'Dominio Personalizado',
        'whatsapp_integration' => 'Integracao WhatsApp',
        'full_reports' => 'Relatorios Completos',
        'control_panel' => 'Painel de Controle Avancado',
        'dedicated_support' => 'Suporte Dedicado'
    ];
    return $names[$feature] ?? $feature;
}

function getRequiredPlanForFeature(string $feature): string {
    global $pdo;
    
    try {
        if (!$pdo) $pdo = getDB();
        
        $stmt = $pdo->prepare("
            SELECT id, name, price_monthly 
            FROM plans 
            WHERE $feature = 1 AND is_active = 1
            ORDER BY price_monthly ASC 
            LIMIT 1
        ");
        $stmt->execute();
        return $stmt->fetch(PDO::FETCH_ASSOC);
    } catch (Exception $e) {
        return ['id' => 'pro', 'name' => 'Pro'];
    }
}

function featureLockStart($feature, $title = null) {
    global $_featureLockConfig;
    
    $title = $title ?? getFeatureName($feature);
    
    $_featureLockConfig = [
        'feature' => $feature,
        'title' => $title
    ];
    
    if (!hasFeatureAccess($feature)) {
        ob_start();
    }
}

function featureLockEnd($options = []) {
    global $_featureLockConfig;
    
    $feature = $_featureLockConfig['feature'] ?? 'custom_domain';
    $title = $_featureLockConfig['title'] ?? 'Recurso Premium';
    
    if (!hasFeatureAccess($feature)) {
        $content = ob_get_clean();
        $requiredPlan = getRequiredPlanForFeature($feature);
        
        $description = $options['description'] ?? "Este recurso esta disponivel a partir do plano {$requiredPlan['name']}.";
        $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';
        if ($size === 'full') $sizeClass = 'premium-full';
        
        echo '<div class="premium-locked ' . $sizeClass . '">';
        echo '<div class="premium-content">' . $content . '</div>';
        echo '<div class="premium-overlay">';
        echo '<div class="premium-card">';
        echo '<div class="premium-card-icon"><iconify-icon icon="solar:lock-keyhole-bold"></iconify-icon></div>';
        echo '<h3 class="premium-card-title">' . htmlspecialchars($title) . '</h3>';
        echo '<p class="premium-card-description">' . htmlspecialchars($description) . '</p>';
        echo '<div class="premium-card-plan"><iconify-icon icon="solar:crown-bold"></iconify-icon> Disponivel no plano ' . htmlspecialchars($requiredPlan['name']) . '</div>';
        
        if (!empty($features)) {
            echo '<ul class="premium-card-features">';
            foreach ($features as $feat) {
                echo '<li><iconify-icon icon="solar:check-circle-bold"></iconify-icon> ' . htmlspecialchars($feat) . '</li>';
            }
            echo '</ul>';
        }
        
        echo '<a href="' . htmlspecialchars($upgradeUrl) . '" class="btn-upgrade"><iconify-icon icon="solar:rocket-bold"></iconify-icon> Fazer Upgrade</a>';
        echo '</div></div></div>';
    }
}

function pageFeatureLock($feature, $options = []) {
    if (hasFeatureAccess($feature)) {
        return false;
    }
    
    $title = $options['title'] ?? getFeatureName($feature);
    $requiredPlan = getRequiredPlanForFeature($feature);
    $description = $options['description'] ?? "Este recurso esta disponivel a partir do plano {$requiredPlan['name']}.";
    $features = $options['features'] ?? [];
    $upgradeUrl = $options['upgrade_url'] ?? '/pages/upgrade.php';
    $icon = $options['icon'] ?? 'solar:lock-keyhole-bold';
    
    echo '<div class="premium-page-lock">';
    echo '<div class="premium-page-card">';
    echo '<div class="premium-card-icon"><iconify-icon icon="' . htmlspecialchars($icon) . '"></iconify-icon></div>';
    echo '<h2 class="premium-card-title">' . htmlspecialchars($title) . '</h2>';
    echo '<p class="premium-card-description">' . htmlspecialchars($description) . '</p>';
    echo '<div class="premium-card-plan"><iconify-icon icon="solar:crown-bold"></iconify-icon> Disponivel no plano ' . htmlspecialchars($requiredPlan['name']) . '</div>';
    
    if (!empty($features)) {
        echo '<ul class="premium-card-features">';
        foreach ($features as $feat) {
            echo '<li><iconify-icon icon="solar:check-circle-bold"></iconify-icon> ' . htmlspecialchars($feat) . '</li>';
        }
        echo '</ul>';
    }
    
    echo '<a href="' . htmlspecialchars($upgradeUrl) . '" class="btn-upgrade"><iconify-icon icon="solar:rocket-bold"></iconify-icon> Fazer Upgrade</a>';
    echo '</div></div>';
    
    return true;
}

function shouldLockFeature(string $feature): bool {
    return !hasFeatureAccess($feature);
}
