<?php
/**
 * Script de Configuração Inicial do Admin SEF-MG
 * 
 * Execute este script UMA VEZ para configurar a senha do admin
 * Acesse: http://localhost:8080/admin/setup.php
 */

header('Content-Type: text/html; charset=utf-8');

$dbPath = __DIR__ . '/admin.db';
$setupComplete = false;
$message = '';

// Criar conexão com o banco
try {
    $pdo = new PDO('sqlite:' . $dbPath);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    // Criar tabela settings se não existir
    $pdo->exec("CREATE TABLE IF NOT EXISTS settings (
        key TEXT PRIMARY KEY,
        value TEXT NOT NULL,
        updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
    )");
    
    // Criar tabela events se não existir
    $pdo->exec("CREATE TABLE IF NOT EXISTS events (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        session_id TEXT,
        event_type TEXT,
        event_timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
        ip_address TEXT,
        user_agent TEXT,
        metadata TEXT
    )");
    
} catch (Exception $e) {
    die("Erro ao conectar ao banco: " . $e->getMessage());
}

// Verificar se já tem senha configurada
$stmt = $pdo->prepare('SELECT value FROM settings WHERE key = :key LIMIT 1');
$stmt->execute([':key' => 'admin_password_hash']);
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$hasPassword = !empty($row['value']);

// Processar formulário
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    if ($action === 'set_password') {
        $password = $_POST['password'] ?? '';
        $confirm = $_POST['confirm'] ?? '';
        
        if (strlen($password) < 4) {
            $message = '❌ A senha deve ter pelo menos 4 caracteres.';
        } elseif ($password !== $confirm) {
            $message = '❌ As senhas não coincidem.';
        } else {
            $hash = password_hash($password, PASSWORD_DEFAULT);
            
            $stmt = $pdo->prepare('INSERT INTO settings (key, value, updated_at) VALUES (:key, :value, CURRENT_TIMESTAMP)
                ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = CURRENT_TIMESTAMP');
            $stmt->execute([':key' => 'admin_password_hash', ':value' => $hash]);
            
            $setupComplete = true;
            $message = '✅ Senha configurada com sucesso!';
            $hasPassword = true;
        }
    }
    
    if ($action === 'set_pix') {
        $pixKey = trim($_POST['pix_key'] ?? '');
        $pixKeyType = $_POST['pix_key_type'] ?? 'cpf';
        $receiverName = trim($_POST['receiver_name'] ?? 'SEF-MG');
        $receiverCity = trim($_POST['receiver_city'] ?? 'BELO HORIZONTE');
        
        $pixConfig = [
            'mode' => 'manual',
            'active' => true,
            'pixKey' => $pixKey,
            'pixKeyType' => $pixKeyType,
            'receiverName' => strtoupper(substr($receiverName, 0, 25)),
            'receiverCity' => strtoupper(substr($receiverCity, 0, 15)),
            'amount' => null,
            'apiUrl' => '',
            'secretKey' => '',
            'companyId' => ''
        ];
        
        $stmt = $pdo->prepare('INSERT INTO settings (key, value, updated_at) VALUES (:key, :value, CURRENT_TIMESTAMP)
            ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = CURRENT_TIMESTAMP');
        $stmt->execute([':key' => 'pix_config', ':value' => json_encode($pixConfig)]);
        
        $message = '✅ Configuração PIX salva com sucesso!';
    }
}

// Buscar config PIX atual
$stmt = $pdo->prepare('SELECT value FROM settings WHERE key = :key LIMIT 1');
$stmt->execute([':key' => 'pix_config']);
$pixRow = $stmt->fetch(PDO::FETCH_ASSOC);
$pixConfig = $pixRow ? json_decode($pixRow['value'], true) : [];
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Setup - Admin SEF-MG</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: linear-gradient(135deg, #b81f25 0%, #8b0000 100%);
            min-height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 20px;
        }
        .container {
            background: white;
            border-radius: 16px;
            box-shadow: 0 20px 60px rgba(0,0,0,0.3);
            padding: 40px;
            max-width: 500px;
            width: 100%;
        }
        h1 {
            color: #b81f25;
            margin-bottom: 10px;
            font-size: 28px;
        }
        .subtitle {
            color: #666;
            margin-bottom: 30px;
        }
        .section {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 20px;
        }
        .section h3 {
            color: #333;
            margin-bottom: 15px;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        .form-group {
            margin-bottom: 15px;
        }
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: 500;
            color: #333;
        }
        input, select {
            width: 100%;
            padding: 12px;
            border: 1px solid #ddd;
            border-radius: 8px;
            font-size: 16px;
        }
        input:focus, select:focus {
            outline: none;
            border-color: #b81f25;
        }
        button {
            width: 100%;
            padding: 14px;
            background: #b81f25;
            color: white;
            border: none;
            border-radius: 8px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            margin-top: 10px;
        }
        button:hover {
            background: #a01a20;
        }
        .message {
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
            font-weight: 500;
        }
        .message.success {
            background: #d4edda;
            color: #155724;
        }
        .message.error {
            background: #f8d7da;
            color: #721c24;
        }
        .status {
            display: inline-block;
            padding: 4px 10px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
        }
        .status.ok { background: #d4edda; color: #155724; }
        .status.pending { background: #fff3cd; color: #856404; }
        .link {
            text-align: center;
            margin-top: 20px;
        }
        .link a {
            color: #b81f25;
            text-decoration: none;
            font-weight: 500;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🏛️ Setup Admin</h1>
        <p class="subtitle">SEF-MG - Sistema de IPVA</p>
        
        <?php if ($message): ?>
        <div class="message <?= strpos($message, '✅') !== false ? 'success' : 'error' ?>">
            <?= $message ?>
        </div>
        <?php endif; ?>
        
        <!-- Seção Senha -->
        <div class="section">
            <h3>
                🔐 Senha de Acesso
                <span class="status <?= $hasPassword ? 'ok' : 'pending' ?>">
                    <?= $hasPassword ? 'Configurada' : 'Pendente' ?>
                </span>
            </h3>
            <form method="POST">
                <input type="hidden" name="action" value="set_password">
                <div class="form-group">
                    <label>Nova Senha</label>
                    <input type="password" name="password" required minlength="4" placeholder="Digite a senha de acesso">
                </div>
                <div class="form-group">
                    <label>Confirmar Senha</label>
                    <input type="password" name="confirm" required minlength="4" placeholder="Confirme a senha">
                </div>
                <button type="submit"><?= $hasPassword ? 'Alterar Senha' : 'Definir Senha' ?></button>
            </form>
        </div>
        
        <!-- Seção PIX -->
        <div class="section">
            <h3>
                💳 Configuração PIX
                <span class="status <?= !empty($pixConfig['pixKey']) ? 'ok' : 'pending' ?>">
                    <?= !empty($pixConfig['pixKey']) ? 'Configurado' : 'Pendente' ?>
                </span>
            </h3>
            <form method="POST">
                <input type="hidden" name="action" value="set_pix">
                <div class="form-group">
                    <label>Tipo de Chave PIX</label>
                    <select name="pix_key_type">
                        <option value="cpf" <?= ($pixConfig['pixKeyType'] ?? '') === 'cpf' ? 'selected' : '' ?>>CPF</option>
                        <option value="cnpj" <?= ($pixConfig['pixKeyType'] ?? '') === 'cnpj' ? 'selected' : '' ?>>CNPJ</option>
                        <option value="email" <?= ($pixConfig['pixKeyType'] ?? '') === 'email' ? 'selected' : '' ?>>E-mail</option>
                        <option value="phone" <?= ($pixConfig['pixKeyType'] ?? '') === 'phone' ? 'selected' : '' ?>>Telefone</option>
                        <option value="random" <?= ($pixConfig['pixKeyType'] ?? '') === 'random' ? 'selected' : '' ?>>Chave Aleatória</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>Chave PIX</label>
                    <input type="text" name="pix_key" value="<?= htmlspecialchars($pixConfig['pixKey'] ?? '') ?>" placeholder="Sua chave PIX">
                </div>
                <div class="form-group">
                    <label>Nome do Recebedor (máx 25 chars)</label>
                    <input type="text" name="receiver_name" value="<?= htmlspecialchars($pixConfig['receiverName'] ?? 'SEF-MG') ?>" maxlength="25" placeholder="SEF-MG">
                </div>
                <div class="form-group">
                    <label>Cidade (máx 15 chars)</label>
                    <input type="text" name="receiver_city" value="<?= htmlspecialchars($pixConfig['receiverCity'] ?? 'BELO HORIZONTE') ?>" maxlength="15" placeholder="BELO HORIZONTE">
                </div>
                <button type="submit">Salvar Configuração PIX</button>
            </form>
        </div>
        
        <?php if ($hasPassword): ?>
        <div class="link">
            <a href="login.html">→ Acessar Painel Admin</a>
        </div>
        <?php endif; ?>
    </div>
</body>
</html>
