-- ============================================
-- MIGRATION: Atualização da Tabela Mensagens
-- Sistema de Mensagens - Sou Mulher Agenda
-- ============================================
--
-- COMO USAR:
-- 1. Abra o phpMyAdmin
-- 2. Selecione o banco "soumulheragenda"
-- 3. Vá na aba "SQL"
-- 4. Cole todo este código
-- 5. Clique em "Executar"
--
-- ============================================

-- Usar o banco correto
USE soumulheragenda;

-- ============================================
-- PASSO 1: Adicionar coluna user_id
-- ============================================
SET @dbname = DATABASE();
SET @tablename = 'mensagens';
SET @columnname = 'user_id';
SET @preparedStatement = (SELECT IF(
    (
        SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS
        WHERE
            (table_name = @tablename)
            AND (table_schema = @dbname)
            AND (column_name = @columnname)
    ) > 0,
    "SELECT 1;",
    CONCAT("ALTER TABLE ", @tablename, " ADD ", @columnname, " INT(11) NOT NULL DEFAULT 0 AFTER id;")
));
PREPARE alterIfNotExists FROM @preparedStatement;
EXECUTE alterIfNotExists;
DEALLOCATE PREPARE alterIfNotExists;

SELECT '✓ Coluna user_id verificada/adicionada' AS STATUS;

-- ============================================
-- PASSO 2: Adicionar coluna lida
-- ============================================
SET @columnname = 'lida';
SET @preparedStatement = (SELECT IF(
    (
        SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS
        WHERE
            (table_name = @tablename)
            AND (table_schema = @dbname)
            AND (column_name = @columnname)
    ) > 0,
    "SELECT 1;",
    CONCAT("ALTER TABLE ", @tablename, " ADD ", @columnname, " TINYINT(1) NOT NULL DEFAULT 0 AFTER tag;")
));
PREPARE alterIfNotExists FROM @preparedStatement;
EXECUTE alterIfNotExists;
DEALLOCATE PREPARE alterIfNotExists;

SELECT '✓ Coluna lida verificada/adicionada' AS STATUS;

-- ============================================
-- PASSO 3: Adicionar coluna created_at
-- ============================================
SET @columnname = 'created_at';
SET @preparedStatement = (SELECT IF(
    (
        SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS
        WHERE
            (table_name = @tablename)
            AND (table_schema = @dbname)
            AND (column_name = @columnname)
    ) > 0,
    "SELECT 1;",
    CONCAT("ALTER TABLE ", @tablename, " ADD ", @columnname, " DATETIME NULL DEFAULT NULL;")
));
PREPARE alterIfNotExists FROM @preparedStatement;
EXECUTE alterIfNotExists;
DEALLOCATE PREPARE alterIfNotExists;

SELECT '✓ Coluna created_at verificada/adicionada' AS STATUS;

-- ============================================
-- PASSO 4: Adicionar coluna updated_at
-- ============================================
SET @columnname = 'updated_at';
SET @preparedStatement = (SELECT IF(
    (
        SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS
        WHERE
            (table_name = @tablename)
            AND (table_schema = @dbname)
            AND (column_name = @columnname)
    ) > 0,
    "SELECT 1;",
    CONCAT("ALTER TABLE ", @tablename, " ADD ", @columnname, " DATETIME NULL DEFAULT NULL;")
));
PREPARE alterIfNotExists FROM @preparedStatement;
EXECUTE alterIfNotExists;
DEALLOCATE PREPARE alterIfNotExists;

SELECT '✓ Coluna updated_at verificada/adicionada' AS STATUS;

-- ============================================
-- PASSO 5: Criar índices otimizados
-- ============================================

-- Índice para user_id
SET @s = (SELECT IF(
    (SELECT COUNT(*) FROM INFORMATION_SCHEMA.STATISTICS
     WHERE table_schema = DATABASE()
     AND table_name = 'mensagens'
     AND index_name = 'idx_user_id') > 0,
    "SELECT '→ Índice idx_user_id já existe' AS STATUS;",
    "ALTER TABLE mensagens ADD INDEX idx_user_id (user_id); SELECT '✓ Índice idx_user_id criado' AS STATUS;"
));
PREPARE stmt FROM @s;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

-- Índice composto user_id + lida
SET @s = (SELECT IF(
    (SELECT COUNT(*) FROM INFORMATION_SCHEMA.STATISTICS
     WHERE table_schema = DATABASE()
     AND table_name = 'mensagens'
     AND index_name = 'idx_user_lida') > 0,
    "SELECT '→ Índice idx_user_lida já existe' AS STATUS;",
    "ALTER TABLE mensagens ADD INDEX idx_user_lida (user_id, lida); SELECT '✓ Índice idx_user_lida criado' AS STATUS;"
));
PREPARE stmt FROM @s;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

-- Índice para created_at
SET @s = (SELECT IF(
    (SELECT COUNT(*) FROM INFORMATION_SCHEMA.STATISTICS
     WHERE table_schema = DATABASE()
     AND table_name = 'mensagens'
     AND index_name = 'idx_created_at') > 0,
    "SELECT '→ Índice idx_created_at já existe' AS STATUS;",
    "ALTER TABLE mensagens ADD INDEX idx_created_at (created_at); SELECT '✓ Índice idx_created_at criado' AS STATUS;"
));
PREPARE stmt FROM @s;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

-- ============================================
-- PASSO 6: Verificar estrutura final
-- ============================================
SELECT '======================================' AS '';
SELECT '✅ MIGRATION EXECUTADA COM SUCESSO!' AS '';
SELECT '======================================' AS '';
SELECT '' AS '';
SELECT 'Estrutura atual da tabela mensagens:' AS '';
DESCRIBE mensagens;

SELECT '' AS '';
SELECT 'Índices criados:' AS '';
SHOW INDEX FROM mensagens;

-- ============================================
-- MENSAGENS DE TESTE (OPCIONAL)
-- ============================================
SELECT '' AS '';
SELECT '======================================' AS '';
SELECT 'Para inserir mensagens de teste:' AS '';
SELECT '======================================' AS '';
SELECT 'Execute o SQL abaixo (substitua 32 pelo seu user_id):' AS '';
SELECT '' AS '';

/*
-- DESCOMENTE AS LINHAS ABAIXO PARA INSERIR MENSAGENS DE TESTE
-- IMPORTANTE: Substitua 32 pelo seu user_id correto!

INSERT INTO mensagens (user_id, titulo_acao, mensagem, tag, lida, created_at)
VALUES
(32, 'Bem-vindo ao sistema!', 'Configure seus dados e comece a usar o sistema.', 'info', 0, NOW()),
(32, 'Sistema atualizado', 'Novas funcionalidades foram adicionadas ao sistema.', 'success', 0, NOW()),
(32, 'Atenção: Backup recomendado', 'Faça backup dos seus dados regularmente para evitar perdas.', 'warning', 0, NOW()),
(32, 'Erro no pagamento', 'Houve um problema ao processar o pagamento. Tente novamente.', 'danger', 0, NOW());

SELECT '✅ Mensagens de teste inseridas!' AS STATUS;
*/

-- ============================================
-- PRÓXIMOS PASSOS
-- ============================================
SELECT '' AS '';
SELECT '📋 Próximos Passos:' AS '';
SELECT '1. Leia o arquivo: ATIVAR_MENSAGENS_DINAMICAS.md' AS '';
SELECT '2. Ative o badge e dropdown dinâmicos no menu' AS '';
SELECT '3. Insira mensagens de teste (descomente acima)' AS '';
SELECT '4. Acesse: http://localhost/SouMulherAgenda/mensagens' AS '';
