<?php
/**
 * Criar Nova Loja - Super Admin
 */
require_once __DIR__ . '/../../../includes/config.php';

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

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

$errors = [];
$success = false;

// Processar formulário
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $whatsapp = trim($_POST['whatsapp_number'] ?? '');
    $slug = trim($_POST['slug'] ?? '');
    $subdomain = trim($_POST['subdomain'] ?? '');
    $customDomain = trim($_POST['custom_domain'] ?? '');
    $domainType = $_POST['domain_type'] ?? 'subdomain';
    $type = $_POST['type'] ?? 'store';
    $businessType = $_POST['business_type'] ?? 'service';
    $primaryColor = $_POST['primary_color'] ?? '#CCA43B';
    $status = $_POST['status'] ?? 'trial';
    $isActive = isset($_POST['is_active']) ? 1 : 0;

    // Validações
    if (empty($name)) {
        $errors[] = "Nome da loja é obrigatório";
    }

    if (empty($slug)) {
        $errors[] = "Slug é obrigatório";
    } elseif (!preg_match('/^[a-z0-9-]+$/', $slug)) {
        $errors[] = "Slug deve conter apenas letras minúsculas, números e hífens";
    }

    if (empty($whatsapp)) {
        $errors[] = "WhatsApp é obrigatório";
    }

    // Verificar se slug já existe
    if (empty($errors)) {
        $stmt = $pdo->prepare("SELECT id FROM stores WHERE slug = ? AND deleted_at IS NULL");
        $stmt->execute([$slug]);
        if ($stmt->fetch()) {
            $errors[] = "Slug já está em uso";
        }
    }

    // Verificar se subdomain já existe
    if ($domainType === 'subdomain' && !empty($subdomain)) {
        $stmt = $pdo->prepare("SELECT id FROM stores WHERE subdomain = ? AND deleted_at IS NULL");
        $stmt->execute([$subdomain]);
        if ($stmt->fetch()) {
            $errors[] = "Subdomínio já está em uso";
        }
    }

    if (empty($errors)) {
        try {
            $stmt = $pdo->prepare("
                INSERT INTO stores (
                    name, email, whatsapp_number, slug, subdomain, 
                    custom_domain, domain_type, type, business_type, 
                    primary_color, status, is_active, created_at
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())
            ");

            $stmt->execute([
                $name,
                $email,
                $whatsapp,
                $slug,
                $subdomain,
                $customDomain,
                $domainType,
                $type,
                $businessType,
                $primaryColor,
                $status,
                $isActive
            ]);

            $newStoreId = $pdo->lastInsertId();

            // Redirecionar para edição da nova loja
            header("Location: /pages/superadmin/stores/edit.php?id={$newStoreId}&success=created");
            exit;

        } catch (PDOException $e) {
            $errors[] = "Erro ao criar loja: " . $e->getMessage();
        }
    }
}

$pageTitle = "Criar Nova Loja";
$currentPage = 'stores';

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">
                <!-- Page Header -->
                <div class="page-header">
                    <div>
                        <h2>Criar Nova Loja</h2>
                        <p>Cadastrar uma nova loja no sistema</p>
                    </div>
                    <a href="/pages/superadmin/stores/index.php" class="btn btn-secondary">
                        <iconify-icon icon="solar:arrow-left-bold"></iconify-icon>
                        Voltar
                    </a>
                </div>

                <?php if (!empty($errors)): ?>
                    <div style="background: rgba(239,68,68,0.1); border: 1px solid rgba(239,68,68,0.3); color: var(--danger); padding: 1rem; border-radius: var(--radius-md); margin-bottom: 1.5rem;">
                        <div style="display: flex; align-items: center; gap: 0.75rem; margin-bottom: 0.5rem;">
                            <iconify-icon icon="solar:danger-circle-bold" width="24"></iconify-icon>
                            <strong>Erros encontrados:</strong>
                        </div>
                        <ul style="margin: 0; padding-left: 2rem;">
                            <?php foreach ($errors as $error): ?>
                                <li><?= htmlspecialchars($error) ?></li>
                            <?php endforeach; ?>
                        </ul>
                    </div>
                <?php endif; ?>

                <!-- Formulário -->
                <form method="POST" class="panel">
                    <div class="grid-2">
                        <!-- Informações Básicas -->
                        <div style="grid-column: 1 / -1;">
                            <h3 style="margin: 0 0 1.5rem 0;">Informações Básicas</h3>
                        </div>

                        <div>
                            <label class="form-label">Nome da Loja *</label>
                            <input type="text" name="name" value="<?= htmlspecialchars($_POST['name'] ?? '') ?>" 
                                   class="form-input" required>
                        </div>

                        <div>
                            <label class="form-label">Email</label>
                            <input type="email" name="email" value="<?= htmlspecialchars($_POST['email'] ?? '') ?>" 
                                   class="form-input">
                        </div>

                        <div>
                            <label class="form-label">WhatsApp *</label>
                            <input type="text" name="whatsapp_number" value="<?= htmlspecialchars($_POST['whatsapp_number'] ?? '') ?>" 
                                   class="form-input" placeholder="5511999999999" required>
                            <small class="text-muted">Formato: 5511999999999</small>
                        </div>

                        <div>
                            <label class="form-label">Slug *</label>
                            <input type="text" name="slug" value="<?= htmlspecialchars($_POST['slug'] ?? '') ?>" 
                                   class="form-input" pattern="[a-z0-9-]+" required>
                            <small class="text-muted">Apenas letras minúsculas, números e hífens</small>
                        </div>

                        <!-- Tipo e Negócio -->
                        <div style="grid-column: 1 / -1;">
                            <h3 style="margin: 2rem 0 1.5rem 0;">Tipo de Negócio</h3>
                        </div>

                        <div>
                            <label class="form-label">Tipo da Loja</label>
                            <select name="type" class="form-select">
                                <option value="store" <?= ($_POST['type'] ?? 'store') === 'store' ? 'selected' : '' ?>>Loja</option>
                                <option value="barbershop" <?= ($_POST['type'] ?? '') === 'barbershop' ? 'selected' : '' ?>>Barbearia</option>
                            </select>
                        </div>

                        <div>
                            <label class="form-label">Modelo de Negócio</label>
                            <select name="business_type" class="form-select">
                                <option value="service" <?= ($_POST['business_type'] ?? 'service') === 'service' ? 'selected' : '' ?>>Serviço</option>
                                <option value="retail" <?= ($_POST['business_type'] ?? '') === 'retail' ? 'selected' : '' ?>>Varejo</option>
                            </select>
                        </div>

                        <!-- Domínio -->
                        <div style="grid-column: 1 / -1;">
                            <h3 style="margin: 2rem 0 1.5rem 0;">Configuração de Domínio</h3>
                        </div>

                        <div>
                            <label class="form-label">Tipo de Domínio</label>
                            <select name="domain_type" class="form-select" onchange="toggleDomainFields(this.value)">
                                <option value="subdomain" <?= ($_POST['domain_type'] ?? 'subdomain') === 'subdomain' ? 'selected' : '' ?>>Subdomínio</option>
                                <option value="custom" <?= ($_POST['domain_type'] ?? '') === 'custom' ? 'selected' : '' ?>>Domínio Personalizado</option>
                            </select>
                        </div>

                        <div id="subdomain-field">
                            <label class="form-label">Subdomínio</label>
                            <div style="position: relative;">
                                <input type="text" name="subdomain" value="<?= htmlspecialchars($_POST['subdomain'] ?? '') ?>" 
                                       class="form-input" placeholder="minha-loja">
                                <span style="position: absolute; right: 12px; top: 50%; transform: translateY(-50%); color: var(--text-muted);">
                                    .duolead.com.br
                                </span>
                            </div>
                        </div>

                        <div id="custom-domain-field" style="grid-column: 1 / -1; display: none;">
                            <label class="form-label">Domínio Personalizado</label>
                            <input type="text" name="custom_domain" value="<?= htmlspecialchars($_POST['custom_domain'] ?? '') ?>" 
                                   class="form-input" placeholder="www.minhaloja.com.br">
                        </div>

                        <!-- Personalização -->
                        <div style="grid-column: 1 / -1;">
                            <h3 style="margin: 2rem 0 1.5rem 0;">Personalização</h3>
                        </div>

                        <div>
                            <label class="form-label">Cor Primária</label>
                            <input type="color" name="primary_color" value="<?= htmlspecialchars($_POST['primary_color'] ?? '#CCA43B') ?>" 
                                   class="form-input" style="height: 50px;">
                        </div>

                        <!-- Status -->
                        <div style="grid-column: 1 / -1;">
                            <h3 style="margin: 2rem 0 1.5rem 0;">Status Inicial</h3>
                        </div>

                        <div>
                            <label class="form-label">Status da Conta</label>
                            <select name="status" class="form-select">
                                <option value="trial" <?= ($_POST['status'] ?? 'trial') === 'trial' ? 'selected' : '' ?>>Período de Teste</option>
                                <option value="active" <?= ($_POST['status'] ?? '') === 'active' ? 'selected' : '' ?>>Ativo</option>
                                <option value="past_due" <?= ($_POST['status'] ?? '') === 'past_due' ? 'selected' : '' ?>>Pagamento Atrasado</option>
                                <option value="cancelled" <?= ($_POST['status'] ?? '') === 'cancelled' ? 'selected' : '' ?>>Cancelado</option>
                                <option value="suspended" <?= ($_POST['status'] ?? '') === 'suspended' ? 'selected' : '' ?>>Suspenso</option>
                            </select>
                        </div>

                        <div>
                            <label class="flex items-center gap-2" style="cursor: pointer;">
                                <input type="checkbox" name="is_active" value="1" 
                                       <?= isset($_POST['is_active']) || !isset($_POST['name']) ? 'checked' : '' ?>
                                       style="width: 20px; height: 20px;">
                                <span>Loja Ativa</span>
                            </label>
                            <small class="text-muted">Marque para ativar a loja imediatamente</small>
                        </div>
                    </div>

                    <div style="margin-top: 2rem; padding-top: 1.5rem; border-top: 1px solid var(--border-light); display: flex; gap: 1rem; justify-content: flex-end;">
                        <a href="/pages/superadmin/stores/index.php" class="btn btn-secondary">
                            Cancelar
                        </a>
                        <button type="submit" class="btn btn-primary">
                            <iconify-icon icon="solar:add-circle-bold"></iconify-icon>
                            Criar Loja
                        </button>
                    </div>
                </form>
            </div>
        </main>
    </div>

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

    <script>
        function toggleDomainFields(type) {
            const subdomainField = document.getElementById('subdomain-field');
            const customDomainField = document.getElementById('custom-domain-field');
            
            if (type === 'subdomain') {
                subdomainField.style.display = 'block';
                customDomainField.style.display = 'none';
            } else {
                subdomainField.style.display = 'none';
                customDomainField.style.display = 'block';
            }
        }

        // Auto-gerar slug a partir do nome
        document.querySelector('input[name="name"]').addEventListener('input', function(e) {
            const slugField = document.querySelector('input[name="slug"]');
            if (!slugField.value || slugField.dataset.manual !== 'true') {
                const slug = e.target.value
                    .toLowerCase()
                    .normalize('NFD')
                    .replace(/[\u0300-\u036f]/g, '')
                    .replace(/[^a-z0-9]+/g, '-')
                    .replace(/^-+|-+$/g, '');
                slugField.value = slug;
            }
        });

        document.querySelector('input[name="slug"]').addEventListener('input', function() {
            this.dataset.manual = 'true';
        });

        // Auto-gerar subdomínio a partir do slug
        document.querySelector('input[name="slug"]').addEventListener('input', function(e) {
            const subdomainField = document.querySelector('input[name="subdomain"]');
            const domainType = document.querySelector('select[name="domain_type"]').value;
            if (domainType === 'subdomain' && (!subdomainField.value || subdomainField.dataset.manual !== 'true')) {
                subdomainField.value = e.target.value;
            }
        });

        document.querySelector('input[name="subdomain"]').addEventListener('input', function() {
            this.dataset.manual = 'true';
        });
    </script>
</body>
</html>
