<?php
/**
 * Página Minha Loja - MontaLoja SaaS
 * Versão Refatorada (MVC) com Assets Separados
 */
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/check-access.php';
require_once __DIR__ . '/../includes/premium-lock.php';
require_once __DIR__ . '/../includes/services/StoreSettingsService.php';

$pdo = getDB();
$userId = $_SESSION['user_id'] ?? null;
$storeId = $_SESSION['store_id'] ?? null;

if (!$userId || !$storeId) {
    header('Location: /pages/login.php');
    exit;
}

// Inicializar Serviço
$service = new StoreSettingsService($pdo, $storeId);
$csrfToken = $service->generateCsrfToken();

// Processar Ações (Controller Logic)
$message = '';
$messageType = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $action = $_POST['action'] ?? '';
        $result = $service->handleRequest($action, $_POST, $_FILES);
        
        $message = $result['message'];
        $messageType = $result['success'] ? 'success' : 'error';
    } catch (Exception $e) {
        $message = $e->getMessage();
        $messageType = 'error';
    }
}

// Carregar Dados da View
$storeStmt = $pdo->prepare("SELECT * FROM stores WHERE id = ?");
$storeStmt->execute([$storeId]);
$store = $storeStmt->fetch(PDO::FETCH_ASSOC);

$templateSettings = !empty($store['template_settings']) ? json_decode($store['template_settings'], true) : [];
$headerSettings = $templateSettings['header'] ?? [
    'logo_type' => 'text',
    'logo_text' => $store['name'] ?? 'Minha Loja',
    'logo_image' => ''
];

$socialLinks = $templateSettings['social_links'] ?? [];
$seoSettings = $templateSettings['seo'] ?? [];
$slug = $store['slug'] ?? 'minhaloja';
$domainType = $store['domain_type'] ?? 'subdomain';
$customDomain = $store['custom_domain'] ?? '';

// Helpers de URL de Loja
if (function_exists('get_store_url')) {
    $storeUrl = get_store_url($store);
} else {
    // Fallback caso a função não esteja no config (embora deva estar)
    $systemDomain = getenv('SYSTEM_DOMAIN') ?: 'duolead.com.br';
    $urlPath = 'https://' . $systemDomain . '/loja/' . $slug;
    $urlSubdomain = 'https://' . $slug . '.' . $systemDomain;
    
    $urlCustom = $customDomain ? 'https://' . $customDomain : '';
    $storeUrl = ($domainType === 'custom' && $customDomain) ? $urlCustom : 
                (($domainType === 'subdomain') ? $urlSubdomain : $urlPath);
}

// URLs para exibição - Detectar domínio automaticamente
$currentHost = $_SERVER['HTTP_HOST'] ?? getenv('SYSTEM_DOMAIN') ?: 'duolead.com.br';
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? "https://" : "http://";

$urlPath = $protocol . $currentHost . '/loja/' . $slug;
$urlSubdomain = $protocol . $slug . '.' . $currentHost;

$activeTab = $_GET['tab'] ?? 'appearance';

$pageTitle = 'Minha Loja';
// Custom CSS injection for dashboard-header
$customCss = ['/assets/css/pages/store-settings.css?v=' . time()];

include __DIR__ . '/../includes/dashboard-header.php';
?>

<main class="main-content">
    <div class="page-header page-header-flex">
        <div>
            <h1><iconify-icon icon="solar:shop-2-bold"></iconify-icon> Minha Loja</h1>
            <p>Personalize a aparência e configurações da sua loja online</p>
        </div>
        <a href="<?php echo htmlspecialchars($storeUrl); ?>" target="_blank" class="btn btn-primary">
            <iconify-icon icon="solar:eye-bold"></iconify-icon>
            <span>Ver Loja</span>
        </a>
    </div>

    <?php if ($message): ?>
    <div class="alert alert-<?php echo $messageType; ?>">
        <iconify-icon icon="<?php echo $messageType === 'success' ? 'solar:check-circle-bold' : 'solar:danger-circle-bold'; ?>"></iconify-icon>
        <?php echo htmlspecialchars($message); ?>
    </div>
    <?php endif; ?>

    <!-- Preview da Loja -->
    <!-- Preview da Loja - Redesign Premium -->
    <div class="card store-preview-card">
        <div class="store-preview-banner"></div>
        <div class="store-preview-body">
            <div class="store-preview-logo-wrapper" style="background: var(--primary);">
                <?php 
                $favicon = $headerSettings['favicon'] ?? '';
                $logoImage = $headerSettings['logo_image'] ?? '';
                $logoType = $headerSettings['logo_type'] ?? 'text';
                
                // Logic: Show Favicon -> Logo Image -> Initials
                // We use favicon if available, otherwise check logo rules
                $showFavicon = !empty($favicon);
                $showLogo = !$showFavicon && ($logoType === 'image' || $logoType === 'both') && !empty($logoImage);
                ?>
                
                <?php if ($showFavicon): ?>
                <img src="<?php echo htmlspecialchars($favicon); ?>" alt="Favicon">
                <?php elseif ($showLogo): ?>
                <img src="<?php echo htmlspecialchars($logoImage); ?>" alt="Logo">
                <?php else: ?>
                <span><?php echo strtoupper(substr($store['name'] ?? 'L', 0, 1)); ?></span>
                <?php endif; ?>
            </div>
            
            <div class="store-preview-info">
                <h2 class="store-preview-name"><?php echo htmlspecialchars($store['name'] ?? 'Minha Loja'); ?></h2>
                <?php if ($logoType === 'both'): ?>
                <p class="store-preview-subtitle"><?php echo htmlspecialchars($headerSettings['logo_text'] ?? ''); ?></p>
                <?php endif; ?>
                
                <div class="store-preview-url-box">
                    <a href="<?php echo htmlspecialchars($storeUrl); ?>" target="_blank" class="store-url-link">
                        <iconify-icon icon="solar:link-bold"></iconify-icon>
                        <?php echo htmlspecialchars($storeUrl); ?>
                    </a>
                    <button type="button" class="store-copy-btn" onclick="copyToClipboard('<?php echo $storeUrl; ?>', event)" title="Copiar Link">
                        <iconify-icon icon="solar:copy-bold"></iconify-icon>
                    </button>
                </div>
                
                <div class="store-preview-badges">
                    <span class="badge-status active">
                        <iconify-icon icon="solar:check-circle-bold"></iconify-icon> Loja Online
                    </span>
                    <span class="badge-plan">
                        <iconify-icon icon="solar:star-bold"></iconify-icon> Plano Premium
                    </span>
                </div>
            </div>
        </div>
    </div>

    <!-- Tabs -->
    <nav class="tab-nav">
        <!-- HREF com onclick para garantir compatibilidade se JS falhar ou SEO -->
        <a href="javascript:void(0)" onclick="switchTab('appearance')" data-tab="appearance" class="tab-btn <?php echo $activeTab === 'appearance' ? 'active' : ''; ?>">
            <iconify-icon icon="solar:palette-bold"></iconify-icon>
            Aparência
        </a>
        <a href="javascript:void(0)" onclick="switchTab('domain')" data-tab="domain" class="tab-btn <?php echo $activeTab === 'domain' ? 'active' : ''; ?>">
            <iconify-icon icon="solar:global-bold"></iconify-icon>
            Domínio
        </a>
        <a href="javascript:void(0)" onclick="switchTab('social')" data-tab="social" class="tab-btn <?php echo $activeTab === 'social' ? 'active' : ''; ?>">
            <iconify-icon icon="solar:share-bold"></iconify-icon>
            Redes Sociais
        </a>
        <a href="javascript:void(0)" onclick="switchTab('seo')" data-tab="seo" class="tab-btn <?php echo $activeTab === 'seo' ? 'active' : ''; ?>">
            <iconify-icon icon="solar:magnifer-bold"></iconify-icon>
            SEO
        </a>
    </nav>

    <!-- Aparência -->
    <div class="card tab-content <?php echo $activeTab === 'appearance' ? 'active' : ''; ?>" id="tab-appearance">
        <h2 style="font-size: 1.1rem; margin-bottom: 1.5rem;">
            <iconify-icon icon="solar:palette-bold"></iconify-icon>
            Aparência da Loja
        </h2>
        <form method="POST" enctype="multipart/form-data">
            <input type="hidden" name="action" value="update_appearance">
            <input type="hidden" name="csrf_token" value="<?php echo $csrfToken; ?>">
            <input type="hidden" name="remove_logo" id="removeLogoInput" value="0">
            <input type="hidden" name="remove_favicon" id="removeFaviconInput" value="0">

            <!-- Logo da Loja -->
            <div class="form-group">
                <label class="form-label">
                    <iconify-icon icon="solar:gallery-bold" style="margin-right: 0.5rem;"></iconify-icon>
                    Logo da Loja
                </label>

                <!-- Tipo de Logo -->
                <div class="form-group" style="margin-top: 0.75rem;">
                    <label class="form-label" style="font-size: 0.8rem;">Tipo de Logo</label>
                    <div class="logo-type-options">
                        <label class="logo-type-option <?php echo ($headerSettings['logo_type'] ?? 'text') === 'text' ? 'active' : ''; ?>">
                            <input type="radio" name="logo_type" value="text" <?php echo ($headerSettings['logo_type'] ?? 'text') === 'text' ? 'checked' : ''; ?> onchange="updateLogoType('text')">
                            <iconify-icon icon="solar:text-bold"></iconify-icon>
                            <span>Só Texto</span>
                        </label>
                        <label class="logo-type-option <?php echo ($headerSettings['logo_type'] ?? 'text') === 'image' ? 'active' : ''; ?>">
                            <input type="radio" name="logo_type" value="image" <?php echo ($headerSettings['logo_type'] ?? 'text') === 'image' ? 'checked' : ''; ?> onchange="updateLogoType('image')">
                            <iconify-icon icon="solar:gallery-minimalistic-bold"></iconify-icon>
                            <span>Só Imagem</span>
                        </label>
                        <label class="logo-type-option <?php echo ($headerSettings['logo_type'] ?? 'text') === 'both' ? 'active' : ''; ?>">
                            <input type="radio" name="logo_type" value="both" <?php echo ($headerSettings['logo_type'] ?? 'text') === 'both' ? 'checked' : ''; ?> onchange="updateLogoType('both')">
                            <iconify-icon icon="solar:widget-2-bold"></iconify-icon>
                            <span>Imagem + Texto</span>
                        </label>
                    </div>
                </div>

                <!-- Nome/Texto do Logo -->
                <div class="form-group" id="logoTextGroup" style="<?php echo ($headerSettings['logo_type'] ?? 'text') === 'image' ? 'display:none;' : ''; ?>">
                    <label class="form-label" style="font-size: 0.8rem;">Nome da Loja</label>
                    <input type="text" name="logo_text" class="form-input"
                           value="<?php echo htmlspecialchars($headerSettings['logo_text'] ?? $store['name'] ?? ''); ?>"
                           placeholder="Nome da sua loja">
                </div>

                <!-- Upload de Logo -->
                <div class="form-group" id="logoImageGroup" style="<?php echo ($headerSettings['logo_type'] ?? 'text') === 'text' ? 'display:none;' : ''; ?>">
                    <label class="form-label" style="font-size: 0.8rem;">Imagem do Logo</label>
                    <div class="logo-preview-box" id="logoPreviewBox" onclick="document.getElementById('logoInput').click()">
                        <?php if (!empty($headerSettings['logo_image'])): ?>
                        <img src="<?php echo htmlspecialchars($headerSettings['logo_image']); ?>" alt="Logo" id="logoPreviewImg">
                        <button type="button" class="logo-remove-btn" onclick="event.stopPropagation(); removeLogo()">
                            <iconify-icon icon="solar:trash-bin-trash-bold"></iconify-icon>
                        </button>
                        <?php else: ?>
                        <div class="logo-placeholder" id="logoPlaceholder">
                            <iconify-icon icon="solar:gallery-add-bold"></iconify-icon>
                            <span>Clique para enviar uma imagem</span>
                        </div>
                        <?php endif; ?>
                    </div>
                    <input type="file" name="logo_file" id="logoInput" accept="image/*" onchange="previewLogo(this)" style="display: none;">
                    <div class="logo-upload-info">
                        <p class="logo-upload-hint">PNG, JPG, SVG ou WebP. Máx 2MB. Clique na área acima para enviar.</p>
                    </div>
                </div>
            </div>

            <!-- Favicon -->
            <div class="form-group" style="margin-top: 1.5rem; padding-top: 1.5rem; border-top: 1px solid var(--border-color);">
                <label class="form-label">
                    <iconify-icon icon="solar:bookmark-square-bold" style="margin-right: 0.5rem;"></iconify-icon>
                    Favicon
                </label>
                <p style="font-size: 0.8rem; color: var(--text-muted); margin-bottom: 0.75rem;">
                    Ícone que aparece na aba do navegador
                </p>
                
                <div class="favicon-upload-area">
                    <div class="favicon-preview-box" id="faviconPreviewBox" onclick="document.getElementById('faviconInput').click()">
                        <?php if (!empty($headerSettings['favicon'])): ?>
                        <img src="<?php echo htmlspecialchars($headerSettings['favicon']); ?>" alt="Favicon" id="faviconPreviewImg">
                        <button type="button" class="favicon-remove-btn" onclick="event.stopPropagation(); removeFavicon()">
                            <iconify-icon icon="solar:trash-bin-trash-bold"></iconify-icon>
                        </button>
                        <?php else: ?>
                        <div class="favicon-placeholder" id="faviconPlaceholder">
                            <iconify-icon icon="solar:bookmark-square-bold"></iconify-icon>
                            <span>32x32 px</span>
                        </div>
                        <?php endif; ?>
                    </div>
                    <div class="favicon-info">
                        <button type="button" class="btn btn-secondary btn-sm" onclick="document.getElementById('faviconInput').click()">
                            <iconify-icon icon="solar:upload-bold"></iconify-icon>
                            <?php echo empty($headerSettings['favicon']) ? 'Enviar Favicon' : 'Trocar Favicon'; ?>
                        </button>
                        <p class="favicon-upload-hint">PNG ou ICO. Tamanho recomendado: 32x32 ou 64x64 pixels.</p>
                    </div>
                </div>
                <input type="file" name="favicon_file" id="faviconInput" accept="image/png,image/x-icon,image/ico,.ico" onchange="previewFavicon(this)" style="display: none;">
            </div>

            <button type="submit" class="btn btn-primary">
                <iconify-icon icon="solar:check-circle-bold"></iconify-icon>
                Salvar Alterações
            </button>
        </form>
    </div>

    <!-- Domain -->
    <div class="card tab-content <?php echo $activeTab === 'domain' ? 'active' : ''; ?>" id="tab-domain">
        <h2 style="font-size: 1.1rem; margin-bottom: 1.5rem;">
            <iconify-icon icon="solar:global-bold"></iconify-icon>
            Configurações de Domínio
        </h2>
        <p style="color: var(--text-muted); margin-bottom: 1.5rem;">
            Escolha como seus clientes vão acessar sua loja online.
        </p>
        
        <form method="POST" id="domainForm">
            <input type="hidden" name="action" value="update_domain">
            <input type="hidden" name="csrf_token" value="<?php echo $csrfToken; ?>">
            <input type="hidden" name="domain_type" id="domainType" value="<?php echo htmlspecialchars($domainType); ?>">
            
            <div class="domain-options">
                <!-- Opção 1: Caminho -->
                <label class="domain-option <?php echo $domainType === 'path' ? 'selected' : ''; ?>" data-type="path">
                    <input type="radio" name="domain_type_radio" value="path" <?php echo $domainType === 'path' ? 'checked' : ''; ?>>
                    <div class="domain-option-header">
                        <div class="domain-option-radio"></div>
                        <span class="domain-option-title">Caminho</span>
                        <span class="domain-option-badge">
                            <iconify-icon icon="solar:check-circle-bold"></iconify-icon>
                            Gratuito
                        </span>
                        <iconify-icon icon="solar:folder-path-connect-bold" class="domain-option-icon"></iconify-icon>
                    </div>
                    <div class="domain-option-url">
                        <iconify-icon icon="solar:link-bold"></iconify-icon>
                        <?php echo $urlPath; ?>
                        <button type="button" class="copy-btn" onclick="copyToClipboard('<?php echo $urlPath; ?>', event)" title="Copiar">
                            <iconify-icon icon="solar:copy-bold"></iconify-icon>
                        </button>
                    </div>
                    <p class="domain-option-description">
                        Sua loja ficará acessível em um caminho do domínio principal. Ideal para começar rapidamente.
                    </p>
                </label>
                
                <!-- Opção 2: Subdomínio -->
                <label class="domain-option <?php echo $domainType === 'subdomain' ? 'selected' : ''; ?>" data-type="subdomain">
                    <input type="radio" name="domain_type_radio" value="subdomain" <?php echo $domainType === 'subdomain' ? 'checked' : ''; ?>>
                    <div class="domain-option-header">
                        <div class="domain-option-radio"></div>
                        <span class="domain-option-title">Subdomínio</span>
                        <span class="domain-option-badge" style="background: var(--primary);">
                            <iconify-icon icon="solar:star-bold"></iconify-icon>
                            Recomendado
                        </span>
                        <iconify-icon icon="solar:server-square-bold" class="domain-option-icon"></iconify-icon>
                    </div>
                    <div class="domain-option-url">
                        <iconify-icon icon="solar:link-bold"></iconify-icon>
                        <?php echo $urlSubdomain; ?>
                        <button type="button" class="copy-btn" onclick="copyToClipboard('<?php echo $urlSubdomain; ?>', event)" title="Copiar">
                            <iconify-icon icon="solar:copy-bold"></iconify-icon>
                        </button>
                    </div>
                    <p class="domain-option-description">
                        Sua loja terá um subdomínio exclusivo. URL mais curta e profissional.
                    </p>
                </label>

                <?php if (shouldLockFeature('custom_domain')): ?>
                <!-- VERSÃO BLOQUEADA -->
                <div class="premium-locked">
                    <div class="premium-content">
                        <!-- Mock content hidden via CSS -->
                        <label class="domain-option disabled">
                             N/A
                        </label>
                    </div>
                    <div class="premium-overlay">
                        <div class="premium-card">
                            <h3 class="premium-card-title">Domínio Personalizado</h3>
                            <p class="premium-card-description">Use seu próprio domínio para uma identidade profissional completa!</p>
                            <div class="premium-card-plan">
                                <iconify-icon icon="solar:crown-bold"></iconify-icon>
                                Disponível no plano Pro
                            </div>
                            <ul class="premium-card-features">
                                <li><iconify-icon icon="solar:check-circle-bold"></iconify-icon> Use seu próprio domínio</li>
                                <li><iconify-icon icon="solar:check-circle-bold"></iconify-icon> Identidade de marca completa</li>
                            </ul>
                            <a href="/pages/upgrade.php" class="btn-upgrade">
                                <iconify-icon icon="solar:rocket-bold"></iconify-icon>
                                Fazer Upgrade
                            </a>
                        </div>
                    </div>
                </div>
                <?php else: ?>
                <!-- VERSÃO DESBLOQUEADA -->
                <label class="domain-option <?php echo $domainType === 'custom' ? 'selected' : ''; ?>" data-type="custom">
                    <input type="radio" name="domain_type_radio" value="custom" <?php echo $domainType === 'custom' ? 'checked' : ''; ?>>
                    <div class="domain-option-header">
                        <div class="domain-option-radio"></div>
                        <span class="domain-option-title">Domínio Próprio</span>
                        <span class="domain-option-badge" style="background: #F59E0B;">
                            <iconify-icon icon="solar:crown-bold"></iconify-icon>
                            Premium
                        </span>
                        <iconify-icon icon="solar:global-bold" class="domain-option-icon"></iconify-icon>
                    </div>

                    <?php if ($customDomain): ?>
                    <div class="domain-option-url">
                        <iconify-icon icon="solar:link-bold"></iconify-icon>
                        https://<?php echo htmlspecialchars($customDomain); ?>
                        <button type="button" class="copy-btn" onclick="copyToClipboard('https://<?php echo htmlspecialchars($customDomain); ?>', event)" title="Copiar">
                            <iconify-icon icon="solar:copy-bold"></iconify-icon>
                        </button>
                    </div>
                    <?php endif; ?>

                    <p class="domain-option-description">
                        Use seu próprio domínio Ex: www.suamarca.com.br
                    </p>

                    <div class="custom-domain-input">
                        <div class="form-group" style="margin-bottom: 0;">
                            <label class="form-label">Seu Domínio</label>
                            <input type="text" name="custom_domain" class="form-input"
                                   placeholder="www.seudominio.com.br"
                                   value="<?php echo htmlspecialchars($customDomain); ?>">
                            <small style="color: var(--text-muted);">
                                Digite apenas o domínio, sem http:// ou https://
                            </small>
                        </div>

                        <?php if ($customDomain): ?>
                        <div class="domain-status pending">
                            <iconify-icon icon="solar:clock-circle-bold"></iconify-icon>
                            <span>Aguardando configuração de DNS.</span>
                        </div>
                        <?php endif; ?>

                        <div class="dns-instructions">
                            <h4><iconify-icon icon="solar:settings-bold"></iconify-icon> Configuração DNS</h4>
                            <table class="dns-table">
                                <thead><tr><th>Tipo</th><th>Nome</th><th>Valor</th><th></th></tr></thead>
                                <tbody>
                                    <tr>
                                        <td><code>CNAME</code></td>
                                        <td><code>www</code></td>
                                        <td><code><?php echo htmlspecialchars($currentHost); ?></code></td>
                                        <td><button type="button" class="copy-btn" onclick="copyToClipboard('<?php echo htmlspecialchars($currentHost); ?>', event)"><iconify-icon icon="solar:copy-bold"></iconify-icon></button></td>
                                    </tr>
                                    <tr>
                                        <td><code>A</code></td>
                                        <td><code>@</code></td>
                                        <td><code>187.33.241.55</code></td>
                                        <td><button type="button" class="copy-btn" onclick="copyToClipboard('187.33.241.55', event)"><iconify-icon icon="solar:copy-bold"></iconify-icon></button></td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </label>
                <?php endif; ?>
            </div>

            <button type="submit" class="btn btn-primary" style="margin-top: 1.5rem;">
                <iconify-icon icon="solar:check-circle-bold"></iconify-icon>
                Salvar Configurações de Domínio
            </button>
        </form>
    </div>

    <!-- Redes Sociais -->
    <div class="card tab-content <?php echo $activeTab === 'social' ? 'active' : ''; ?>" id="tab-social">
        <h2 style="font-size: 1.1rem; margin-bottom: 1.5rem;">
            <iconify-icon icon="solar:share-bold"></iconify-icon>
            Redes Sociais
        </h2>
        <form method="POST">
            <input type="hidden" name="action" value="update_social">
            <input type="hidden" name="csrf_token" value="<?php echo $csrfToken; ?>">

            <div class="form-group">
                <label class="form-label">Instagram</label>
                <div class="social-input">
                    <iconify-icon icon="mdi:instagram"></iconify-icon>
                    <input type="text" name="instagram" class="form-input" placeholder="@seuusuario" value="<?php echo htmlspecialchars($socialLinks['instagram'] ?? ''); ?>">
                </div>
            </div>

            <div class="form-group">
                <label class="form-label">Facebook</label>
                <div class="social-input">
                    <iconify-icon icon="mdi:facebook"></iconify-icon>
                    <input type="text" name="facebook" class="form-input" placeholder="facebook.com/suapagina" value="<?php echo htmlspecialchars($socialLinks['facebook'] ?? ''); ?>">
                </div>
            </div>

            <div class="form-group">
                <label class="form-label">WhatsApp</label>
                <div class="social-input">
                    <iconify-icon icon="mdi:whatsapp"></iconify-icon>
                    <input type="text" name="whatsapp" class="form-input" placeholder="11999999999" value="<?php echo htmlspecialchars($socialLinks['whatsapp'] ?? ''); ?>">
                </div>
            </div>

            <div class="form-group">
                <label class="form-label">TikTok</label>
                <div class="social-input">
                    <iconify-icon icon="ic:baseline-tiktok"></iconify-icon>
                    <input type="text" name="tiktok" class="form-input" placeholder="@seuusuario" value="<?php echo htmlspecialchars($socialLinks['tiktok'] ?? ''); ?>">
                </div>
            </div>

            <button type="submit" class="btn btn-primary">
                <iconify-icon icon="solar:check-circle-bold"></iconify-icon>
                Salvar Redes Sociais
            </button>
        </form>
    </div>

    <!-- SEO -->
    <div class="card tab-content <?php echo $activeTab === 'seo' ? 'active' : ''; ?>" id="tab-seo">
        <h2 style="font-size: 1.1rem; margin-bottom: 1.5rem;">
            <iconify-icon icon="solar:magnifer-bold"></iconify-icon>
            Otimização para Buscadores (SEO)
        </h2>
        <form method="POST" enctype="multipart/form-data">
            <input type="hidden" name="action" value="update_seo">
            <input type="hidden" name="csrf_token" value="<?php echo $csrfToken; ?>">

            <div class="form-group">
                <label class="form-label">Título da Página (Meta Title)</label>
                <input type="text" name="meta_title" class="form-input" placeholder="Nome da Loja | Produtos Incríveis" value="<?php echo htmlspecialchars($seoSettings['meta_title'] ?? ''); ?>" maxlength="70">
                <small style="color: var(--text-muted);">Máximo 70 caracteres. Aparece nos resultados do Google.</small>
            </div>

            <div class="form-group">
                <label class="form-label">Descrição (Meta Description)</label>
                <textarea name="meta_description" class="form-input" rows="3" placeholder="Uma breve descrição da sua loja para os buscadores..." maxlength="160"><?php echo htmlspecialchars($seoSettings['meta_description'] ?? ''); ?></textarea>
                <small style="color: var(--text-muted);">Máximo 160 caracteres. Aparece abaixo do título no Google.</small>
            </div>

            <div class="form-group">
                <label class="form-label">Palavras-chave</label>
                <input type="text" name="keywords" class="form-input" placeholder="loja online, produtos, compras" value="<?php echo htmlspecialchars($seoSettings['keywords'] ?? ''); ?>">
                <small style="color: var(--text-muted);">Separe as palavras-chave por vírgula</small>
            </div>

            <h3 style="margin-top: 2rem; margin-bottom: 1rem; font-size: 1rem; font-weight: 600; padding-top: 1.5rem; border-top: 1px solid var(--border);">
                <iconify-icon icon="solar:share-bold"></iconify-icon> Redes Sociais (Open Graph)
            </h3>

            <div class="form-group">
                <label class="form-label">Imagem social</label>
                <div class="logo-preview-box" id="socialPreviewBox" onclick="document.getElementById('socialImageInput').click()" style="height: auto; aspect-ratio: 16/9; margin-bottom: 1rem; max-width: 350px;">
                    <?php if (!empty($seoSettings['social_image'])): ?>
                    <img src="<?php echo htmlspecialchars($seoSettings['social_image']); ?>" alt="Social Preview" id="socialPreviewImg" style="width: 100%; height: 100%; object-fit: cover;">
                    <button type="button" class="logo-remove-btn" onclick="event.stopPropagation(); removeSocialImage()">
                        <iconify-icon icon="solar:trash-bin-trash-bold"></iconify-icon>
                    </button>
                    <?php else: ?>
                    <div class="logo-placeholder" id="socialPlaceholder" style="flex-direction: column;">
                        <iconify-icon icon="solar:gallery-add-bold" style="font-size: 2.5rem; margin-bottom: 0.5rem;"></iconify-icon>
                        <span style="font-size: 0.9rem; text-align: center;">O tamanho recomendado para esta imagem é 1200x675px</span>
                    </div>
                    <?php endif; ?>
                </div>
                <input type="file" name="social_image_file" id="socialImageInput" accept="image/*" onchange="previewSocialImage(this)" style="display: none;">
                <input type="hidden" name="remove_social_image" id="removeSocialImageInput" value="0">
                
                <button type="button" class="btn btn-outline btn-sm" onclick="document.getElementById('socialImageInput').click()">
                    Selecione a imagem
                </button>
            </div>

            <div class="form-group">
                <label class="form-label">Título social</label>
                <input type="text" name="social_title" class="form-input" placeholder="Título para redes sociais" value="<?php echo htmlspecialchars($seoSettings['social_title'] ?? ''); ?>">
            </div>

            <div class="form-group">
                <label class="form-label">Descrição social</label>
                <textarea name="social_description" class="form-input" rows="3" placeholder="Descrição para redes sociais"><?php echo htmlspecialchars($seoSettings['social_description'] ?? ''); ?></textarea>
            </div>

            <button type="submit" class="btn btn-primary">
                <iconify-icon icon="solar:check-circle-bold"></iconify-icon>
                Salvar Configurações SEO
            </button>
        </form>
    </div>
</main>

<script src="/assets/js/pages/store-settings.js?v=<?php echo time(); ?>"></script>
<?php include __DIR__ . '/../includes/dashboard-footer.php'; ?>
