<?php
require __DIR__ . '/../../_layout.php';
?>

<div class="container">
    <h1>Templates do E-commerce</h1>

    <div id="templates-grid" class="card" style="margin-top: 2rem;">
        <p>Carregando templates...</p>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', async () => {
    const token = localStorage.getItem('auth_token') || getCookie('auth_token');
    const tenantId = getCookie('tenant_id') || 'default';
    
    try {
        const res = await fetch('/api/ecommerce/templates', {
            headers: {
                'Authorization': `Bearer ${token}`,
                'X-Tenant-Id': tenantId
            }
        });
        
        if (res.ok) {
            const { data } = await res.json();
            const grid = document.getElementById('templates-grid');
            
            if (data.length === 0) {
                grid.innerHTML = '<p>Nenhum template disponível.</p>';
                return;
            }
            
            grid.innerHTML = `
                <div style="display: grid; grid-template-columns: repeat(auto-fill, minmax(250px, 1fr)); gap: 1.5rem;">
                    ${data.map(template => `
                        <div class="template-card" style="border: 2px solid #e5e7eb; border-radius: 8px; padding: 1rem; cursor: pointer; transition: all 0.3s;" 
                             onclick="selectTemplate('${template.code}')">
                            ${template.preview_image ? `<img src="${template.preview_image}" style="width: 100%; height: 150px; object-fit: cover; border-radius: 4px; margin-bottom: 0.5rem;">` : ''}
                            <h3>${template.name}</h3>
                            <p style="color: #6b7280; font-size: 0.9rem;">${template.description || ''}</p>
                            <small style="color: #9ca3af;">Categoria: ${template.category || 'geral'}</small>
                        </div>
                    `).join('')}
                </div>
            `;
        }
    } catch (error) {
        console.error('Erro ao carregar templates:', error);
        document.getElementById('templates-grid').innerHTML = '<p style="color: #dc3545;">Erro ao carregar templates.</p>';
    }
});

async function selectTemplate(templateCode) {
    if (!confirm(`Deseja aplicar o template "${templateCode}"?`)) return;
    
    const token = localStorage.getItem('auth_token') || getCookie('auth_token');
    const tenantId = getCookie('tenant_id') || 'default';
    
    try {
        const res = await fetch('/api/ecommerce/template', {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${token}`,
                'X-Tenant-Id': tenantId
            },
            body: JSON.stringify({ template_id: templateCode })
        });
        
        if (res.ok) {
            alert('Template aplicado com sucesso!');
        } else {
            const error = await res.json();
            alert('Erro: ' + (error.error?.message || 'Erro ao aplicar template'));
        }
    } catch (error) {
        console.error('Erro ao aplicar template:', error);
        alert('Erro ao aplicar template');
    }
}

function getCookie(name) {
    const value = `; ${document.cookie}`;
    const parts = value.split(`; ${name}=`);
    if (parts.length === 2) return parts.pop().split(';').shift();
}
</script>

