<?php
/**
 * MontaLoja - Gerenciador de Templates de Landing Pages
 * Permite criar, editar e gerenciar templates de páginas de venda
 */
require_once __DIR__ . '/../../../includes/config.php';

if (!isSuperAdmin()) {
    header('Location: /pages/login.php');
    exit;
}

$superAdmin = getSuperAdmin();
$pdo = getDB();
$pageTitle = 'Templates de Landing Page';

$success = '';
$error = '';

// Processar ações
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    try {
        if ($action === 'create') {
            $name = trim($_POST['name'] ?? '');
            $slug = trim($_POST['slug'] ?? '');
            $description = trim($_POST['description'] ?? '');
            $category = $_POST['category'] ?? 'modern';
            $isPremium = isset($_POST['is_premium']) ? 1 : 0;
            $isActive = isset($_POST['is_active']) ? 1 : 0;
            
            // Gerar slug se não informado
            if (empty($slug)) {
                $slug = strtolower(preg_replace('/[^a-zA-Z0-9]+/', '-', $name));
            }
            
            // Configurações padrão do template
            $settings = json_encode([
                'colors' => [
                    'primary' => $_POST['color_primary'] ?? '#CCA43B',
                    'secondary' => $_POST['color_secondary'] ?? '#1A1A1A',
                    'accent' => $_POST['color_accent'] ?? '#FFFFFF',
                    'background' => $_POST['color_background'] ?? '#0F0F0F'
                ],
                'fonts' => [
                    'heading' => $_POST['font_heading'] ?? 'Inter',
                    'body' => $_POST['font_body'] ?? 'Inter'
                ],
                'sections' => [
                    'hero' => true,
                    'features' => true,
                    'products' => true,
                    'testimonials' => true,
                    'cta' => true,
                    'footer' => true
                ],
                'layout' => $_POST['layout'] ?? 'fullwidth'
            ]);
            
            // Upload de imagem de preview
            $previewImage = '';
            if (!empty($_FILES['preview_image']['name'])) {
                $uploadDir = '/home/socialar/dev.duolead.com.br/assets/images/templates/';
                if (!is_dir($uploadDir)) {
                    mkdir($uploadDir, 0755, true);
                }
                $fileName = $slug . '-' . time() . '.' . pathinfo($_FILES['preview_image']['name'], PATHINFO_EXTENSION);
                $uploadPath = $uploadDir . $fileName;
                
                if (move_uploaded_file($_FILES['preview_image']['tmp_name'], $uploadPath)) {
                    $previewImage = '/assets/images/templates/' . $fileName;
                }
            }
            
            $stmt = $pdo->prepare("
                INSERT INTO store_templates (name, slug, description, preview_image, category, is_premium, is_active, settings)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?)
            ");
            $stmt->execute([$name, $slug, $description, $previewImage, $category, $isPremium, $isActive, $settings]);
            $success = 'Template criado com sucesso!';
            
        } elseif ($action === 'update') {
            $id = (int)$_POST['id'];
            $name = trim($_POST['name'] ?? '');
            $description = trim($_POST['description'] ?? '');
            $category = $_POST['category'] ?? 'modern';
            $isPremium = isset($_POST['is_premium']) ? 1 : 0;
            $isActive = isset($_POST['is_active']) ? 1 : 0;
            
            $settings = json_encode([
                'colors' => [
                    'primary' => $_POST['color_primary'] ?? '#CCA43B',
                    'secondary' => $_POST['color_secondary'] ?? '#1A1A1A',
                    'accent' => $_POST['color_accent'] ?? '#FFFFFF',
                    'background' => $_POST['color_background'] ?? '#0F0F0F'
                ],
                'fonts' => [
                    'heading' => $_POST['font_heading'] ?? 'Inter',
                    'body' => $_POST['font_body'] ?? 'Inter'
                ],
                'sections' => [
                    'hero' => isset($_POST['section_hero']),
                    'features' => isset($_POST['section_features']),
                    'products' => isset($_POST['section_products']),
                    'testimonials' => isset($_POST['section_testimonials']),
                    'cta' => isset($_POST['section_cta']),
                    'footer' => isset($_POST['section_footer'])
                ],
                'layout' => $_POST['layout'] ?? 'fullwidth'
            ]);
            
            // Upload de nova imagem
            $previewUpdate = '';
            if (!empty($_FILES['preview_image']['name'])) {
                $uploadDir = '/home/socialar/dev.duolead.com.br/assets/images/templates/';
                $stmt = $pdo->prepare("SELECT slug FROM store_templates WHERE id = ?");
                $stmt->execute([$id]);
                $template = $stmt->fetch();
                
                $fileName = $template['slug'] . '-' . time() . '.' . pathinfo($_FILES['preview_image']['name'], PATHINFO_EXTENSION);
                $uploadPath = $uploadDir . $fileName;
                
                if (move_uploaded_file($_FILES['preview_image']['tmp_name'], $uploadPath)) {
                    $previewUpdate = ", preview_image = '/assets/images/templates/" . $fileName . "'";
                }
            }
            
            $sql = "UPDATE store_templates SET name = ?, description = ?, category = ?, is_premium = ?, is_active = ?, settings = ? $previewUpdate WHERE id = ?";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([$name, $description, $category, $isPremium, $isActive, $settings, $id]);
            $success = 'Template atualizado com sucesso!';
            
        } elseif ($action === 'delete') {
            $id = (int)$_POST['id'];
            
            // Verificar se está em uso
            $stmt = $pdo->prepare("SELECT COUNT(*) FROM sales_page_templates WHERE template_name = (SELECT slug FROM store_templates WHERE id = ?)");
            $stmt->execute([$id]);
            $inUse = $stmt->fetchColumn();
            
            if ($inUse > 0) {
                $error = 'Este template está em uso por ' . $inUse . ' loja(s) e não pode ser excluído.';
            } else {
                $stmt = $pdo->prepare("DELETE FROM store_templates WHERE id = ?");
                $stmt->execute([$id]);
                $success = 'Template excluído com sucesso!';
            }
            
        } elseif ($action === 'toggle_status') {
            $id = (int)$_POST['id'];
            $stmt = $pdo->prepare("UPDATE store_templates SET is_active = NOT is_active WHERE id = ?");
            $stmt->execute([$id]);
            $success = 'Status atualizado!';
            
        } elseif ($action === 'duplicate') {
            $id = (int)$_POST['id'];
            
            $stmt = $pdo->prepare("SELECT * FROM store_templates WHERE id = ?");
            $stmt->execute([$id]);
            $template = $stmt->fetch();
            
            if ($template) {
                $newSlug = $template['slug'] . '-copy-' . time();
                $newName = $template['name'] . ' (Cópia)';
                
                $stmt = $pdo->prepare("
                    INSERT INTO store_templates (name, slug, description, preview_image, category, is_premium, is_active, settings)
                    VALUES (?, ?, ?, ?, ?, ?, 0, ?)
                ");
                $stmt->execute([
                    $newName,
                    $newSlug,
                    $template['description'],
                    $template['preview_image'],
                    $template['category'],
                    $template['is_premium'],
                    $template['settings']
                ]);
                $success = 'Template duplicado com sucesso!';
            }
        }
    } catch (PDOException $e) {
        $error = 'Erro: ' . $e->getMessage();
    }
}

// Buscar templates
$templates = $pdo->query("
    SELECT t.*, 
           (SELECT COUNT(*) FROM sales_page_templates spt WHERE spt.template_name = t.slug) as usage_count
    FROM store_templates t
    ORDER BY t.created_at DESC
")->fetchAll();

// Estatísticas
$stats = [
    'total' => count($templates),
    'active' => count(array_filter($templates, fn($t) => $t['is_active'])),
    'premium' => count(array_filter($templates, fn($t) => $t['is_premium'])),
    'in_use' => count(array_filter($templates, fn($t) => $t['usage_count'] > 0))
];

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

<style>
/* Estilos específicos para esta página */
.templates-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
    gap: 1.5rem;
    margin-top: 1.5rem;
}

.template-card {
    background: var(--bg-panel);
    border-radius: var(--radius-lg);
    overflow: hidden;
    border: 1px solid var(--border-light);
    transition: all 0.3s ease;
}

.template-card:hover {
    transform: translateY(-4px);
    box-shadow: var(--shadow-lg);
    border-color: var(--gold);
}

.template-preview {
    position: relative;
    height: 200px;
    background: linear-gradient(135deg, var(--bg-input) 0%, var(--bg-dark) 100%);
    display: flex;
    align-items: center;
    justify-content: center;
    overflow: hidden;
}

.template-preview img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.template-preview .no-preview {
    color: var(--text-muted);
    text-align: center;
}

.template-preview .no-preview iconify-icon {
    font-size: 3rem;
    margin-bottom: 0.5rem;
    opacity: 0.5;
}

.template-badges {
    position: absolute;
    top: 0.75rem;
    left: 0.75rem;
    display: flex;
    gap: 0.5rem;
}

.template-badge {
    padding: 0.25rem 0.75rem;
    border-radius: 20px;
    font-size: 0.7rem;
    font-weight: 600;
    text-transform: uppercase;
}

.badge-premium {
    background: linear-gradient(135deg, #FFD700 0%, #FFA500 100%);
    color: #1A1A1A;
}

.badge-active {
    background: var(--success);
    color: white;
}

.badge-inactive {
    background: var(--text-muted);
    color: white;
}

.badge-category {
    background: var(--bg-panel);
    color: var(--text-primary);
    border: 1px solid var(--border-light);
}

.template-actions-overlay {
    position: absolute;
    inset: 0;
    background: rgba(0, 0, 0, 0.7);
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 0.5rem;
    opacity: 0;
    transition: opacity 0.3s ease;
}

.template-card:hover .template-actions-overlay {
    opacity: 1;
}

.template-actions-overlay button {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    border: none;
    background: var(--bg-panel);
    color: var(--text-primary);
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.2s;
}

.template-actions-overlay button:hover {
    background: var(--gold);
    color: var(--bg-dark);
    transform: scale(1.1);
}

.template-info {
    padding: 1.25rem;
}

.template-name {
    font-size: 1.1rem;
    font-weight: 600;
    color: var(--text-primary);
    margin-bottom: 0.5rem;
}

.template-description {
    font-size: 0.85rem;
    color: var(--text-muted);
    line-height: 1.5;
    margin-bottom: 1rem;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
}

.template-meta {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-top: 1rem;
    border-top: 1px solid var(--border-light);
}

.template-usage {
    font-size: 0.8rem;
    color: var(--text-muted);
    display: flex;
    align-items: center;
    gap: 0.25rem;
}

.template-usage.in-use {
    color: var(--success);
}

/* Modal de criação/edição */
.modal-overlay {
    position: fixed;
    inset: 0;
    background: rgba(0, 0, 0, 0.8);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 9999;
    opacity: 0;
    visibility: hidden;
    transition: all 0.3s ease;
}

.modal-overlay.active {
    opacity: 1;
    visibility: visible;
}

.modal-content {
    background: var(--bg-panel);
    border-radius: var(--radius-lg);
    width: 90%;
    max-width: 700px;
    max-height: 90vh;
    overflow-y: auto;
    transform: scale(0.9);
    transition: transform 0.3s ease;
}

.modal-overlay.active .modal-content {
    transform: scale(1);
}

.modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 1.5rem;
    border-bottom: 1px solid var(--border-light);
    position: sticky;
    top: 0;
    background: var(--bg-panel);
    z-index: 10;
}

.modal-title {
    font-size: 1.25rem;
    font-weight: 600;
    color: var(--text-primary);
    display: flex;
    align-items: center;
    gap: 0.75rem;
}

.modal-close {
    width: 36px;
    height: 36px;
    border-radius: 50%;
    border: none;
    background: var(--bg-input);
    color: var(--text-muted);
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.2s;
}

.modal-close:hover {
    background: var(--danger);
    color: white;
}

.modal-body {
    padding: 1.5rem;
}

.form-section {
    margin-bottom: 1.5rem;
}

.form-section-title {
    font-size: 0.85rem;
    font-weight: 600;
    color: var(--gold);
    margin-bottom: 1rem;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

.form-row {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 1rem;
}

.form-group {
    margin-bottom: 1rem;
}

.form-group.full-width {
    grid-column: span 2;
}

.form-label {
    display: block;
    font-size: 0.85rem;
    font-weight: 500;
    color: var(--text-muted);
    margin-bottom: 0.5rem;
}

.form-input,
.form-select,
.form-textarea {
    width: 100%;
    padding: 0.75rem 1rem;
    background: var(--bg-input);
    border: 1px solid var(--border-light);
    border-radius: var(--radius-md);
    color: var(--text-primary);
    font-size: 0.9rem;
    transition: all 0.2s;
}

.form-input:focus,
.form-select:focus,
.form-textarea:focus {
    outline: none;
    border-color: var(--gold);
    box-shadow: 0 0 0 3px var(--gold-light);
}

.form-textarea {
    min-height: 100px;
    resize: vertical;
}

.color-inputs {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 0.75rem;
}

.color-input-group {
    text-align: center;
}

.color-input-group label {
    display: block;
    font-size: 0.75rem;
    color: var(--text-muted);
    margin-bottom: 0.5rem;
}

.color-input-group input[type="color"] {
    width: 100%;
    height: 40px;
    border: none;
    border-radius: var(--radius-md);
    cursor: pointer;
    background: transparent;
}

.toggle-group {
    display: flex;
    align-items: center;
    gap: 0.75rem;
    padding: 0.75rem;
    background: var(--bg-input);
    border-radius: var(--radius-md);
    margin-bottom: 0.5rem;
}

.toggle-switch {
    position: relative;
    width: 44px;
    height: 24px;
    flex-shrink: 0;
}

.toggle-switch input {
    opacity: 0;
    width: 0;
    height: 0;
}

.toggle-slider {
    position: absolute;
    cursor: pointer;
    inset: 0;
    background: var(--bg-dark);
    border-radius: 24px;
    transition: 0.3s;
}

.toggle-slider:before {
    position: absolute;
    content: "";
    height: 18px;
    width: 18px;
    left: 3px;
    bottom: 3px;
    background: white;
    border-radius: 50%;
    transition: 0.3s;
}

.toggle-switch input:checked + .toggle-slider {
    background: var(--gold);
}

.toggle-switch input:checked + .toggle-slider:before {
    transform: translateX(20px);
}

.toggle-label {
    font-size: 0.9rem;
    color: var(--text-primary);
}

.toggle-description {
    font-size: 0.75rem;
    color: var(--text-muted);
}

.modal-footer {
    display: flex;
    justify-content: flex-end;
    gap: 1rem;
    padding: 1.5rem;
    border-top: 1px solid var(--border-light);
    position: sticky;
    bottom: 0;
    background: var(--bg-panel);
}

.btn {
    padding: 0.75rem 1.5rem;
    border-radius: var(--radius-md);
    font-size: 0.9rem;
    font-weight: 500;
    cursor: pointer;
    display: inline-flex;
    align-items: center;
    gap: 0.5rem;
    transition: all 0.2s;
    border: none;
}

.btn-primary {
    background: var(--gold);
    color: var(--bg-dark);
}

.btn-primary:hover {
    background: var(--gold-hover);
    transform: translateY(-2px);
}

.btn-secondary {
    background: var(--bg-input);
    color: var(--text-primary);
}

.btn-secondary:hover {
    background: var(--border-light);
}

.btn-danger {
    background: var(--danger);
    color: white;
}

.btn-danger:hover {
    opacity: 0.9;
}

/* Stats cards */
.stats-row {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 1rem;
    margin-bottom: 1.5rem;
}

.stat-card {
    background: var(--bg-panel);
    border-radius: var(--radius-lg);
    padding: 1.25rem;
    display: flex;
    align-items: center;
    gap: 1rem;
    border: 1px solid var(--border-light);
}

.stat-icon {
    width: 48px;
    height: 48px;
    border-radius: var(--radius-md);
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.5rem;
}

.stat-icon.total { background: var(--gold-light); color: var(--gold); }
.stat-icon.active { background: rgba(34, 197, 94, 0.15); color: var(--success); }
.stat-icon.premium { background: rgba(255, 215, 0, 0.15); color: #FFD700; }
.stat-icon.usage { background: rgba(59, 130, 246, 0.15); color: var(--info); }

.stat-info h3 {
    font-size: 1.5rem;
    font-weight: 700;
    color: var(--text-primary);
}

.stat-info p {
    font-size: 0.8rem;
    color: var(--text-muted);
}

/* Preview modal */
.preview-modal {
    max-width: 1000px;
}

.preview-frame {
    width: 100%;
    height: 70vh;
    border: none;
    border-radius: var(--radius-md);
    background: white;
}

/* File input custom */
.file-input-wrapper {
    position: relative;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 2rem;
    background: var(--bg-input);
    border: 2px dashed var(--border-light);
    border-radius: var(--radius-md);
    cursor: pointer;
    transition: all 0.2s;
}

.file-input-wrapper:hover {
    border-color: var(--gold);
    background: var(--gold-light);
}

.file-input-wrapper input {
    position: absolute;
    inset: 0;
    opacity: 0;
    cursor: pointer;
}

.file-input-wrapper iconify-icon {
    font-size: 2.5rem;
    color: var(--text-muted);
    margin-bottom: 0.5rem;
}

.file-input-wrapper span {
    color: var(--text-muted);
    font-size: 0.85rem;
}

/* Header actions */
.page-header-actions {
    display: flex;
    gap: 1rem;
    margin-bottom: 1.5rem;
}

.search-box {
    flex: 1;
    max-width: 400px;
    position: relative;
}

.search-box input {
    width: 100%;
    padding: 0.75rem 1rem 0.75rem 2.75rem;
    background: var(--bg-panel);
    border: 1px solid var(--border-light);
    border-radius: var(--radius-md);
    color: var(--text-primary);
    font-size: 0.9rem;
}

.search-box iconify-icon {
    position: absolute;
    left: 1rem;
    top: 50%;
    transform: translateY(-50%);
    color: var(--text-muted);
}

.filter-select {
    padding: 0.75rem 1rem;
    background: var(--bg-panel);
    border: 1px solid var(--border-light);
    border-radius: var(--radius-md);
    color: var(--text-primary);
    font-size: 0.9rem;
    min-width: 150px;
}

@media (max-width: 768px) {
    .stats-row {
        grid-template-columns: repeat(2, 1fr);
    }
    
    .templates-grid {
        grid-template-columns: 1fr;
    }
    
    .form-row {
        grid-template-columns: 1fr;
    }
    
    .form-group.full-width {
        grid-column: span 1;
    }
    
    .color-inputs {
        grid-template-columns: repeat(2, 1fr);
    }
    
    .page-header-actions {
        flex-wrap: wrap;
    }
    
    .search-box {
        max-width: 100%;
        order: 3;
        width: 100%;
    }
}
</style>

<div class="app-container">
    <?php include __DIR__ . '/../includes/sidebar.php'; ?>
    
    <main class="main-content">
        <?php include __DIR__ . '/../includes/topbar.php'; ?>
        
        <div class="content-area">
            <?php if ($success): ?>
                <div class="alert alert-success">
                    <iconify-icon icon="solar:check-circle-bold"></iconify-icon>
                    <?= htmlspecialchars($success) ?>
                </div>
            <?php endif; ?>
            
            <?php if ($error): ?>
                <div class="alert alert-error">
                    <iconify-icon icon="solar:danger-triangle-bold"></iconify-icon>
                    <?= htmlspecialchars($error) ?>
                </div>
            <?php endif; ?>
            
            <!-- Stats -->
            <div class="stats-row">
                <div class="stat-card">
                    <div class="stat-icon total">
                        <iconify-icon icon="solar:layers-bold"></iconify-icon>
                    </div>
                    <div class="stat-info">
                        <h3><?= $stats['total'] ?></h3>
                        <p>Total de Templates</p>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-icon active">
                        <iconify-icon icon="solar:check-circle-bold"></iconify-icon>
                    </div>
                    <div class="stat-info">
                        <h3><?= $stats['active'] ?></h3>
                        <p>Templates Ativos</p>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-icon premium">
                        <iconify-icon icon="solar:crown-bold"></iconify-icon>
                    </div>
                    <div class="stat-info">
                        <h3><?= $stats['premium'] ?></h3>
                        <p>Templates Premium</p>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-icon usage">
                        <iconify-icon icon="solar:shop-bold"></iconify-icon>
                    </div>
                    <div class="stat-info">
                        <h3><?= $stats['in_use'] ?></h3>
                        <p>Em Uso por Lojas</p>
                    </div>
                </div>
            </div>
            
            <!-- Header Actions -->
            <div class="page-header-actions">
                <div class="search-box">
                    <iconify-icon icon="solar:magnifer-linear"></iconify-icon>
                    <input type="text" id="searchTemplates" placeholder="Buscar templates...">
                </div>
                
                <select class="filter-select" id="filterCategory">
                    <option value="">Todas categorias</option>
                    <option value="modern">Modern</option>
                    <option value="classic">Classic</option>
                    <option value="minimal">Minimal</option>
                    <option value="bold">Bold</option>
                </select>
                
                <select class="filter-select" id="filterStatus">
                    <option value="">Todos status</option>
                    <option value="active">Ativos</option>
                    <option value="inactive">Inativos</option>
                </select>
                
                <button class="btn btn-primary" onclick="openCreateModal()">
                    <iconify-icon icon="solar:add-circle-bold"></iconify-icon>
                    Novo Template
                </button>
            </div>
            
            <!-- Templates Grid -->
            <div class="templates-grid" id="templatesGrid">
                <?php if (empty($templates)): ?>
                    <div class="panel" style="grid-column: 1 / -1; text-align: center; padding: 3rem;">
                        <iconify-icon icon="solar:layers-minimalistic-bold" style="font-size: 4rem; color: var(--text-muted); opacity: 0.5;"></iconify-icon>
                        <h3 style="margin-top: 1rem; color: var(--text-muted);">Nenhum template cadastrado</h3>
                        <p style="color: var(--text-muted); margin-bottom: 1.5rem;">Crie seu primeiro template de landing page</p>
                        <button class="btn btn-primary" onclick="openCreateModal()">
                            <iconify-icon icon="solar:add-circle-bold"></iconify-icon>
                            Criar Template
                        </button>
                    </div>
                <?php else: ?>
                    <?php foreach ($templates as $template): 
                        $settings = json_decode($template['settings'] ?? '{}', true);
                    ?>
                        <div class="template-card" 
                             data-name="<?= strtolower($template['name']) ?>"
                             data-category="<?= $template['category'] ?>"
                             data-status="<?= $template['is_active'] ? 'active' : 'inactive' ?>">
                            <div class="template-preview">
                                <?php if ($template['preview_image']): ?>
                                    <img src="<?= htmlspecialchars($template['preview_image']) ?>" alt="<?= htmlspecialchars($template['name']) ?>">
                                <?php else: ?>
                                    <div class="no-preview">
                                        <iconify-icon icon="solar:gallery-bold"></iconify-icon>
                                        <p>Sem preview</p>
                                    </div>
                                <?php endif; ?>
                                
                                <div class="template-badges">
                                    <?php if ($template['is_premium']): ?>
                                        <span class="template-badge badge-premium">
                                            <iconify-icon icon="solar:crown-bold"></iconify-icon> Premium
                                        </span>
                                    <?php endif; ?>
                                    <span class="template-badge <?= $template['is_active'] ? 'badge-active' : 'badge-inactive' ?>">
                                        <?= $template['is_active'] ? 'Ativo' : 'Inativo' ?>
                                    </span>
                                    <span class="template-badge badge-category">
                                        <?= ucfirst($template['category']) ?>
                                    </span>
                                </div>
                                
                                <div class="template-actions-overlay">
                                    <button onclick="previewTemplate(<?= $template['id'] ?>, '<?= htmlspecialchars($template['slug']) ?>')" title="Visualizar">
                                        <iconify-icon icon="solar:eye-bold"></iconify-icon>
                                    </button>
                                    <button onclick="editTemplate(<?= $template['id'] ?>)" title="Editar">
                                        <iconify-icon icon="solar:pen-bold"></iconify-icon>
                                    </button>
                                    <button onclick="duplicateTemplate(<?= $template['id'] ?>)" title="Duplicar">
                                        <iconify-icon icon="solar:copy-bold"></iconify-icon>
                                    </button>
                                    <button onclick="deleteTemplate(<?= $template['id'] ?>, '<?= htmlspecialchars($template['name']) ?>')" title="Excluir">
                                        <iconify-icon icon="solar:trash-bin-trash-bold"></iconify-icon>
                                    </button>
                                </div>
                            </div>
                            
                            <div class="template-info">
                                <h3 class="template-name"><?= htmlspecialchars($template['name']) ?></h3>
                                <p class="template-description"><?= htmlspecialchars($template['description'] ?: 'Sem descrição') ?></p>
                                
                                <div class="template-meta">
                                    <div class="template-usage <?= $template['usage_count'] > 0 ? 'in-use' : '' ?>">
                                        <iconify-icon icon="solar:shop-bold"></iconify-icon>
                                        <?= $template['usage_count'] ?> <?= $template['usage_count'] == 1 ? 'loja usando' : 'lojas usando' ?>
                                    </div>
                                    
                                    <form method="POST" style="margin: 0;">
                                        <input type="hidden" name="action" value="toggle_status">
                                        <input type="hidden" name="id" value="<?= $template['id'] ?>">
                                        <label class="toggle-switch" title="<?= $template['is_active'] ? 'Desativar' : 'Ativar' ?>">
                                            <input type="checkbox" <?= $template['is_active'] ? 'checked' : '' ?> onchange="this.form.submit()">
                                            <span class="toggle-slider"></span>
                                        </label>
                                    </form>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>
    </main>
</div>

<!-- Modal de Criação/Edição -->
<div class="modal-overlay" id="templateModal">
    <div class="modal-content">
        <div class="modal-header">
            <h2 class="modal-title">
                <iconify-icon icon="solar:layers-bold"></iconify-icon>
                <span id="modalTitle">Novo Template</span>
            </h2>
            <button class="modal-close" onclick="closeModal()">
                <iconify-icon icon="solar:close-circle-bold"></iconify-icon>
            </button>
        </div>
        
        <form method="POST" enctype="multipart/form-data" id="templateForm">
            <input type="hidden" name="action" id="formAction" value="create">
            <input type="hidden" name="id" id="templateId">
            
            <div class="modal-body">
                <!-- Informações Básicas -->
                <div class="form-section">
                    <h4 class="form-section-title">Informações Básicas</h4>
                    
                    <div class="form-row">
                        <div class="form-group">
                            <label class="form-label">Nome do Template *</label>
                            <input type="text" name="name" id="templateName" class="form-input" required placeholder="Ex: Landing Page Moderna">
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">Slug (URL)</label>
                            <input type="text" name="slug" id="templateSlug" class="form-input" placeholder="Gerado automaticamente">
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Descrição</label>
                        <textarea name="description" id="templateDescription" class="form-textarea" placeholder="Descreva o template..."></textarea>
                    </div>
                    
                    <div class="form-row">
                        <div class="form-group">
                            <label class="form-label">Categoria</label>
                            <select name="category" id="templateCategory" class="form-select">
                                <option value="modern">Modern</option>
                                <option value="classic">Classic</option>
                                <option value="minimal">Minimal</option>
                                <option value="bold">Bold</option>
                            </select>
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">Layout</label>
                            <select name="layout" id="templateLayout" class="form-select">
                                <option value="fullwidth">Full Width</option>
                                <option value="boxed">Boxed</option>
                                <option value="wide">Wide</option>
                            </select>
                        </div>
                    </div>
                </div>
                
                <!-- Cores -->
                <div class="form-section">
                    <h4 class="form-section-title">Paleta de Cores</h4>
                    
                    <div class="color-inputs">
                        <div class="color-input-group">
                            <label>Primária</label>
                            <input type="color" name="color_primary" id="colorPrimary" value="#CCA43B">
                        </div>
                        <div class="color-input-group">
                            <label>Secundária</label>
                            <input type="color" name="color_secondary" id="colorSecondary" value="#1A1A1A">
                        </div>
                        <div class="color-input-group">
                            <label>Destaque</label>
                            <input type="color" name="color_accent" id="colorAccent" value="#FFFFFF">
                        </div>
                        <div class="color-input-group">
                            <label>Fundo</label>
                            <input type="color" name="color_background" id="colorBackground" value="#0F0F0F">
                        </div>
                    </div>
                </div>
                
                <!-- Fontes -->
                <div class="form-section">
                    <h4 class="form-section-title">Tipografia</h4>
                    
                    <div class="form-row">
                        <div class="form-group">
                            <label class="form-label">Fonte dos Títulos</label>
                            <select name="font_heading" id="fontHeading" class="form-select">
                                <option value="Inter">Inter</option>
                                <option value="Poppins">Poppins</option>
                                <option value="Montserrat">Montserrat</option>
                                <option value="Playfair Display">Playfair Display</option>
                                <option value="Oswald">Oswald</option>
                            </select>
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">Fonte do Corpo</label>
                            <select name="font_body" id="fontBody" class="form-select">
                                <option value="Inter">Inter</option>
                                <option value="Open Sans">Open Sans</option>
                                <option value="Roboto">Roboto</option>
                                <option value="Lato">Lato</option>
                                <option value="Source Sans Pro">Source Sans Pro</option>
                            </select>
                        </div>
                    </div>
                </div>
                
                <!-- Imagem de Preview -->
                <div class="form-section">
                    <h4 class="form-section-title">Imagem de Preview</h4>
                    
                    <div class="file-input-wrapper">
                        <input type="file" name="preview_image" id="previewImage" accept="image/*">
                        <iconify-icon icon="solar:upload-bold"></iconify-icon>
                        <span>Clique ou arraste uma imagem</span>
                    </div>
                </div>
                
                <!-- Opções -->
                <div class="form-section">
                    <h4 class="form-section-title">Opções</h4>
                    
                    <div class="toggle-group">
                        <label class="toggle-switch">
                            <input type="checkbox" name="is_active" id="isActive" checked>
                            <span class="toggle-slider"></span>
                        </label>
                        <div>
                            <div class="toggle-label">Template Ativo</div>
                            <div class="toggle-description">Disponível para seleção pelas lojas</div>
                        </div>
                    </div>
                    
                    <div class="toggle-group">
                        <label class="toggle-switch">
                            <input type="checkbox" name="is_premium" id="isPremium">
                            <span class="toggle-slider"></span>
                        </label>
                        <div>
                            <div class="toggle-label">Template Premium</div>
                            <div class="toggle-description">Disponível apenas para planos pagos</div>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="closeModal()">Cancelar</button>
                <button type="submit" class="btn btn-primary">
                    <iconify-icon icon="solar:diskette-bold"></iconify-icon>
                    Salvar Template
                </button>
            </div>
        </form>
    </div>
</div>

<!-- Modal de Preview -->
<div class="modal-overlay" id="previewModal">
    <div class="modal-content preview-modal">
        <div class="modal-header">
            <h2 class="modal-title">
                <iconify-icon icon="solar:eye-bold"></iconify-icon>
                <span id="previewTitle">Preview do Template</span>
            </h2>
            <button class="modal-close" onclick="closePreviewModal()">
                <iconify-icon icon="solar:close-circle-bold"></iconify-icon>
            </button>
        </div>
        <div class="modal-body" style="padding: 0;">
            <iframe id="previewFrame" class="preview-frame"></iframe>
        </div>
    </div>
</div>

<!-- Form de ações oculto -->
<form id="actionForm" method="POST" style="display: none;">
    <input type="hidden" name="action" id="actionType">
    <input type="hidden" name="id" id="actionId">
</form>

<script>
// Templates data para edição
const templatesData = <?= json_encode($templates) ?>;

// Abrir modal de criação
function openCreateModal() {
    document.getElementById('modalTitle').textContent = 'Novo Template';
    document.getElementById('formAction').value = 'create';
    document.getElementById('templateForm').reset();
    document.getElementById('templateId').value = '';
    document.getElementById('isActive').checked = true;
    document.getElementById('templateModal').classList.add('active');
}

// Abrir modal de edição
function editTemplate(id) {
    const template = templatesData.find(t => t.id == id);
    if (!template) return;
    
    document.getElementById('modalTitle').textContent = 'Editar Template';
    document.getElementById('formAction').value = 'update';
    document.getElementById('templateId').value = template.id;
    document.getElementById('templateName').value = template.name;
    document.getElementById('templateSlug').value = template.slug;
    document.getElementById('templateDescription').value = template.description || '';
    document.getElementById('templateCategory').value = template.category;
    document.getElementById('isActive').checked = template.is_active == 1;
    document.getElementById('isPremium').checked = template.is_premium == 1;
    
    // Settings
    const settings = JSON.parse(template.settings || '{}');
    if (settings.colors) {
        document.getElementById('colorPrimary').value = settings.colors.primary || '#CCA43B';
        document.getElementById('colorSecondary').value = settings.colors.secondary || '#1A1A1A';
        document.getElementById('colorAccent').value = settings.colors.accent || '#FFFFFF';
        document.getElementById('colorBackground').value = settings.colors.background || '#0F0F0F';
    }
    if (settings.fonts) {
        document.getElementById('fontHeading').value = settings.fonts.heading || 'Inter';
        document.getElementById('fontBody').value = settings.fonts.body || 'Inter';
    }
    if (settings.layout) {
        document.getElementById('templateLayout').value = settings.layout;
    }
    
    document.getElementById('templateModal').classList.add('active');
}

// Fechar modal
function closeModal() {
    document.getElementById('templateModal').classList.remove('active');
}

// Preview do template
function previewTemplate(id, slug) {
    document.getElementById('previewTitle').textContent = 'Preview: ' + slug;
    document.getElementById('previewFrame').src = '/landing/' + slug + '?preview=1';
    document.getElementById('previewModal').classList.add('active');
}

// Fechar preview
function closePreviewModal() {
    document.getElementById('previewModal').classList.remove('active');
    document.getElementById('previewFrame').src = '';
}

// Duplicar template
function duplicateTemplate(id) {
    if (confirm('Deseja duplicar este template?')) {
        document.getElementById('actionType').value = 'duplicate';
        document.getElementById('actionId').value = id;
        document.getElementById('actionForm').submit();
    }
}

// Excluir template
function deleteTemplate(id, name) {
    if (confirm('Tem certeza que deseja excluir o template "' + name + '"?')) {
        document.getElementById('actionType').value = 'delete';
        document.getElementById('actionId').value = id;
        document.getElementById('actionForm').submit();
    }
}

// Filtros
document.getElementById('searchTemplates').addEventListener('input', filterTemplates);
document.getElementById('filterCategory').addEventListener('change', filterTemplates);
document.getElementById('filterStatus').addEventListener('change', filterTemplates);

function filterTemplates() {
    const search = document.getElementById('searchTemplates').value.toLowerCase();
    const category = document.getElementById('filterCategory').value;
    const status = document.getElementById('filterStatus').value;
    
    document.querySelectorAll('.template-card').forEach(card => {
        const name = card.dataset.name;
        const cardCategory = card.dataset.category;
        const cardStatus = card.dataset.status;
        
        const matchSearch = name.includes(search);
        const matchCategory = !category || cardCategory === category;
        const matchStatus = !status || cardStatus === status;
        
        card.style.display = matchSearch && matchCategory && matchStatus ? '' : 'none';
    });
}

// Gerar slug automaticamente
document.getElementById('templateName').addEventListener('input', function() {
    const slugField = document.getElementById('templateSlug');
    if (!slugField.value || document.getElementById('formAction').value === 'create') {
        slugField.value = this.value
            .toLowerCase()
            .normalize('NFD')
            .replace(/[\u0300-\u036f]/g, '')
            .replace(/[^a-z0-9]+/g, '-')
            .replace(/(^-|-$)/g, '');
    }
});

// Fechar modais com ESC
document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') {
        closeModal();
        closePreviewModal();
    }
});

// Fechar modal clicando fora
document.querySelectorAll('.modal-overlay').forEach(overlay => {
    overlay.addEventListener('click', function(e) {
        if (e.target === this) {
            closeModal();
            closePreviewModal();
        }
    });
});
</script>

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