<?php
require_once __DIR__ . '/session_check.php';
require_once __DIR__ . '/db.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: ../tren.php');
    exit();
}

$userId = $_SESSION['user_id'];
$content = $_POST['messageContent'] ?? '';
$recipientId = $_POST['recipientId'] ?? '';
$scheduleType = $_POST['scheduleType'] ?? 'now';

// Validation
if (empty($recipientId) || empty($content)) {
    header('Location: ../tren.php?error=missing_fields');
    exit();
}

$pdo->beginTransaction();

try {
    // 1. Save the message content
    $stmt = $pdo->prepare("INSERT INTO messages (user_id, content) VALUES (?, ?)");
    $stmt->execute([$userId, $content]);
    $messageId = $pdo->lastInsertId();

    // 2. Schedule the message
    $sendTime = null;
    $status = 'pending';

    if ($scheduleType === 'later') {
        if (empty($_POST['scheduleDateTime'])) {
            throw new Exception('La fecha y hora de envío son requeridas para programar.');
        }
        $sendTime = (new DateTime($_POST['scheduleDateTime'], new DateTimeZone('America/Mexico_City')))->format('Y-m-d H:i:s');
    } else { // 'now'
        $sendTime = date('Y-m-d H:i:s');
    }

    $stmt = $pdo->prepare(
        "INSERT INTO schedules (message_id, recipient_id, send_time, status, is_recurring, recurring_days, recurring_time) VALUES (?, ?, ?, ?, 0, NULL, NULL)"
    );
    $stmt->execute([$messageId, $recipientId, $sendTime, $status]);

    $pdo->commit();

    // If it's an immediate send, trigger processing
    if ($scheduleType === 'now') {
        $phpPath = PHP_BINARY ?: 'php';
        $scriptPath = dirname(__DIR__) . '/process_queue.php';
        $logPath = dirname(__DIR__) . '/logs/process_queue_manual.log';
        
        // Asegurarse de que se use el entorno correcto
        $command = sprintf(
            'APP_ENVIRONMENT=pruebas %s %s >> %s 2>&1 &', 
            escapeshellarg($phpPath), 
            escapeshellarg($scriptPath), 
            escapeshellarg($logPath)
        );
        
        // Registrar el comando que se va a ejecutar para depuración
        error_log("Ejecutando comando desde tren_handler.php: " . $command . "\n", 3, dirname(__DIR__) . '/logs/tren_handler.log');
        
        // Ejecutar el comando
        shell_exec($command);
    }

    header('Location: ../scheduled_messages.php?success=message_created');
    exit();

} catch (Exception $e) {
    $pdo->rollBack();
    // Log the error properly in a real application
    header('Location: ../tren.php?error=dberror');
    exit();
}
?>