<?php

/**
 * Script para executar a migration de mensagens
 * Acesse via navegador: http://localhost/SouMulherAgenda/executar_migration_mensagens.php
 */

// Carregar o autoloader do CodeIgniter
require_once __DIR__ . '/vendor/autoload.php';

// Inicializar o CodeIgniter
$pathsConfig = FCPATH . '../app/Config/Paths.php';
require realpath($pathsConfig) ?: $pathsConfig;

$paths = new Config\Paths();
$bootstrap = rtrim($paths->systemDirectory, '\\/ ') . DIRECTORY_SEPARATOR . 'bootstrap.php';
$app = require realpath($bootstrap) ?: $bootstrap;

?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Executar Migrations - Sistema de Mensagens</title>
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            max-width: 900px;
            margin: 50px auto;
            padding: 20px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
        }
        .container {
            background: white;
            padding: 40px;
            border-radius: 15px;
            box-shadow: 0 10px 40px rgba(0,0,0,0.2);
        }
        h1 {
            color: #667eea;
            border-bottom: 3px solid #667eea;
            padding-bottom: 15px;
            margin-bottom: 30px;
        }
        pre {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 8px;
            border-left: 4px solid #667eea;
            overflow-x: auto;
            font-size: 14px;
            line-height: 1.6;
        }
        .success {
            color: #28a745;
            font-weight: bold;
        }
        .error {
            color: #dc3545;
            font-weight: bold;
        }
        .info {
            color: #17a2b8;
        }
        .btn {
            display: inline-block;
            padding: 12px 30px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            text-decoration: none;
            border-radius: 8px;
            margin-top: 20px;
            transition: all 0.3s ease;
        }
        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
        }
        .status-box {
            background: #e7f3ff;
            padding: 15px;
            border-radius: 8px;
            margin: 20px 0;
            border-left: 4px solid #2196F3;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🔧 Executando Migrations do Sistema de Mensagens</h1>

        <?php
        // Verificar estrutura atual da tabela
        $db = \Config\Database::connect();

        echo "<div class='status-box'>";
        echo "<strong>📊 Status Atual da Tabela 'mensagens':</strong><br>";

        if ($db->tableExists('mensagens')) {
            $fields = $db->getFieldNames('mensagens');
            echo "<pre>";
            echo "Colunas existentes: " . implode(', ', $fields) . "\n";

            $hasUserId = in_array('user_id', $fields);
            $hasLida = in_array('lida', $fields);
            $hasCreatedAt = in_array('created_at', $fields);

            echo "\n";
            echo ($hasUserId ? "✓" : "✗") . " user_id\n";
            echo ($hasLida ? "✓" : "✗") . " lida\n";
            echo ($hasCreatedAt ? "✓" : "✗") . " created_at\n";
            echo "</pre>";
        } else {
            echo "<pre>⚠ Tabela 'mensagens' não encontrada!</pre>";
        }
        echo "</div>";

        // Rodar a migration
        try {
            $migrate = \Config\Services::migrations();
            $migrate->setNamespace('App');

            echo "<h2>🚀 Executando Migrations...</h2>";
            echo "<pre>";

            if ($migrate->latest()) {
                echo "\n<span class='success'>✅ Migrations executadas com sucesso!</span>\n";
            } else {
                echo "\n<span class='info'>⚠ Nenhuma nova migration para executar.</span>\n";
            }

            echo "</pre>";

            // Verificar estrutura após migration
            echo "<div class='status-box'>";
            echo "<strong>📊 Status Após Migration:</strong><br>";

            if ($db->tableExists('mensagens')) {
                $fields = $db->getFieldNames('mensagens');
                echo "<pre>";
                echo "Colunas atualizadas: " . implode(', ', $fields) . "\n";

                $hasUserId = in_array('user_id', $fields);
                $hasLida = in_array('lida', $fields);
                $hasCreatedAt = in_array('created_at', $fields);
                $hasUpdatedAt = in_array('updated_at', $fields);

                echo "\n";
                echo ($hasUserId ? "✓" : "✗") . " user_id\n";
                echo ($hasLida ? "✓" : "✗") . " lida\n";
                echo ($hasCreatedAt ? "✓" : "✗") . " created_at\n";
                echo ($hasUpdatedAt ? "✓" : "✗") . " updated_at\n";

                if ($hasUserId && $hasLida && $hasCreatedAt && $hasUpdatedAt) {
                    echo "\n<span class='success'>🎉 Todas as colunas necessárias foram criadas!</span>\n";
                    echo "\n<strong>Próximos passos:</strong>\n";
                    echo "1. Acesse ATIVAR_MENSAGENS_DINAMICAS.md\n";
                    echo "2. Siga as instruções para ativar badge e dropdown dinâmicos\n";
                    echo "3. Insira mensagens de teste (SQL no arquivo de instruções)\n";
                    echo "4. Acesse: <a href='" . base_url('mensagens') . "'>" . base_url('mensagens') . "</a>\n";
                } else {
                    echo "\n<span class='error'>⚠ Algumas colunas ainda estão faltando.</span>\n";
                }
                echo "</pre>";
            }
            echo "</div>";

        } catch (\Exception $e) {
            echo "<h2 class='error'>❌ Erro ao executar migrations</h2>";
            echo "<pre class='error'>";
            echo "Erro: " . $e->getMessage() . "\n\n";
            echo "Stack trace:\n" . $e->getTraceAsString();
            echo "</pre>";

            echo "<div class='status-box'>";
            echo "<strong>💡 Possíveis soluções:</strong><br>";
            echo "<pre>";
            echo "1. Verifique se o MySQL está rodando\n";
            echo "2. Confirme as credenciais do banco de dados\n";
            echo "3. Verifique as permissões do usuário do banco\n";
            echo "4. Confira se a tabela 'mensagens' existe\n";
            echo "</pre>";
            echo "</div>";
        }
        ?>

        <a href="<?= base_url('dashboard') ?>" class="btn">🏠 Voltar ao Dashboard</a>
        <a href="<?= base_url('mensagens') ?>" class="btn" style="background: linear-gradient(135deg, #56ab2f 0%, #a8e063 100%);">📧 Ver Mensagens</a>
    </div>
</body>
</html>
