<?php
/**
 * API - Editar mensaje
 * Permite editar el contenido de un mensaje enviado (solo mensajes propios/outgoing)
 * Fecha: 28 de enero de 2026
 */

// Habilitar display de errores para debug
ini_set('display_errors', 1);
error_reporting(E_ALL);

require_once '../config/config.php';

// Log para debug
error_log("edit_message.php: Iniciando, session_id=" . session_id() . ", admin_logged_in=" . (isset($_SESSION['admin_logged_in']) ? $_SESSION['admin_logged_in'] : 'no definido'));

requireAuthentication();

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

// Manejar preflight OPTIONS request
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'error' => 'Método no permitido. Use POST.']);
    exit;
}

try {
    $input = json_decode(file_get_contents('php://input'), true);
    
    if (!$input) {
        http_response_code(400);
        echo json_encode(['success' => false, 'error' => 'JSON inválido']);
        exit;
    }
    
    $messageId = $input['message_id'] ?? $input['id'] ?? null;
    $newContent = $input['content'] ?? $input['new_content'] ?? null;
    
    if (!$messageId) {
        http_response_code(400);
        echo json_encode(['success' => false, 'error' => 'message_id es requerido']);
        exit;
    }
    
    if ($newContent === null || trim($newContent) === '') {
        http_response_code(400);
        echo json_encode(['success' => false, 'error' => 'El contenido no puede estar vacío']);
        exit;
    }
    
    $db = Database::getInstance();
    
    // Buscar el mensaje
    $sql = "SELECT id, user_id, direction, message_type, content, message_id as wa_message_id 
            FROM conversations 
            WHERE id = :mid1 OR message_id = :mid2 
            LIMIT 1";
    $message = $db->fetch($sql, ['mid1' => $messageId, 'mid2' => $messageId]);
    
    if (!$message) {
        http_response_code(404);
        echo json_encode(['success' => false, 'error' => 'Mensaje no encontrado']);
        exit;
    }
    
    // Solo permitir editar mensajes salientes (outgoing)
    if ($message['direction'] !== 'outgoing') {
        http_response_code(403);
        echo json_encode(['success' => false, 'error' => 'Solo puedes editar tus propios mensajes']);
        exit;
    }
    
    // Solo permitir editar mensajes de texto
    if ($message['message_type'] !== 'text' && $message['message_type'] !== null) {
        http_response_code(400);
        echo json_encode(['success' => false, 'error' => 'Solo se pueden editar mensajes de texto']);
        exit;
    }
    
    // Guardar contenido original para historial (opcional)
    $originalContent = $message['content'];
    
    // Verificar si existe la columna edited_at
    $hasEditedAt = false;
    try {
        $columns = $db->fetchAll("SHOW COLUMNS FROM conversations WHERE Field = 'edited_at'");
        $hasEditedAt = !empty($columns);
    } catch (Exception $e) {
        // Ignorar
    }
    
    // Actualizar el mensaje en la base de datos
    if ($hasEditedAt) {
        $updateSql = "UPDATE conversations SET content = :content, edited_at = NOW() WHERE id = :id";
    } else {
        $updateSql = "UPDATE conversations SET content = :content WHERE id = :id";
    }
    
    $db->execute($updateSql, [
        'content' => trim($newContent),
        'id' => $message['id']
    ]);
    
    // Registrar la edición en el log
    error_log("Message edited: ID={$message['id']}, User={$message['user_id']}, Original='{$originalContent}', New='{$newContent}'");
    
    // Intentar notificar por SSE si está disponible
    try {
        $ssePayload = [
            'type' => 'message_edited',
            'user_id' => $message['user_id'],
            'message_id' => $message['id'],
            'wa_message_id' => $message['wa_message_id'],
            'new_content' => trim($newContent),
            'edited_at' => date('Y-m-d H:i:s')
        ];
        
        // Llamar al endpoint push_event interno
        $pushUrl = 'http://127.0.0.1' . dirname($_SERVER['SCRIPT_NAME']) . '/push_event.php';
        $ch = curl_init($pushUrl);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
            'event_type' => 'message_edited',
            'data' => $ssePayload,
            'target_user_id' => 'all'
        ]));
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 2);
        curl_exec($ch);
        curl_close($ch);
    } catch (Exception $sseErr) {
        error_log("edit_message: SSE notification failed: " . $sseErr->getMessage());
    }
    
    echo json_encode([
        'success' => true,
        'message' => 'Mensaje editado correctamente',
        'data' => [
            'id' => $message['id'],
            'message_id' => $message['wa_message_id'],
            'new_content' => trim($newContent),
            'edited_at' => date('Y-m-d H:i:s')
        ]
    ]);
    
} catch (Exception $e) {
    error_log('edit_message.php error: ' . $e->getMessage() . ' | Trace: ' . $e->getTraceAsString());
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => 'Error interno del servidor', 'debug' => $e->getMessage()]);
}
