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

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

$action = $_POST['action'] ?? '';
$userId = $_SESSION['user_id'] ?? 0;
$username = $_SESSION['username'] ?? 'Unknown';

// Function to redirect with a status message
function redirect_with_status($status, $message) {
    header("Location: ../recurrentes.php?status=$status&message=" . urlencode($message));
    exit;
}


try {
    switch ($action) {
        case 'create':
            $name = trim($_POST['messageName'] ?? '');
            $content = trim($_POST['messageContent'] ?? '');
            $telegram_command = trim($_POST['telegram_command'] ?? '');

            if (empty($name) || empty($content)) {
                redirect_with_status('error', 'El nombre y el contenido del mensaje son obligatorios.');
            }

            // Si el comando no está vacío, asegúrate de que no contenga el '#'
            if (!empty($telegram_command)) {
                $telegram_command = ltrim($telegram_command, '#');
            }

            $stmt = $pdo->prepare(
                "INSERT INTO recurrent_messages (name, telegram_command, message_content) 
                 VALUES (?, ?, ?)"
            );
            $stmt->execute([$name, $telegram_command, $content]);
            log_activity($userId, 'Recurrent Message Created', 'User ' . $username . ' created recurrent message: ' . $name);
            redirect_with_status('success', 'Mensaje guardado exitosamente.');
            break;

        case 'activate':
        case 'deactivate':
            $id = $_POST['id'] ?? 0;
            $is_active = ($action === 'activate') ? 1 : 0;
            $stmt = $pdo->prepare("UPDATE recurrent_messages SET is_active = ? WHERE id = ?");
            $stmt->execute([$is_active, $id]);
            $status_message = ($action === 'activate') ? 'activado' : 'desactivado';
            log_activity($userId, 'Recurrent Message Status Change', 'User ' . $username . ' ' . $status_message . ' recurrent message ID: ' . $id);
            redirect_with_status('success', "Mensaje recurrente $status_message.");
            break;

        case 'update':
            $id = $_POST['id'] ?? 0;
            $name = trim($_POST['messageName'] ?? '');
            $content = trim($_POST['messageContent'] ?? '');
            $telegram_command = trim($_POST['telegram_command'] ?? '');

            if (empty($id) || empty($name) || empty($content)) {
                redirect_with_status('error', 'ID, nombre y contenido del mensaje son obligatorios para actualizar.');
            }

            // Si el comando no está vacío, asegúrate de que no contenga el '#'
            if (!empty($telegram_command)) {
                $telegram_command = ltrim($telegram_command, '#');
            }

            $stmt = $pdo->prepare(
                "UPDATE recurrent_messages SET name = ?, telegram_command = ?, message_content = ? WHERE id = ?"
            );
            $stmt->execute([$name, $telegram_command, $content, $id]);
            log_activity($userId, 'Recurrent Message Updated', 'User ' . $username . ' updated recurrent message ID: ' . $id . ' with name: ' . $name);
            redirect_with_status('success', 'Mensaje recurrente actualizado exitosamente.');
            break;

        case 'delete':
            $id = $_POST['id'] ?? 0;
            $stmt = $pdo->prepare("DELETE FROM recurrent_messages WHERE id = ?");
            $stmt->execute([$id]);
            log_activity($userId, 'Recurrent Message Deleted', 'User ' . $username . ' deleted recurrent message ID: ' . $id);
            redirect_with_status('success', 'Mensaje recurrente eliminado.');
            break;

        default:
            redirect_with_status('error', 'Acción no válida.');
            break;
    }
} catch (PDOException $e) {
    // Log the error in a real application
    error_log("Error in recurrent_message_handler: " . $e->getMessage());
    redirect_with_status('error', 'Error en la base de datos: ' . $e->getMessage());
}
