<?php
// CORS Headers
header('Access-Control-Allow-Origin: http://localhost:5173');
header('Access-Control-Allow-Methods: GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
header('Access-Control-Allow-Credentials: true');

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

require_once '../../config/db.php';
require_once '../../core/Auth.php';

if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    http_response_code(405);
    echo json_encode(['error' => 'Method not allowed']);
    exit;
}

try {
    // 1. Verificar Autenticación
    $user_id = Auth::check();
    error_log("[get_messages.php] User authenticated: $user_id");

    // 2. Parámetros
    if (!isset($_GET['chat_id'])) {
        http_response_code(400);
        echo json_encode(['error' => 'Missing chat_id']);
        exit;
    }

    $chat_id = (int)$_GET['chat_id'];
    $last_id = isset($_GET['last_id']) ? (int)$_GET['last_id'] : 0;
    
    error_log("[get_messages.php] Parameters: chat_id=$chat_id, last_id=$last_id");

    // 3. Consultar Mensajes Nuevos
    // Traemos también info del remitente desde i_users
    $sql = "SELECT m.*, u.i_username as username, u.user_avatar as avatar 
            FROM messages m 
            JOIN i_users u ON m.sender_id = u.iuid 
            WHERE m.chat_id = ? AND m.id > ? 
            ORDER BY m.id ASC LIMIT 50";
    
    error_log("[get_messages.php] Executing SQL: $sql with params [$chat_id, $last_id]");
            
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$chat_id, $last_id]);
    $messages = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    error_log("[get_messages.php] Found " . count($messages) . " messages");

    // Normalizar avatares a URLs absolutas
    $server_url = "http://localhost/Juuvix_Shop/KLKAPP%20TEST";
    foreach ($messages as &$msg) {
        if ($msg['avatar'] && $msg['avatar'] !== 'default.png') {
            if (preg_match('/avatars[\\\\\/]([^\\\\\/]+)$/', $msg['avatar'], $matches)) {
                $msg['avatar'] = $server_url . "/avatars/" . $matches[1];
            } else if (strpos($msg['avatar'], 'http') === false) {
                $msg['avatar'] = $server_url . "/avatars/" . basename($msg['avatar']);
            }
        }
    }

    echo json_encode([
        'status' => 'success',
        'messages' => $messages
    ]);

} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['error' => 'DB Error: ' . $e->getMessage()]);
}
?>
