<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Instalação - Portal Bahia</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.0/font/bootstrap-icons.css">
    <style>
        body {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }
        .install-container {
            max-width: 800px;
            margin: 0 auto;
            background: white;
            border-radius: 12px;
            box-shadow: 0 10px 40px rgba(0,0,0,0.2);
            padding: 40px;
        }
        .step-indicator {
            display: flex;
            justify-content: space-between;
            margin-bottom: 30px;
        }
        .step {
            flex: 1;
            text-align: center;
            padding: 10px;
            border-radius: 8px;
            background: #f0f0f0;
            margin: 0 5px;
        }
        .step.active {
            background: #667eea;
            color: white;
        }
        .step.completed {
            background: #28a745;
            color: white;
        }
    </style>
</head>
<body>
    <div class="install-container">
        <div class="text-center mb-4">
            <h1><i class="bi bi-newspaper"></i> Portal Bahia</h1>
            <p class="text-muted">Instalador do Sistema</p>
        </div>
        
        <div class="step-indicator">
            <div class="step active" id="step-1">
                <strong>1</strong><br>Configuração
            </div>
            <div class="step" id="step-2">
                <strong>2</strong><br>Download
            </div>
            <div class="step" id="step-3">
                <strong>3</strong><br>Instalação
            </div>
            <div class="step" id="step-4">
                <strong>4</strong><br>Concluído
            </div>
        </div>
        
        <div id="step-content">
            <!-- Conteúdo será carregado via JavaScript -->
        </div>
            </div>
            
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        let currentStep = 1;
        const totalSteps = 4;

        function showStep(step) {
            currentStep = step;
            
            // Atualizar indicadores
            for (let i = 1; i <= totalSteps; i++) {
                const stepEl = document.getElementById(`step-${i}`);
                stepEl.classList.remove('active', 'completed');
                if (i < step) {
                    stepEl.classList.add('completed');
                } else if (i === step) {
                    stepEl.classList.add('active');
                }
            }

            // Carregar conteúdo do passo
            const content = document.getElementById('step-content');
            
            switch(step) {
                case 1:
                    content.innerHTML = getStep1Content();
                    break;
                case 2:
                    content.innerHTML = getStep2Content();
                    break;
                case 3:
                    content.innerHTML = getStep3Content();
                    break;
                case 4:
                    content.innerHTML = getStep4Content();
                    break;
            }
        }

        function getStep1Content() {
            return `
                <h3>Configuração Inicial</h3>
                <form id="config-form" onsubmit="return false;">
                    <div class="mb-3">
                        <label class="form-label">URL do Servidor Central</label>
                        <input type="url" class="form-control" id="server_url" 
                               value="https://servidor.canal33.com.br" required>
                        <small class="text-muted">Servidor onde estão os arquivos do portal</small>
                    </div>
                
                    <div class="mb-3">
                        <label class="form-label">URL do Master Panel</label>
                        <input type="url" class="form-control" id="master_url" 
                               value="https://master.canal33.com.br" required>
                </div>
                
                    <div class="mb-3">
                        <label class="form-label">License Key</label>
                        <input type="text" class="form-control" id="license_key" required>
                </div>
                
                    <hr>

                    <h5>Banco de Dados</h5>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Host</label>
                            <input type="text" class="form-control" id="db_host" value="localhost" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Porta</label>
                            <input type="number" class="form-control" id="db_port" value="3306" required>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Nome do Banco</label>
                        <input type="text" class="form-control" id="db_database" required>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Usuário</label>
                            <input type="text" class="form-control" id="db_username" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Senha</label>
                            <input type="password" class="form-control" id="db_password">
                        </div>
                </div>
                
                    <hr>

                    <h5>Administrador</h5>
                    <div class="mb-3">
                        <label class="form-label">Nome</label>
                        <input type="text" class="form-control" id="admin_name" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Email</label>
                        <input type="email" class="form-control" id="admin_email" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Senha</label>
                        <input type="password" class="form-control" id="admin_password" required minlength="8">
                </div>
                
                    <button type="button" class="btn btn-primary w-100" onclick="proceedToStep2()">
                        Próximo <i class="bi bi-arrow-right"></i>
                    </button>
            </form>
            `;
        }

        function getStep2Content() {
            return `
                <h3>Download de Arquivos</h3>
                <div id="download-progress">
                    <div class="progress mb-3">
                        <div class="progress-bar" id="progress-bar" style="width: 0%">0%</div>
                    </div>
                    <div id="download-status">Preparando download...</div>
                </div>
                <button type="button" class="btn btn-primary w-100" onclick="startDownload()" id="btn-download">
                    Iniciar Download
                </button>
            `;
        }

        function getStep3Content() {
            return `
                <h3>Instalação</h3>
                <div id="install-progress">
                    <div class="progress mb-3">
                        <div class="progress-bar" id="install-progress-bar" style="width: 0%">0%</div>
                    </div>
                    <div id="install-status">Preparando instalação...</div>
                    <div id="install-log" class="mt-3" style="max-height: 300px; overflow-y: auto; background: #f5f5f5; padding: 15px; border-radius: 5px; font-family: monospace; font-size: 12px;"></div>
                </div>
            `;
        }

        function getStep4Content() {
            return `
                <div class="text-center">
                    <i class="bi bi-check-circle-fill text-success" style="font-size: 64px;"></i>
                    <h3 class="mt-3">Instalação Concluída!</h3>
                    <p class="text-muted">O Portal Bahia foi instalado com sucesso.</p>
                    <div class="alert alert-info">
                        <strong>URL do Admin:</strong><br>
                        <a href="/admin/login" id="admin-url" target="_blank"></a>
                    </div>
                    <button type="button" class="btn btn-success" onclick="window.location.href='/admin/login'">
                        Acessar Painel Admin
                    </button>
                </div>
            `;
        }

        let configData = {};

        function proceedToStep2() {
            // Validar formulário
            const form = document.getElementById('config-form');
            if (!form.checkValidity()) {
                form.reportValidity();
                return;
            }

            // Salvar dados
            configData = {
                server_url: document.getElementById('server_url').value,
                master_url: document.getElementById('master_url').value,
                license_key: document.getElementById('license_key').value,
                db_host: document.getElementById('db_host').value,
                db_port: document.getElementById('db_port').value,
                db_database: document.getElementById('db_database').value,
                db_username: document.getElementById('db_username').value,
                db_password: document.getElementById('db_password').value,
                admin_name: document.getElementById('admin_name').value,
                admin_email: document.getElementById('admin_email').value,
                admin_password: document.getElementById('admin_password').value
            };

            showStep(2);
        }

        async function startDownload() {
            const btn = document.getElementById('btn-download');
            btn.disabled = true;
            btn.innerHTML = '<span class="spinner-border spinner-border-sm"></span> Baixando...';

            const statusEl = document.getElementById('download-status');
            const progressBar = document.getElementById('progress-bar');

            try {
                const response = await fetch('install.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        action: 'download',
                        config: configData
                    })
                });

                const reader = response.body.getReader();
                const decoder = new TextDecoder();
                let progress = 0;

                while (true) {
                    const { done, value } = await reader.read();
                    if (done) break;

                    const chunk = decoder.decode(value);
                    const lines = chunk.split('\n');

                    for (const line of lines) {
                        if (line.startsWith('progress:')) {
                            progress = parseInt(line.split(':')[1]);
                            progressBar.style.width = progress + '%';
                            progressBar.textContent = progress + '%';
                        } else if (line.startsWith('status:')) {
                            statusEl.textContent = line.split(':')[1].trim();
                        }
                    }
                }

                if (progress === 100) {
                    setTimeout(() => {
                        showStep(3);
                        startInstallation();
                    }, 1000);
                }
            } catch (error) {
                statusEl.textContent = 'Erro: ' + error.message;
                btn.disabled = false;
            }
        }

        async function startInstallation() {
            const statusEl = document.getElementById('install-status');
            const progressBar = document.getElementById('install-progress-bar');
            const logEl = document.getElementById('install-log');

            function addLog(message) {
                logEl.innerHTML += message + '<br>';
                logEl.scrollTop = logEl.scrollHeight;
            }

            try {
                addLog('Iniciando instalação...');

                const response = await fetch('install.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        action: 'install',
                        config: configData
                    })
                });

                const reader = response.body.getReader();
                const decoder = new TextDecoder();
                let progress = 0;

                while (true) {
                    const { done, value } = await reader.read();
                    if (done) break;

                    const chunk = decoder.decode(value);
                    const lines = chunk.split('\n');

                    for (const line of lines) {
                        if (line.startsWith('progress:')) {
                            progress = parseInt(line.split(':')[1]);
                            progressBar.style.width = progress + '%';
                            progressBar.textContent = progress + '%';
                        } else if (line.startsWith('log:')) {
                            addLog(line.split(':')[1].trim());
                        } else if (line.startsWith('status:')) {
                            statusEl.textContent = line.split(':')[1].trim();
                        }
                    }
                }

                if (progress === 100) {
                    addLog('✅ Instalação concluída com sucesso!');
                    setTimeout(() => {
                        showStep(4);
                        document.getElementById('admin-url').href = window.location.origin + '/admin/login';
                        document.getElementById('admin-url').textContent = window.location.origin + '/admin/login';
                    }, 2000);
                }
            } catch (error) {
                addLog('❌ Erro: ' + error.message);
            }
        }

        // Inicializar
        showStep(1);
    </script>
</body>
</html>

