<?php
/**
 * Editar Loja - Super Admin
 * Interface melhorada com UX aprimorada
 */
require_once __DIR__ . '/../../../includes/config.php';

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

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

$storeId = (int)($_GET['id'] ?? 0);

if ($storeId <= 0) {
    header('Location: /pages/superadmin/stores/index.php?error=invalid_id');
    exit;
}

// Buscar dados da loja
$stmt = $pdo->prepare("SELECT * FROM stores WHERE id = ? AND deleted_at IS NULL");
$stmt->execute([$storeId]);
$store = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$store) {
    header('Location: /pages/superadmin/stores/index.php?error=store_not_found');
    exit;
}

// Buscar plano da loja
$planName = 'Sem plano';
if (!empty($store['plan_id'])) {
    $stmt = $pdo->prepare("SELECT name FROM plans WHERE id = ?");
    $stmt->execute([$store['plan_id']]);
    $plan = $stmt->fetch(PDO::FETCH_ASSOC);
    if ($plan) {
        $planName = $plan['name'];
    }
}

// Buscar todos os planos disponiveis
$stmtPlans = $pdo->prepare("SELECT id, name, price_monthly FROM plans WHERE is_active = 1 ORDER BY price_monthly ASC");
$stmtPlans->execute();
$allPlans = $stmtPlans->fetchAll(PDO::FETCH_ASSOC);

$errors = [];
$success = false;

// Processar formulario
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'] ?? 'active';
    $isActive = isset($_POST['is_active']) ? 1 : 0;
    $planId = !empty($_POST['plan_id']) ? trim($_POST['plan_id']) : null;

    // Validacoes
    if (empty($name)) {
        $errors[] = "Nome da loja e obrigatorio";
    }

    if (empty($slug)) {
        $errors[] = "Slug e obrigatorio";
    } elseif (!preg_match('/^[a-z0-9-]+$/', $slug)) {
        $errors[] = "Slug deve conter apenas letras minusculas, numeros e hifens";
    }

    if (empty($whatsapp)) {
        $errors[] = "WhatsApp e obrigatorio";
    }

    // Verificar se slug ja existe em outra loja
    if (empty($errors)) {
        $stmt = $pdo->prepare("SELECT id FROM stores WHERE slug = ? AND id != ? AND deleted_at IS NULL");
        $stmt->execute([$slug, $storeId]);
        if ($stmt->fetch()) {
            $errors[] = "Slug ja esta em uso";
        }
    }

    // Verificar se subdomain ja existe em outra loja
    if ($domainType === 'subdomain' && !empty($subdomain)) {
        $stmt = $pdo->prepare("SELECT id FROM stores WHERE subdomain = ? AND id != ? AND deleted_at IS NULL");
        $stmt->execute([$subdomain, $storeId]);
        if ($stmt->fetch()) {
            $errors[] = "Subdominio ja esta em uso";
        }
    }

    if (empty($errors)) {
        try {
            $stmt = $pdo->prepare("
                UPDATE stores SET
                    name = ?,
                    email = ?,
                    whatsapp_number = ?,
                    slug = ?,
                    subdomain = ?,
                    custom_domain = ?,
                    domain_type = ?,
                    type = ?,
                    business_type = ?,
                    primary_color = ?,
                    status = ?,
                    is_active = ?,
                    plan_id = ?
                WHERE id = ?
            ");

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

            // Atualizar dados da loja no array
            $store['name'] = $name;
            $store['email'] = $email;
            $store['whatsapp_number'] = $whatsapp;
            $store['slug'] = $slug;
            $store['subdomain'] = $subdomain;
            $store['custom_domain'] = $customDomain;
            $store['domain_type'] = $domainType;
            $store['type'] = $type;
            $store['business_type'] = $businessType;
            $store['primary_color'] = $primaryColor;
            $store['status'] = $status;
            $store['is_active'] = $isActive;
            $store['plan_id'] = $planId;

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

$pageTitle = "Editar 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>
                            <iconify-icon icon="solar:pen-bold"></iconify-icon>
                            Editar Loja
                        </h2>
                        <p>Alterar informacoes de <?= htmlspecialchars($store['name']) ?></p>
                    </div>
                    <div class="action-buttons">
                        <a href="impersonate.php?store_id=<?= $storeId ?>" class="btn btn-outline">
                            <iconify-icon icon="solar:eye-bold"></iconify-icon>
                            Acessar Loja
                        </a>
                        <a href="/pages/superadmin/stores/index.php" class="btn btn-secondary">
                            <iconify-icon icon="solar:arrow-left-bold"></iconify-icon>
                            Voltar
                        </a>
                    </div>
                </div>

                <!-- Alertas -->
                <?php if (isset($_GET["success"]) && $_GET["success"] === "created"): ?>
                    <div class="alert alert-success">
                        <iconify-icon icon="solar:check-circle-bold"></iconify-icon>
                        <span>Loja criada com sucesso!</span>
                    </div>
                <?php endif; ?>

                <?php if ($success): ?>
                    <div class="alert alert-success">
                        <iconify-icon icon="solar:check-circle-bold"></iconify-icon>
                        <span>Loja atualizada com sucesso!</span>
                    </div>
                <?php endif; ?>

                <?php if (!empty($errors)): ?>
                    <div class="alert alert-error">
                        <iconify-icon icon="solar:danger-circle-bold"></iconify-icon>
                        <div>
                            <strong>Erros encontrados:</strong>
                            <ul style="margin: 0.5rem 0 0 1.5rem; padding: 0;">
                                <?php foreach ($errors as $error): ?>
                                    <li><?= htmlspecialchars($error) ?></li>
                                <?php endforeach; ?>
                            </ul>
                        </div>
                    </div>
                <?php endif; ?>

                <form method="POST">
                    <div class="panels-grid">
                        <!-- Coluna Esquerda -->
                        <div>
                            <!-- Informacoes Basicas -->
                            <div class="panel">
                                <div class="panel-header">
                                    <div class="panel-icon">
                                        <iconify-icon icon="solar:shop-bold"></iconify-icon>
                                    </div>
                                    <div>
                                        <h3>Informacoes Basicas</h3>
                                        <span class="panel-subtitle">Dados principais da loja</span>
                                    </div>
                                </div>

                                <div class="form-group">
                                    <label class="form-label">
                                        <iconify-icon icon="solar:shop-2-bold"></iconify-icon>
                                        Nome da Loja *
                                    </label>
                                    <input type="text" name="name" value="<?= htmlspecialchars($store['name']) ?>"
                                           class="form-input" placeholder="Ex: Minha Loja" required>
                                </div>

                                <div class="form-row">
                                    <div class="form-group">
                                        <label class="form-label">
                                            <iconify-icon icon="solar:letter-bold"></iconify-icon>
                                            Email
                                        </label>
                                        <input type="email" name="email" value="<?= htmlspecialchars($store['email'] ?? '') ?>"
                                               class="form-input" placeholder="contato@loja.com">
                                    </div>

                                    <div class="form-group">
                                        <label class="form-label">
                                            <iconify-icon icon="solar:phone-bold"></iconify-icon>
                                            WhatsApp *
                                        </label>
                                        <input type="text" name="whatsapp_number" value="<?= htmlspecialchars($store['whatsapp_number']) ?>"
                                               class="form-input" placeholder="5511999999999" required>
                                        <span class="form-hint">
                                            <iconify-icon icon="solar:info-circle-linear"></iconify-icon>
                                            Formato: 5511999999999
                                        </span>
                                    </div>
                                </div>

                                <div class="form-group">
                                    <label class="form-label">
                                        <iconify-icon icon="solar:link-bold"></iconify-icon>
                                        Slug *
                                    </label>
                                    <input type="text" name="slug" value="<?= htmlspecialchars($store['slug']) ?>"
                                           class="form-input" pattern="[a-z0-9-]+" placeholder="minha-loja" required>
                                    <span class="form-hint">
                                        <iconify-icon icon="solar:info-circle-linear"></iconify-icon>
                                        Apenas letras minusculas, numeros e hifens
                                    </span>
                                </div>
                            </div>

                            <!-- Tipo de Negocio -->
                            <div class="panel">
                                <div class="panel-header">
                                    <div class="panel-icon blue">
                                        <iconify-icon icon="solar:buildings-bold"></iconify-icon>
                                    </div>
                                    <div>
                                        <h3>Tipo de Negocio</h3>
                                        <span class="panel-subtitle">Categoria e modelo da loja</span>
                                    </div>
                                </div>

                                <div class="form-row">
                                    <div class="form-group">
                                        <label class="form-label">
                                            <iconify-icon icon="solar:tag-bold"></iconify-icon>
                                            Tipo da Loja
                                        </label>
                                        <select name="type" class="form-select">
                                            <option value="store" <?= $store['type'] === 'store' ? 'selected' : '' ?>>Loja</option>
                                            <option value="barbershop" <?= $store['type'] === 'barbershop' ? 'selected' : '' ?>>Barbearia</option>
                                        </select>
                                    </div>

                                    <div class="form-group">
                                        <label class="form-label">
                                            <iconify-icon icon="solar:chart-bold"></iconify-icon>
                                            Modelo de Negocio
                                        </label>
                                        <select name="business_type" class="form-select">
                                            <option value="service" <?= $store['business_type'] === 'service' ? 'selected' : '' ?>>Servico</option>
                                            <option value="retail" <?= $store['business_type'] === 'retail' ? 'selected' : '' ?>>Varejo</option>
                                        </select>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Coluna Direita -->
                        <div>
                            <!-- Configuracao de Dominio -->
                            <div class="panel">
                                <div class="panel-header">
                                    <div class="panel-icon green">
                                        <iconify-icon icon="solar:global-bold"></iconify-icon>
                                    </div>
                                    <div>
                                        <h3>Configuracao de Dominio</h3>
                                        <span class="panel-subtitle">URL de acesso a loja</span>
                                    </div>
                                </div>

                                <div class="form-group">
                                    <label class="form-label">
                                        <iconify-icon icon="solar:server-bold"></iconify-icon>
                                        Tipo de Dominio
                                    </label>
                                    <select name="domain_type" class="form-select" onchange="toggleDomainFields(this.value)">
                                        <option value="subdomain" <?= $store['domain_type'] === 'subdomain' ? 'selected' : '' ?>>Subdominio</option>
                                        <option value="custom" <?= $store['domain_type'] === 'custom' ? 'selected' : '' ?>>Dominio Personalizado</option>
                                    </select>
                                </div>

                                <div id="subdomain-field" class="form-group" style="<?= $store['domain_type'] === 'custom' ? 'display:none;' : '' ?>">
                                    <label class="form-label">
                                        <iconify-icon icon="solar:link-circle-bold"></iconify-icon>
                                        Subdominio
                                    </label>
                                    <div style="position: relative;">
                                        <input type="text" name="subdomain" value="<?= htmlspecialchars($store['subdomain'] ?? '') ?>"
                                               class="form-input" placeholder="minha-loja" style="padding-right: 120px;">
                                        <span style="position: absolute; right: 12px; top: 50%; transform: translateY(-50%); color: var(--text-muted); font-size: 0.85rem;">
                                            .duolead.com.br
                                        </span>
                                    </div>
                                </div>

                                <div id="custom-domain-field" class="form-group" style="<?= $store['domain_type'] === 'subdomain' ? 'display:none;' : '' ?>">
                                    <label class="form-label">
                                        <iconify-icon icon="solar:global-bold"></iconify-icon>
                                        Dominio Personalizado
                                    </label>
                                    <input type="text" name="custom_domain" value="<?= htmlspecialchars($store['custom_domain'] ?? '') ?>"
                                           class="form-input" placeholder="www.minhaloja.com.br">
                                </div>
                            </div>

                            <!-- Personalizacao -->
                            <div class="panel">
                                <div class="panel-header">
                                    <div class="panel-icon purple">
                                        <iconify-icon icon="solar:pallete-bold"></iconify-icon>
                                    </div>
                                    <div>
                                        <h3>Personalizacao</h3>
                                        <span class="panel-subtitle">Aparencia da loja</span>
                                    </div>
                                </div>

                                <div class="form-group">
                                    <label class="form-label">
                                        <iconify-icon icon="solar:pallete-2-bold"></iconify-icon>
                                        Cor Primaria
                                    </label>
                                    <div style="display: flex; gap: 1rem; align-items: center;">
                                        <input type="color" name="primary_color" value="<?= htmlspecialchars($store['primary_color']) ?>"
                                               style="width: 60px; height: 45px; border: none; border-radius: var(--radius-md); cursor: pointer;">
                                        <input type="text" value="<?= htmlspecialchars($store['primary_color']) ?>" 
                                               class="form-input" style="flex: 1;" readonly id="colorText"
                                               onclick="document.querySelector('input[name=primary_color]').click()">
                                    </div>
                                </div>
                            </div>

                            <!-- Status -->
                            <div class="panel">
                                <div class="panel-header">
                                    <div class="panel-icon orange">
                                        <iconify-icon icon="solar:settings-bold"></iconify-icon>
                                    </div>
                                    <div>
                                        <h3>Status e Plano</h3>
                                        <span class="panel-subtitle">Estado atual da loja</span>
                                    </div>
                                </div>

                                <div class="form-row">
                                    <div class="form-group">
                                        <label class="form-label">
                                            <iconify-icon icon="solar:crown-bold"></iconify-icon>
                                            Plano
                                        </label>
                                        <select name="plan_id" class="form-select">
                                            <option value="">Sem plano</option>
                                            <?php foreach ($allPlans as $p): ?>
                                                <option value="<?= $p['id'] ?>" <?= $store['plan_id'] == $p['id'] ? 'selected' : '' ?>>
                                                    <?= htmlspecialchars($p['name']) ?> - R$ <?= number_format($p['price_monthly'], 2, ',', '.') ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                    <div class="form-group">
                                        <label class="form-label">
                                            <iconify-icon icon="solar:calendar-bold"></iconify-icon>
                                            Criada em
                                        </label>
                                        <input type="text" class="form-input" value="<?= date('d/m/Y', strtotime($store['created_at'])) ?>" readonly>
                                    </div>
                                </div>

                                <div class="form-group">
                                    <label class="form-label">
                                        <iconify-icon icon="solar:flag-bold"></iconify-icon>
                                        Status da Conta
                                    </label>
                                    <select name="status" class="form-select">
                                        <option value="trial" <?= $store['status'] === 'trial' ? 'selected' : '' ?>>Periodo de Teste</option>
                                        <option value="active" <?= $store['status'] === 'active' ? 'selected' : '' ?>>Ativo</option>
                                        <option value="past_due" <?= $store['status'] === 'past_due' ? 'selected' : '' ?>>Pagamento Atrasado</option>
                                        <option value="cancelled" <?= $store['status'] === 'cancelled' ? 'selected' : '' ?>>Cancelado</option>
                                        <option value="suspended" <?= $store['status'] === 'suspended' ? 'selected' : '' ?>>Suspenso</option>
                                    </select>
                                </div>

                                <div class="form-group">
                                    <div style="display: flex; align-items: center; justify-content: space-between; padding: 1rem; background: var(--bg-input); border-radius: var(--radius-md);">
                                        <div>
                                            <strong style="color: var(--text-primary);">Loja Ativa</strong>
                                            <p style="margin: 0.25rem 0 0 0; font-size: 0.8rem; color: var(--text-muted);">
                                                Desative para bloquear o acesso
                                            </p>
                                        </div>
                                        <label class="toggle-switch">
                                            <input type="checkbox" name="is_active" value="1" <?= $store['is_active'] ? 'checked' : '' ?>>
                                            <span class="toggle-slider"></span>
                                        </label>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Botoes de Acao -->
                    <div class="panel" style="display: flex; justify-content: space-between; align-items: center;">
                        <a href="/pages/superadmin/stores/index.php" class="btn btn-secondary">
                            <iconify-icon icon="solar:arrow-left-bold"></iconify-icon>
                            Cancelar
                        </a>
                        <button type="submit" class="btn btn-primary btn-lg">
                            <iconify-icon icon="solar:check-circle-bold"></iconify-icon>
                            Salvar Alteracoes
                        </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';
            }
        }

        // Atualizar campo de texto quando mudar cor
        document.querySelector('input[name="primary_color"]').addEventListener('input', function() {
            document.getElementById('colorText').value = this.value;
        });
    </script>
</body>
</html>
