<?php
require_once 'includes/verificar_permissao.php';
verificarPermissao(__FILE__);
?>
<?php
require_once 'includes/config.php';
require_once 'includes/auth.php';

$pageTitle = "Configurações";
include 'includes/header.php';
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Configurações - <?php echo htmlspecialchars($config_empresa['nome'] ?? 'Minha Loja'); ?></title>
    <link rel="icon" type="image/png" href="favicon.png">
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Bootstrap Icons -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.8.1/font/bootstrap-icons.css" rel="stylesheet">
    <!-- Google Fonts - Poppins -->
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <!-- Custom CSS -->
    <link rel="stylesheet" href="assets/css/theme.css?v=<?php echo time(); ?>">
    <link rel="stylesheet" href="assets/css/style.css?v=<?php echo time(); ?>">
    <link rel="stylesheet" href="assets/css/configuracoes.css?v=<?php echo time(); ?>">
    
    <style>
        /* Estilo para o switcher */
        .form-check-input:checked {
            background-color: #198754 !important; /* Verde quando ativo */
            border-color: #198754 !important;
        }
        
        .form-check-input:not(:checked) {
            background-color: #dc3545 !important; /* Vermelho quando inativo */
            border-color: #dc3545 !important;
        }
        
        /* Remove a cor cinza do fundo quando inativo */
        .form-switch .form-check-input {
            background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='-4 -4 8 8'%3e%3ccircle r='3' fill='%23fff'/%3e%3c/svg%3e") !important;
        }
    </style>
</head>
<body>
    <div class="wrapper config-page">
        <!-- Sidebar -->
    <?php require_once 'includes/sidebar.php'; ?>

        <!-- Page Content -->
        <div id="content">
            <!-- Navbar -->
            <nav class="navbar navbar-expand-lg bg-white">
                <div class="container-fluid">
                    <h2 class="navbar-title">Configurações</h2>
                    <div class="ms-auto">
                </div>
            </nav>

            <!-- Main Content -->
            <div class="container-fluid content-area">
                <!-- Tabs -->
                <ul class="nav nav-tabs" id="configTabs" role="tablist">
                    <li class="nav-item" role="presentation">
                        <button class="nav-link active" id="empresa-tab" data-bs-toggle="tab" data-bs-target="#empresa" type="button" role="tab">
                            <i class="bi bi-building"></i> Empresa
                        </button>
                    </li>
                    <li class="nav-item" role="presentation">
                        <button class="nav-link" id="redes-sociais-tab" data-bs-toggle="tab" data-bs-target="#redes-sociais" type="button" role="tab">
                            <i class="bi bi-share"></i> Redes Sociais
                        </button>
                    </li>
                    <li class="nav-item" role="presentation">
                        <button class="nav-link" id="estilo-tab" data-bs-toggle="tab" data-bs-target="#estilo" type="button" role="tab">
                            <i class="bi bi-palette"></i> Estilo
                        </button>
                    </li>
                    <li class="nav-item" role="presentation">
                        <button class="nav-link" id="backup-tab" data-bs-toggle="tab" data-bs-target="#backup" type="button" role="tab">
                            <i class="bi bi-file-earmark-arrow-down"></i> Backup
                        </button>
                    </li>
                    <li class="nav-item" role="presentation">
                        <button class="nav-link" id="site-tab" data-bs-toggle="tab" data-bs-target="#site" type="button" role="tab">
                            <i class="bi bi-globe"></i> Site
                        </button>
                    </li>
                </ul>

                <!-- Tab Content -->
                <div class="tab-content mt-4" id="configTabsContent">
                    <!-- Empresa Tab -->
                    <div class="tab-pane fade show active" id="empresa" role="tabpanel">
                        <form id="empresaForm" class="config-form">
                            <div class="row">
                                <div class="col-md-3 text-center mb-4">
                                    <div class="logo-upload">
                                        <img src="assets/img/placeholder-logo.png" alt="Logo" id="logoPreview" class="mb-2">
                                        <input type="file" id="logoInput" accept="image/*" class="d-none">
                                        <button type="button" class="btn btn-outline-primary btn-sm" onclick="document.getElementById('logoInput').click()">
                                            <i class="bi bi-upload"></i> Alterar Logo
                                        </button>
                                    </div>
                                </div>
                                <div class="col-md-9">
                                    <div class="row">
                                        <div class="col-md-6 mb-3">
                                            <label for="nomeEmpresa" class="form-label">Nome da Empresa</label>
                                            <input type="text" class="form-control" id="nomeEmpresa" name="nome_empresa">
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label for="cnpj" class="form-label">CNPJ</label>
                                            <input type="text" class="form-control" id="cnpj" name="cnpj">
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label for="endereco" class="form-label">Endereço</label>
                                    <input type="text" class="form-control" id="endereco" name="endereco">
                                </div>
                                <div class="col-md-2 mb-3">
                                    <label for="numero" class="form-label">Nº</label>
                                    <input type="text" class="form-control" id="numero" name="numero">
                                </div>
                                <div class="col-md-4 mb-3">
                                    <label for="bairro" class="form-label">Bairro</label>
                                    <input type="text" class="form-control" id="bairro" name="bairro">
                                </div>
                            </div>

                            <div class="row">
                                <div class="col-md-3 mb-3">
                                    <label for="cep" class="form-label">CEP</label>
                                    <input type="text" class="form-control" id="cep" name="cep">
                                </div>
                                <div class="col-md-4 mb-3">
                                    <label for="cidade" class="form-label">Cidade</label>
                                    <input type="text" class="form-control" id="cidade" name="cidade">
                                </div>
                                <div class="col-md-5 mb-3">
                                    <label for="celular" class="form-label">Celular</label>
                                    <input type="text" class="form-control" id="celular" name="celular">
                                </div>
                            </div>

                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label for="email" class="form-label">Email</label>
                                    <input type="email" class="form-control" id="email" name="email">
                                </div>
                            </div>

                            <div class="row mt-3">
                                <div class="col-12">
                                    <button type="submit" class="btn btn-primary">
                                        <i class="bi bi-save"></i> Salvar Alterações
                                    </button>
                                </div>
                            </div>
                        </form>
                    </div>

                    <!-- Redes Sociais Tab -->
                    <div class="tab-pane fade" id="redes-sociais" role="tabpanel">
                        <form id="redesSociaisForm" class="config-form">
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">
                                        <i class="bi bi-instagram"></i> Instagram
                                    </label>
                                    <div class="input-group">
                                        <span class="input-group-text">@</span>
                                        <input type="text" class="form-control" id="instagram" name="instagram">
                                    </div>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">
                                        <i class="bi bi-facebook"></i> Facebook
                                    </label>
                                    <input type="text" class="form-control" id="facebook" name="facebook">
                                </div>
                            </div>

                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">
                                        <i class="bi bi-tiktok"></i> TikTok
                                    </label>
                                    <div class="input-group">
                                        <span class="input-group-text">@</span>
                                        <input type="text" class="form-control" id="tiktok" name="tiktok">
                                    </div>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">
                                        <i class="bi bi-linkedin"></i> LinkedIn
                                    </label>
                                    <input type="text" class="form-control" id="linkedin" name="linkedin">
                                </div>
                            </div>

                            <div class="row mt-3">
                                <div class="col-12">
                                    <button type="submit" class="btn btn-primary">
                                        <i class="bi bi-save"></i> Salvar Alterações
                                    </button>
                                </div>
                            </div>
                        </form>
                    </div>

                    <!-- Estilo Tab -->
                    <div class="tab-pane fade" id="estilo" role="tabpanel">
                        <form id="estiloForm" class="config-form">
                            <div class="row">
                                <div class="col-md-3 mb-4">
                                    <label class="form-label">Cor Primária</label>
                                    <div class="color-picker-wrapper">
                                        <input type="color" class="form-control form-control-color" id="corPrimaria" value="#bd7fbe" name="cor_primaria">
                                        <input type="text" class="form-control" id="corPrimariaHex" value="#bd7fbe" name="cor_primaria_hex">
                                    </div>
                                </div>
                                <div class="col-md-3 mb-4">
                                    <label class="form-label">Cor Secundária</label>
                                    <div class="color-picker-wrapper">
                                        <input type="color" class="form-control form-control-color" id="corSecundaria" value="#9c5c9d" name="cor_secundaria">
                                        <input type="text" class="form-control" id="corSecundariaHex" value="#9c5c9d" name="cor_secundaria_hex">
                                    </div>
                                </div>
                                <div class="col-md-3 mb-4">
                                    <label class="form-label">Cor Terciária</label>
                                    <div class="color-picker-wrapper">
                                        <input type="color" class="form-control form-control-color" id="corTerciaria" value="#166053" name="cor_terciaria">
                                        <input type="text" class="form-control" id="corTerciariaHex" value="#166053" name="cor_terciaria_hex">
                                    </div>
                                </div>
                                <div class="col-md-3 mb-4">
                                    <label class="form-label">Cor do Texto</label>
                                    <div class="color-picker-wrapper">
                                        <input type="color" class="form-control form-control-color" id="corTexto" value="#333333" name="cor_texto">
                                        <input type="text" class="form-control" id="corTextoHex" value="#333333" name="cor_texto_hex">
                                    </div>
                                </div>
                            </div>

                            <div class="row mt-3">
                                <div class="col-12">
                                    <button type="submit" class="btn btn-primary">
                                        <i class="bi bi-save"></i> Salvar Alterações
                                    </button>
                                </div>
                            </div>
                        </form>
                    </div>

                    <!-- Backup Tab -->
                    <div class="tab-pane fade" id="backup" role="tabpanel">
                        <div class="card">
                            <div class="card-body">
                                <h5 class="card-title mb-4" style="color: var(--text-color);">Backup do Banco de Dados</h5>
                                
                                <!-- Exportar -->
                                <div class="mb-4">
                                    <h6 style="color: var(--text-color);">Exportar Banco de Dados</h6>
                                    <p class="text-muted">Faça o download de um backup completo do banco de dados.</p>
                                    <a href="actions/export_database.php" class="btn btn-primary">
                                        <i class="bi bi-download me-2"></i>Exportar Banco de Dados
                                    </a>
                                </div>

                                <hr>

                                <!-- Importar -->
                                <div class="mt-4">
                                    <h6 style="color: var(--text-color);">Importar Banco de Dados</h6>
                                    <p class="text-muted">Restaure o banco de dados a partir de um arquivo de backup.</p>
                                    <form id="formImportDatabase" enctype="multipart/form-data">
                                        <div class="mb-3">
                                            <input type="file" class="form-control" name="sql_file" accept=".sql" required>
                                        </div>
                                        <button type="submit" class="btn btn-warning">
                                            <i class="bi bi-upload me-2"></i>Importar Banco de Dados
                                        </button>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Site Tab -->
                    <div class="tab-pane fade" id="site" role="tabpanel">
                        <div class="card">
                            <div class="card-body">
                                <form id="siteForm" class="config-form">
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="mb-4">
                                                <div class="d-flex align-items-center justify-content-between">
                                                    <label class="form-label d-flex align-items-center">
                                                        <span class="me-3" style="font-size: 1.1rem;">Site Ativo</span>
                                                        <div class="form-check form-switch">
                                                            <input class="form-check-input" type="checkbox" id="siteAtivo" style="width: 3.5em; height: 1.8em;">
                                                        </div>
                                                    </label>
                                                    <a href="/<?php echo $current_folder; ?>/loja" id="btnAcessarSite" class="btn btn-primary" style="display: none;" target="_blank" rel="noopener">
                                                        <i class="fas fa-external-link-alt me-2"></i>Acessar Site
                                                    </a>
                                                </div>
                                                <div class="text-muted">Ative ou desative o acesso ao site</div>
                                            </div>
                                            
                                            <div class="mb-4">
                                                <label class="form-label d-flex align-items-center">
                                                    <span class="me-3" style="font-size: 1.1rem;">Slide Ativo</span>
                                                    <div class="form-check form-switch">
                                                        <input class="form-check-input" type="checkbox" id="slideAtivo" style="width: 3.5em; height: 1.8em;">
                                                    </div>
                                                </label>
                                                <div class="text-muted">Ative ou desative o slide na página inicial</div>
                                            </div>
                                            
                                            <!-- Configurações do Slide -->
                                            <div id="slideConfig" class="mt-4" style="display: none;">
                                                <h5 class="mb-4">Configurações do Slide</h5>
                                                
                                                <div class="mb-4">
                                                    <label class="form-label">Imagem do Slide (Background)</label>
                                                    <input type="file" class="form-control" id="slideImage" name="slide_image" accept="image/*">
                                                    <div class="mt-2">
                                                        <img id="slideImagePreview" src="" alt="Preview do Slide" style="max-width: 100%; display: none;" class="rounded">
                                                    </div>
                                                </div>

                                                <div class="mb-4">
                                                    <label class="form-label">Texto Principal</label>
                                                    <input type="text" class="form-control" id="slideTextoPrincipal" name="slide_texto_principal" placeholder="Ex: Bem-vinda à Loja">
                                                    <div class="form-text">Este texto aparecerá em destaque no slide</div>
                                                </div>

                                                <div class="mb-4">
                                                    <label class="form-label">Texto Secundário</label>
                                                    <input type="text" class="form-control" id="slideTextoSecundario" name="slide_texto_secundario" placeholder="Ex: Descubra nossa nova coleção">
                                                    <div class="form-text">Este texto aparecerá abaixo do texto principal</div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="row mt-3">
                                        <div class="col-12">
                                            <button type="submit" class="btn btn-primary">
                                                <i class="bi bi-save"></i> Salvar Alterações
                                            </button>
                                        </div>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Toast Container -->
    <div class="toast-container position-fixed bottom-0 end-0 p-3"></div>

    <!-- Scripts -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.16/jquery.mask.min.js"></script>
    <script src="assets/js/configuracoes.js?v=<?php echo time(); ?>"></script>

    <script>
        $(document).ready(function() {
            // Função para mostrar toast
            function showToast(message, type = 'success') {
                const bgColor = type === 'success' ? 'bg-success' : 'bg-danger';
                const toast = `
                    <div class="toast ${bgColor} text-white" role="alert" aria-live="assertive" aria-atomic="true">
                        <div class="d-flex">
                            <div class="toast-body">
                                ${message}
                            </div>
                            <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
                        </div>
                    </div>
                `;
                
                $('.toast-container').append(toast);
                const toastElement = $('.toast').last();
                const bsToast = new bootstrap.Toast(toastElement);
                bsToast.show();
                
                // Remove o toast depois que ele é fechado
                toastElement.on('hidden.bs.toast', function() {
                    $(this).remove();
                });
            }

            // Carrega as configurações do site
            function loadSiteConfig() {
                $.get('actions/get_site_config.php')
                    .done(function(response) {
                        if (response.success) {
                            const siteAtivo = response.data.site_ativo == 1;
                            $('#siteAtivo').prop('checked', siteAtivo);
                            $('#slideAtivo').prop('checked', response.data.slide_ativo == 1);
                            $('#slideConfig').toggle(response.data.slide_ativo == 1);
                            $('#slideImagePreview').attr('src', response.data.slide_image);
                            $('#slideTextoPrincipal').val(response.data.slide_texto_principal);
                            $('#slideTextoSecundario').val(response.data.slide_texto_secundario);
                            
                            // Mostra ou esconde o botão de acessar site
                            $('#btnAcessarSite').toggle(siteAtivo);
                        }
                    })
                    .fail(function(xhr) {
                        showToast('Erro ao carregar configurações', 'error');
                    });
            }

            // Atualiza visibilidade do botão quando o switch mudar
            $('#siteAtivo').on('change', function() {
                $('#btnAcessarSite').toggle($(this).is(':checked'));
            });

            $('#slideAtivo').on('change', function() {
                $('#slideConfig').toggle($(this).is(':checked'));
            });

            // Salva as configurações do site
            $('#siteForm').on('submit', function(e) {
                e.preventDefault();
                
                const formData = new FormData();
                formData.append('site_ativo', $('#siteAtivo').is(':checked') ? 1 : 0);
                formData.append('slide_ativo', $('#slideAtivo').is(':checked') ? 1 : 0);
                formData.append('slide_texto_principal', $('#slideTextoPrincipal').val());
                formData.append('slide_texto_secundario', $('#slideTextoSecundario').val());
                
                // Adiciona a imagem se uma foi selecionada
                const slideImageInput = $('#slideImage')[0];
                if (slideImageInput.files && slideImageInput.files[0]) {
                    formData.append('slide_image', slideImageInput.files[0]);
                }
                
                $.ajax({
                    url: 'actions/save_site_config.php',
                    type: 'POST',
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function(response) {
                        if (response.success) {
                            showToast('Configurações do site salvas com sucesso!');
                        } else {
                            showToast(response.message || 'Erro ao salvar configurações', 'error');
                        }
                    },
                    error: function(xhr) {
                        showToast('Erro ao salvar configurações', 'error');
                    }
                });
            });

            // Carrega as configurações iniciais
            loadSiteConfig();
        });
    </script>
</body>
</html>
