<?php
require_once '/var/www/html/config/config.php';
$db = Database::getInstance();

echo "🔄 Creando tabla scheduled_messages...\n\n";

try {
    $db->execute("
        CREATE TABLE IF NOT EXISTS scheduled_messages (
            id INT AUTO_INCREMENT PRIMARY KEY,
            user_id INT NOT NULL,
            template_id INT NULL,
            template_name VARCHAR(100) NULL,
            template_language VARCHAR(10) DEFAULT 'es',
            template_parameters JSON NULL COMMENT 'Parámetros para las variables de la plantilla',
            message_type ENUM('text', 'template') DEFAULT 'template',
            message_content TEXT NULL COMMENT 'Contenido del mensaje si es tipo text',
            scheduled_date DATE NOT NULL,
            scheduled_time TIME NOT NULL,
            status ENUM('pending', 'sent', 'failed', 'cancelled') DEFAULT 'pending',
            sent_at DATETIME NULL,
            error_message TEXT NULL,
            created_by INT NULL COMMENT 'ID del admin que creó el recordatorio',
            created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
            updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            
            INDEX idx_user_id (user_id),
            INDEX idx_scheduled_date (scheduled_date),
            INDEX idx_status (status),
            INDEX idx_scheduled_datetime (scheduled_date, scheduled_time, status)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    ");
    echo "✅ Tabla scheduled_messages creada\n\n";
} catch (Exception $e) {
    echo "❌ Error: " . $e->getMessage() . "\n\n";
}

echo "📋 Verificando tabla:\n";
try {
    $cols = $db->fetchAll('DESCRIBE scheduled_messages');
    echo "✅ Tabla scheduled_messages existe con " . count($cols) . " columnas:\n";
    foreach($cols as $c) {
        echo "  - {$c['Field']} ({$c['Type']})\n";
    }
} catch (Exception $e) {
    echo "❌ Tabla NO existe: " . $e->getMessage() . "\n";
}
