<?php
/**
 * Super Admin - Gerenciador de Templates de Páginas de Vendas
 * Permite trocar templates e personalizar para cada loja
 */
require_once __DIR__ . '/../../../includes/config.php';

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

$superAdmin = getSuperAdmin();
$pdo = getDB();

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

// Processar ações
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    if ($action === 'assign_template') {
        $storeId = (int)$_POST['store_id'];
        $templateName = $_POST['template_name'] ?? 'modern';
        $primaryColor = $_POST['primary_color'] ?? '#CCA43B';
        $secondaryColor = $_POST['secondary_color'] ?? '#1A1A1A';
        
        try {
            // Verificar se já existe configuração para esta loja
            $stmt = $pdo->prepare("SELECT id FROM sales_page_templates WHERE store_id = ?");
            $stmt->execute([$storeId]);
            $existing = $stmt->fetch();
            
            if ($existing) {
                // Atualizar
                $stmt = $pdo->prepare("
                    UPDATE sales_page_templates 
                    SET template_name = ?, primary_color = ?, secondary_color = ?, updated_at = NOW()
                    WHERE store_id = ?
                ");
                $stmt->execute([$templateName, $primaryColor, $secondaryColor, $storeId]);
                $success = 'Template atualizado com sucesso!';
            } else {
                // Inserir novo
                $stmt = $pdo->prepare("
                    INSERT INTO sales_page_templates (store_id, template_name, primary_color, secondary_color)
                    VALUES (?, ?, ?, ?)
                ");
                $stmt->execute([$storeId, $templateName, $primaryColor, $secondaryColor]);
                $success = 'Template atribuído com sucesso!';
            }
        } catch (PDOException $e) {
            $error = 'Erro ao salvar template: ' . $e->getMessage();
        }
    }
    
    if ($action === 'reset_template') {
        $storeId = (int)$_POST['store_id'];
        try {
            $stmt = $pdo->prepare("DELETE FROM sales_page_templates WHERE store_id = ?");
            $stmt->execute([$storeId]);
            $success = 'Template resetado para padrão!';
        } catch (PDOException $e) {
            $error = 'Erro ao resetar template: ' . $e->getMessage();
        }
    }
}

// Buscar todas as lojas com seus templates
$stmt = $pdo->query("
    SELECT 
        s.id,
        s.name,
        s.slug,
        s.status,
        s.business_type,
        spt.template_name,
        spt.primary_color,
        spt.secondary_color,
        spt.updated_at as template_updated_at
    FROM stores s
    LEFT JOIN sales_page_templates spt ON s.id = spt.store_id
    WHERE s.deleted_at IS NULL
    ORDER BY s.name ASC
");
$stores = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Templates disponíveis
$availableTemplates = [
    'modern' => [
        'name' => 'Modern',
        'description' => 'Design moderno e minimalista com animações suaves',
        'preview' => '/templates/sales/modern/preview.jpg',
        'icon' => 'solar:widget-4-bold'
    ],
    'classic' => [
        'name' => 'Classic',
        'description' => 'Layout clássico e profissional com seções bem definidas',
        'preview' => '/templates/sales/classic/preview.jpg',
        'icon' => 'solar:document-text-bold'
    ],
    'minimal' => [
        'name' => 'Minimal',
        'description' => 'Ultra minimalista focado em conversão',
        'preview' => '/templates/sales/minimal/preview.jpg',
        'icon' => 'solar:layers-minimalistic-bold'
    ],
    'elegant' => [
        'name' => 'Elegant',
        'description' => 'Elegante e sofisticado para negócios premium',
        'preview' => '/templates/sales/elegant/preview.jpg',
        'icon' => 'solar:star-bold'
    ]
];

$pageTitle = 'Gerenciador de Templates';
$currentPage = 'templates';

include __DIR__ . '/../includes/header.php';
?>
    <div class="app-container">
        <?php include __DIR__ . '/../includes/sidebar.php'; ?>

        <main class="main-content">
            <?php include __DIR__ . '/../includes/topbar.php'; ?>

            <div class="content-area">
                <!-- Success/Error Messages -->
                <?php if ($success): ?>
                    <div class="alert alert-success">
                        <iconify-icon icon="solar:check-circle-bold"></iconify-icon>
                        <?= $success ?>
                    </div>
                <?php endif; ?>
                
                <?php if ($error): ?>
                    <div class="alert alert-danger">
                        <iconify-icon icon="solar:danger-circle-bold"></iconify-icon>
                        <?= $error ?>
                    </div>
                <?php endif; ?>

                <!-- Page Header -->
                <div class="page-header">
                    <div>
                        <h2>Gerenciador de Templates</h2>
                        <p>Configure templates de páginas de vendas para cada loja</p>
                    </div>
                </div>

                <!-- Templates Disponíveis -->
                <div class="panel mb-6">
                    <h3 style="margin-bottom: 0.5rem; font-size: 1.25rem; font-weight: 600;">Templates Disponíveis</h3>
                    <p class="text-muted" style="margin-bottom: 1.5rem;">Escolha entre diferentes designs para a página de vendas</p>
                    
                    <div class="templates-grid">
                        <?php foreach ($availableTemplates as $key => $template): ?>
                            <div class="template-card">
                                <div class="template-preview">
                                    <iconify-icon icon="<?= $template['icon'] ?>" width="40"></iconify-icon>
                                </div>
                                <h4><?= $template['name'] ?></h4>
                                <p><?= $template['description'] ?></p>
                                <span class="badge badge-primary"><?= $key ?></span>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>

                <!-- Lojas e Templates -->
                <div class="panel">
                    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 1.5rem;">
                        <div>
                            <h3 style="margin: 0 0 0.25rem 0; font-size: 1.25rem; font-weight: 600;">Configuração por Loja</h3>
                            <p class="text-muted" style="margin: 0; font-size: 0.875rem;"><?= count($stores) ?> lojas cadastradas</p>
                        </div>
                    </div>
                    
                    <div class="table-responsive">
                        <table class="table">
                            <thead>
                                <tr>
                                    <th>Loja</th>
                                    <th>Tipo</th>
                                    <th>Status</th>
                                    <th>Template Atual</th>
                                    <th>Cores</th>
                                    <th>Última Atualização</th>
                                    <th style="text-align: center;">Ações</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($stores as $store): ?>
                                    <tr>
                                        <td>
                                            <div style="font-weight: 500; color: var(--text-primary);"><?= htmlspecialchars($store['name']) ?></div>
                                            <div class="text-muted" style="font-size: 0.8125rem; margin-top: 0.125rem;"><?= htmlspecialchars($store['slug']) ?></div>
                                        </td>
                                        <td>
                                            <span class="badge <?= $store['business_type'] === 'service' ? 'badge-info' : 'badge-warning' ?>">
                                                <?= $store['business_type'] === 'service' ? 'Serviço' : 'Varejo' ?>
                                            </span>
                                        </td>
                                        <td>
                                            <span class="badge badge-<?= $store['status'] === 'active' ? 'success' : ($store['status'] === 'trial' ? 'info' : 'secondary') ?>">
                                                <?= ucfirst($store['status']) ?>
                                            </span>
                                        </td>
                                        <td>
                                            <?php if ($store['template_name']): ?>
                                                <span class="badge badge-primary">
                                                    <?= $availableTemplates[$store['template_name']]['name'] ?? $store['template_name'] ?>
                                                </span>
                                            <?php else: ?>
                                                <span class="text-muted" style="font-size: 0.875rem;">Padrão (Modern)</span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <?php if ($store['primary_color']): ?>
                                                <div style="display: flex; gap: 0.5rem; align-items: center;">
                                                    <div class="color-preview" style="background: <?= $store['primary_color'] ?>"></div>
                                                    <div class="color-preview" style="background: <?= $store['secondary_color'] ?>"></div>
                                                </div>
                                            <?php else: ?>
                                                <span class="text-muted" style="font-size: 0.875rem;">-</span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <span style="font-size: 0.875rem;">
                                                <?= $store['template_updated_at'] ? date('d/m/Y H:i', strtotime($store['template_updated_at'])) : '-' ?>
                                            </span>
                                        </td>
                                        <td style="text-align: center;">
                                            <div class="btn-group">
                                                <button onclick="openTemplateModal(<?= $store['id'] ?>, '<?= addslashes(htmlspecialchars($store['name'])) ?>', '<?= $store['template_name'] ?? 'modern' ?>', '<?= $store['primary_color'] ?? '#CCA43B' ?>', '<?= $store['secondary_color'] ?? '#1A1A1A' ?>')" 
                                                        class="btn btn-sm btn-outline" title="Editar template">
                                                    <iconify-icon icon="solar:pen-bold"></iconify-icon>
                                                </button>
                                                <?php if ($store['template_name']): ?>
                                                    <form method="POST" style="display: inline;" onsubmit="return confirm('Resetar template para padrão?')">
                                                        <input type="hidden" name="action" value="reset_template">
                                                        <input type="hidden" name="store_id" value="<?= $store['id'] ?>">
                                                        <button type="submit" class="btn btn-sm btn-danger" title="Resetar para padrão">
                                                            <iconify-icon icon="solar:restart-bold"></iconify-icon>
                                                        </button>
                                                    </form>
                                                <?php endif; ?>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </main>
    </div>

    <!-- Modal de Edição -->
    <div id="templateModal" class="modal" style="display: none;">
        <div class="modal-content" style="max-width: 600px;">
            <div class="modal-header">
                <h3>Configurar Template</h3>
                <button onclick="closeTemplateModal()" class="btn-close">
                    <iconify-icon icon="solar:close-circle-bold"></iconify-icon>
                </button>
            </div>
            <form method="POST">
                <input type="hidden" name="action" value="assign_template">
                <input type="hidden" name="store_id" id="modalStoreId">
                
                <div class="modal-body">
                    <div class="form-group">
                        <label class="form-label">Loja</label>
                        <input type="text" id="modalStoreName" class="form-input" disabled>
                    </div>

                    <div class="form-group">
                        <label class="form-label">Escolher Template</label>
                        <select name="template_name" id="modalTemplateName" class="form-select" required>
                            <?php foreach ($availableTemplates as $key => $template): ?>
                                <option value="<?= $key ?>"><?= $template['name'] ?> - <?= $template['description'] ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="grid grid-cols-2 gap-4">
                        <div class="form-group">
                            <label class="form-label">Cor Primária</label>
                            <input type="color" name="primary_color" id="modalPrimaryColor" class="form-input" style="height: 50px;">
                        </div>
                        <div class="form-group">
                            <label class="form-label">Cor Secundária</label>
                            <input type="color" name="secondary_color" id="modalSecondaryColor" class="form-input" style="height: 50px;">
                        </div>
                    </div>
                </div>

                <div class="modal-footer">
                    <button type="button" onclick="closeTemplateModal()" class="btn btn-outline">Cancelar</button>
                    <button type="submit" class="btn btn-primary">Salvar Template</button>
                </div>
            </form>
        </div>
    </div>

    <style>
        .templates-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 1.5rem;
            margin-top: 1.5rem;
        }

        .template-card {
            background: var(--bg-panel);
            border: 2px solid var(--border-light);
            border-radius: var(--radius-lg);
            padding: 1.5rem;
            text-align: center;
            transition: all 0.3s ease;
            cursor: pointer;
            position: relative;
            overflow: hidden;
        }

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

        .template-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 4px;
            background: linear-gradient(90deg, var(--gold), #FFD700);
            opacity: 0;
            transition: opacity 0.3s ease;
        }

        .template-card:hover::before {
            opacity: 1;
        }

        .template-preview {
            width: 80px;
            height: 80px;
            margin: 0 auto 1rem;
            border-radius: var(--radius-lg);
            background: linear-gradient(135deg, var(--gold), #FFD700);
            display: flex;
            align-items: center;
            justify-content: center;
            color: #1A1A1A;
            box-shadow: var(--shadow-md);
        }

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

        .template-card p {
            font-size: 0.875rem;
            color: var(--text-muted);
            margin-bottom: 1rem;
            line-height: 1.5;
        }

        .color-preview {
            width: 28px;
            height: 28px;
            border-radius: 6px;
            border: 2px solid var(--border-light);
            box-shadow: var(--shadow-sm);
        }

        .btn-group {
            display: inline-flex;
            gap: 0.5rem;
        }

        /* Modal Styles */
        .modal {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.75);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 9999;
            padding: 1rem;
            backdrop-filter: blur(4px);
        }

        .modal-content {
            background: var(--bg-panel);
            border-radius: var(--radius-lg);
            width: 100%;
            max-width: 600px;
            max-height: 90vh;
            overflow-y: auto;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.4);
            animation: modalSlideIn 0.3s ease-out;
        }

        @keyframes modalSlideIn {
            from {
                opacity: 0;
                transform: translateY(-20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .modal-header {
            padding: 1.5rem;
            border-bottom: 1px solid var(--border-light);
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .modal-header h3 {
            margin: 0;
            font-size: 1.25rem;
            font-weight: 600;
            color: var(--text-primary);
        }

        .modal-body {
            padding: 1.5rem;
        }

        .modal-footer {
            padding: 1.5rem;
            border-top: 1px solid var(--border-light);
            display: flex;
            gap: 0.75rem;
            justify-content: flex-end;
        }

        .btn-close {
            background: transparent;
            border: none;
            color: var(--text-muted);
            cursor: pointer;
            font-size: 1.5rem;
            padding: 0.25rem;
            border-radius: var(--radius-md);
            transition: all 0.2s ease;
        }

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

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

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

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

        .form-input:focus, .form-select:focus {
            outline: none;
            border-color: var(--gold);
            box-shadow: 0 0 0 3px rgba(204, 164, 59, 0.1);
        }

        .form-input:disabled {
            opacity: 0.6;
            cursor: not-allowed;
        }

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

        .table {
            width: 100%;
            border-collapse: collapse;
        }

        .table th,
        .table td {
            padding: 1rem;
            text-align: left;
            border-bottom: 1px solid var(--border-light);
        }

        .table th {
            font-weight: 600;
            color: var(--text-muted);
            font-size: 0.8125rem;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .table tbody tr {
            transition: background-color 0.2s ease;
        }

        .table tbody tr:hover {
            background: var(--bg-input);
        }

        .badge {
            display: inline-flex;
            align-items: center;
            padding: 0.25rem 0.75rem;
            border-radius: 12px;
            font-size: 0.75rem;
            font-weight: 600;
            white-space: nowrap;
        }

        .badge-primary {
            background: rgba(204, 164, 59, 0.15);
            color: var(--gold);
        }

        .badge-success {
            background: rgba(34, 197, 94, 0.15);
            color: var(--success);
        }

        .badge-info {
            background: rgba(59, 130, 246, 0.15);
            color: var(--info);
        }

        .badge-warning {
            background: rgba(245, 158, 11, 0.15);
            color: var(--warning);
        }

        .badge-secondary {
            background: var(--bg-input);
            color: var(--text-muted);
        }

        .alert {
            padding: 1rem 1.25rem;
            border-radius: var(--radius-md);
            margin-bottom: 1.5rem;
            display: flex;
            align-items: center;
            gap: 0.75rem;
            font-size: 0.9375rem;
        }

        .alert-success {
            background: rgba(34, 197, 94, 0.1);
            color: var(--success);
            border: 1px solid rgba(34, 197, 94, 0.2);
        }

        .alert-danger {
            background: rgba(239, 68, 68, 0.1);
            color: var(--danger);
            border: 1px solid rgba(239, 68, 68, 0.2);
        }

        .mb-6 {
            margin-bottom: 2.5rem;
        }

        input[type="color"] {
            cursor: pointer;
        }

        @media (max-width: 768px) {
            .templates-grid {
                grid-template-columns: 1fr;
            }

            .grid-cols-2 {
                grid-template-columns: 1fr;
            }

            .table-responsive {
                overflow-x: auto;
            }

            .modal-content {
                max-width: 100%;
            }
        }
    </style>

    <script>
        function openTemplateModal(storeId, storeName, templateName, primaryColor, secondaryColor) {
            document.getElementById('modalStoreId').value = storeId;
            document.getElementById('modalStoreName').value = storeName;
            document.getElementById('modalTemplateName').value = templateName;
            document.getElementById('modalPrimaryColor').value = primaryColor;
            document.getElementById('modalSecondaryColor').value = secondaryColor;
            document.getElementById('templateModal').style.display = 'flex';
        }

        function closeTemplateModal() {
            document.getElementById('templateModal').style.display = 'none';
        }

        // Fechar modal ao clicar fora
        document.getElementById('templateModal')?.addEventListener('click', function(e) {
            if (e.target === this) {
                closeTemplateModal();
            }
        });
    </script>

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