<?php
/**
 * API - Obtener mensajes de una conversación específica
 */

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

// Modo debug: desactivar autenticación si existe el parámetro debug
$debugMode = isset($_GET['debug']) && $_GET['debug'] === 'true';

if (!$debugMode) {
    requireAuthentication();
}

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

try {
    $user_id = $_GET['user_id'] ?? null;
    
    if (!$user_id) {
        http_response_code(400);
        echo json_encode(['error' => 'user_id es requerido']);
        exit;
    }
    
    $db = Database::getInstance();
    
    // Obtener información del usuario
    $user = $db->fetch(
        "SELECT id, phone_number, name, in_service, in_service_by, in_service_at FROM users WHERE id = ?",
        [$user_id]
    );
    
    if (!$user) {
        http_response_code(404);
        echo json_encode(['error' => 'Usuario no encontrado']);
        exit;
    }

    // Si la conversación está siendo atendida, resolver el nombre del operador
    $inServiceByName = null;
    if (!empty($user['in_service_by'])) {
        $admin = $db->fetch("SELECT id, full_name, username FROM admin_users WHERE id = ?", [$user['in_service_by']]);
        if ($admin) {
            $inServiceByName = $admin['full_name'] ?: $admin['username'];
        }
    }
    
    // Obtener todos los mensajes de la conversación
    $conversations = $db->fetchAll(
        "SELECT 
            id,
            message_id,
            direction,
            message_type,
            content,
            media_url,
            local_file,
            local_thumb,
            filename,
            mime_type,
            status,
            created_at
         FROM conversations 
         WHERE user_id = ? 
         AND (
             message_type = 'text' 
             OR (message_type IN ('image', 'audio', 'video', 'document', 'sticker') AND (media_url IS NOT NULL AND media_url != '' OR local_file IS NOT NULL AND local_file != ''))
         )
         ORDER BY created_at ASC",
        [$user_id]
    );
    
    // Formatear mensajes
    $conversations = array_map(function($msg) {
            // Build external URL if available (media id -> api/get_media proxy)
            $external = (isset($msg['media_url']) && $msg['media_url']) ? (preg_match('#^https?://#i', $msg['media_url']) ? $msg['media_url'] : ("api/version/media-url.php?id=" . urlencode($msg['media_url']))) : null;

            // Fallback: if no external URL but content is JSON with link, extract it
            $contentStr = $msg['content'] ?? '';
            if (!$external && $contentStr) {
                $j = json_decode($contentStr, true);
                if (is_array($j)) {
                    // Look for common shapes: image.link, image.url, document.link, audio.link
                    $candidates = [];
                    foreach (['image','document','audio','video'] as $k) {
                        if (isset($j[$k]) && is_array($j[$k])) {
                            if (!empty($j[$k]['link'])) $candidates[] = $j[$k]['link'];
                            if (!empty($j[$k]['url'])) $candidates[] = $j[$k]['url'];
                            if (!empty($j[$k]['id'])) $candidates[] = $j[$k]['id'];
                        }
                    }
                    // also top-level 'link'
                    if (!empty($j['link'])) $candidates[] = $j['link'];
                    // first valid candidate wins
                    foreach ($candidates as $cand) {
                        if ($cand) {
                            // if looks like id or url
                            $external = preg_match('#^https?://#i', $cand) ? $cand : (strpos($cand, 'http') === false ? "api/version/media-url.php?id=" . urlencode($cand) : $cand);
                            break;
                        }
                    }
                }
            }

            return [
                'id' => intval($msg['id']),
                'message_id' => $msg['message_id'] ?? '',
                'direction' => $msg['direction'],
                'message_type' => $msg['message_type'],
                'content' => $msg['content'] ?? '',
                'media_url' => null,
                'local_file' => $msg['local_file'] ?? null,
                'local_thumb' => $msg['local_thumb'] ?? null,
                'media_url_external' => $external,
                'filename' => $msg['filename'] ?? null,
                'mime_type' => $msg['mime_type'] ?? null,
                'status' => $msg['status'] ?? 'sent',
                'created_at' => $msg['created_at'],
                'time' => date('g:i a', strtotime($msg['created_at'])),
                'date' => date('d/m/Y', strtotime($msg['created_at']))
            ];
        }, $conversations);
    // Marcar mensajes como leídos
    $db->query(
        "UPDATE conversations SET status = 'read' WHERE user_id = ? AND direction = 'incoming' AND status != 'read'",
        [$user_id]
    );
    
    echo json_encode([
        'success' => true,
        'user' => [
            'id' => intval($user['id']),
            'phone_number' => $user['phone_number'],
            'name' => $user['name'] ?? $user['phone_number'],
            'in_service' => !empty($user['in_service']) ? true : false,
            'in_service_by' => isset($user['in_service_by']) ? intval($user['in_service_by']) : null,
            'in_service_at' => $user['in_service_at'] ?? null,
            'in_service_by_name' => $inServiceByName,
            'advisor_requested' => !empty($user['advisor_requested']) ? true : false,
            'on_hold' => !empty($user['on_hold']) ? true : false
        ],
        'conversations' => $conversations,
        'total_conversations' => count($conversations)
    ]);
    
} catch (Exception $e) {
    error_log("Error in get_conversation_detail.php: " . $e->getMessage());
    http_response_code(500);
    echo json_encode(['error' => 'Error interno del servidor: ' . $e->getMessage()]);
}
?>