<?php
// /chat_inbox.php
// VERSIÓN CORREGIDA (Sintaxis MySQL y error de 'case')

session_start();
// Asegúrate que esta comprobación es correcta y no redirige inesperadamente
if (!isset($_SESSION['user_id']) || !in_array($_SESSION['user_rol'], ['superadmin', 'fisio'])) {
    // Redirige a index si no hay sesión o el rol no es correcto
    header('Location: index.php');
    exit;
}
// Si llegamos aquí, la sesión y el rol son válidos para esta página.

require 'db.php';
require_once 'logger.php'; // ★★★ AÑADIDO: Incluir logger.php ★★★

$user_id = $_SESSION['user_id'];
$user_rol = $_SESSION['user_rol'];
$user_name = $_SESSION['user_nombre'] . ' ' . $_SESSION['user_apellido']; // ★★★ AÑADIDO: Obtener nombre completo del actor ★★★

// --- GESTOR DE PETICIONES AJAX PARA EL CHAT ---
if (isset($_REQUEST['ajax'])) {
    header('Content-Type: application/json');
    $action = $_REQUEST['action'] ?? '';
    // Definimos la ruta de la carpeta de imágenes para la limpieza en caso de borrado permanente
    $upload_dir = __DIR__ . '/chat_img/';

    try {
        switch ($action) {
            case 'get_conversations':
                // --- ★ INICIO CORRECCIÓN BUG (Lógica Estricta) ★ ---
                // Esta consulta AHORA solo muestra pacientes si el fisio
                // es creador O colaborador de un tratamiento 'En curs'.
                $stmt = $db->prepare("
                    SELECT DISTINCT
                        p.id, p.nombre, p.apellido,
                        ccv.deleted_until, -- Obtenemos fecha de borrado (si existe)

                        -- Subconsulta para last_message, considerando deleted_until
                        (SELECT cm.body
                         FROM chat_messages cm
                         WHERE ((cm.from_id = p.id AND cm.to_id = :user_id) OR (cm.from_id = :user_id AND cm.to_id = p.id))
                           -- Condición: Mostrar mensaje solo si NO ha sido borrado O si el mensaje es MÁS NUEVO que la fecha de borrado
                           AND (ccv.user_id IS NULL OR cm.created_at > ccv.deleted_until)
                         ORDER BY cm.created_at DESC
                         LIMIT 1) as last_message,

                        -- Subconsulta para last_message_time, considerando deleted_until (misma lógica)
                        (SELECT cm.created_at
                         FROM chat_messages cm
                         WHERE ((cm.from_id = p.id AND cm.to_id = :user_id) OR (cm.from_id = :user_id AND cm.to_id = p.id))
                           AND (ccv.user_id IS NULL OR cm.created_at > ccv.deleted_until)
                         ORDER BY cm.created_at DESC
                         LIMIT 1) as last_message_time,

                        -- Contar 1 si hay mensajes no leídos, 0 si no
                        (SELECT CASE WHEN COUNT(*) > 0 THEN 1 ELSE 0 END
                         FROM chat_messages cm
                         WHERE cm.from_id = p.id AND cm.to_id = :user_id AND cm.status != 'read') as unread_count
                    FROM cuentas p
                    -- JOINs necesarios para filtrar por tratamiento activo y obtener deleted_until
                    JOIN tratamientos t ON t.paciente_id = p.id
                    LEFT JOIN tratamiento_fisios_asignados tfa ON t.id = tfa.tratamiento_id
                    LEFT JOIN chat_conversation_visibility ccv -- Unimos aquí para usar ccv en las subconsultas
                        ON ccv.user_id = :user_id AND ccv.other_user_id = p.id
                    WHERE
                        p.rol = 'paciente' AND p.status = 'activo'
                        AND t.status = 'En curs' -- Tratamiento debe estar activo
                        -- Criterio de vinculación ESTRICTO:
                        AND (t.creator_fisio_id = :user_id OR tfa.fisio_id = :user_id)
                        -- Se elimina: OR p.id_fisio_registrador = :user_id
                    GROUP BY p.id
                    ORDER BY COALESCE(last_message_time, '1970-01-01') DESC, p.apellido, p.nombre
                ");
                // --- ★ FIN CORRECCIÓN BUG ★ ---
                $stmt->execute([':user_id' => $user_id]);
                $conversations = $stmt->fetchAll(PDO::FETCH_ASSOC);

                foreach ($conversations as &$conv) {
                    $conv['initials'] = strtoupper(mb_substr($conv['nombre'] ?? '', 0, 1) . mb_substr($conv['apellido'] ?? '', 0, 1));
                }

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

            case 'get_messages':
                $patient_id = (int)$_GET['patient_id'];
                if ($patient_id === 0) throw new Exception("ID de pacient no vàlid.");

                $updateStmt = $db->prepare("UPDATE chat_messages SET status = 'read' WHERE from_id = :patient_id AND to_id = :user_id AND status != 'read'");
                $updateStmt->execute([':patient_id' => $patient_id, ':user_id' => $user_id]);

                // --- Obtener historial (Usa visibilidad) ---
                $stmt = $db->prepare("
                    SELECT cm.id, cm.from_id, cm.body, cm.status, cm.created_at
                    FROM chat_messages cm
                    LEFT JOIN chat_conversation_visibility ccv
                        ON ccv.user_id = :user_id AND ccv.other_user_id = :patient_id
                    WHERE
                        ((cm.from_id = :user_id AND cm.to_id = :patient_id) OR (cm.from_id = :patient_id AND cm.to_id = :user_id))
                        AND (ccv.user_id IS NULL OR cm.created_at > ccv.deleted_until)
                    ORDER BY cm.created_at ASC
                ");
                $stmt->execute([':user_id' => $user_id, ':patient_id' => $patient_id]);
                $messages = $stmt->fetchAll(PDO::FETCH_ASSOC);

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

            // --- ★★★ INICIO BLOQUE send_message (Implementando Log C14) ★★★ ---
            case 'send_message':
                $to_id = (int)$_POST['to_id'];
                $body = trim($_POST['message']);
                if ($to_id === 0 || empty($body)) throw new Exception("Destinatari o missatge no vàlids.");

                // Comprobar permiso ESTRICTO y obtener el nombre del paciente
                $checkStmt = $db->prepare("
                    SELECT 1, p.nombre, p.apellido
                    FROM tratamientos t
                    LEFT JOIN tratamiento_fisios_asignados tfa ON t.id = tfa.tratamiento_id
                    JOIN cuentas p ON t.paciente_id = p.id
                    WHERE
                        t.paciente_id = :patient_id
                        AND t.status = 'En curs'
                        AND (t.creator_fisio_id = :user_id OR tfa.fisio_id = :user_id)
                    LIMIT 1
                ");
                $checkStmt->execute([':patient_id' => $to_id, ':user_id' => $user_id]);
                $patient_data = $checkStmt->fetch(PDO::FETCH_ASSOC);
                if (!$patient_data) {
                    throw new Exception("No pots enviar missatges a aquest pacient (cap tractament actiu vinculat).");
                }
                $patient_name = $patient_data['nombre'] . ' ' . $patient_data['apellido'];

                $stmt = $db->prepare("INSERT INTO chat_messages (from_id, to_id, body, status, created_at) VALUES (:from_id, :to_id, :body, 'sent', NOW())");
                $stmt->execute([':from_id' => $user_id, ':to_id' => $to_id, ':body' => $body]);
                $new_message_id = $db->lastInsertId();

                // ★★★ REGISTRAR LOG C14 (Mensaje de texto) ★★★
                registrar_mensaje_chat_enviado($db, $user_id, $user_name, $to_id, $patient_name, $body);

                // Devolver la respuesta JSON correcta
                echo json_encode(['status' => 'success', 'newId' => $new_message_id]);
                break;
            // --- ★★★ FIN BLOQUE send_message ★★★ ---

            // --- ★★★ INICIO BLOQUE upload_chat_image (Implementando Log C14) ★★★ ---
            case 'upload_chat_image':
                $patient_id_to_send = (int)($_POST['patient_id'] ?? 0); if ($patient_id_to_send === 0) { throw new Exception("Destinatari no vàlid."); }

                // Comprobar permiso ESTRICTO y obtener el nombre del paciente (copiado de send_message)
                $checkStmt = $db->prepare("
                    SELECT 1, p.nombre, p.apellido
                    FROM tratamientos t
                    LEFT JOIN tratamiento_fisios_asignados tfa ON t.id = tfa.tratamiento_id
                    JOIN cuentas p ON t.paciente_id = p.id
                    WHERE
                        t.paciente_id = :patient_id
                        AND t.status = 'En curs'
                        AND (t.creator_fisio_id = :user_id OR tfa.fisio_id = :user_id)
                    LIMIT 1
                ");
                $checkStmt->execute([':patient_id' => $patient_id_to_send, ':user_id' => $user_id]);
                $patient_data = $checkStmt->fetch(PDO::FETCH_ASSOC);
                if (!$patient_data) {
                    throw new Exception("No pots enviar missatges a aquest pacient (cap tractament actiu vinculat).");
                }
                $patient_name = $patient_data['nombre'] . ' ' . $patient_data['apellido'];


                if (!isset($_FILES['chat_image']) || $_FILES['chat_image']['error'] !== UPLOAD_ERR_OK) { if (isset($_FILES['chat_image']['error']) && $_FILES['chat_image']['error'] === UPLOAD_ERR_INI_SIZE) { throw new Exception("L'arxiu és massa gran. Mida màxima configurada: 2MB."); } throw new Exception("Error al rebre l'arxiu. Comprova la mida i l'estat."); }
                $file = $_FILES['chat_image']; $max_size = 2 * 1024 * 1024; if ($file['size'] > $max_size) { throw new Exception("L'arxiu és massa gran. Mida màxima: 2MB."); } $allowed_types = ['image/jpeg', 'image/png', 'image/gif']; if (!in_array($file['type'], $allowed_types)) { throw new Exception("Tipus d'arxiu no permès. Només JPG, PNG o GIF."); }
                $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION)); $new_filename = uniqid('chat_img_') . '.' . $ext; $target_file = $upload_dir . $new_filename;
                if (!is_dir($upload_dir)) { if (!mkdir($upload_dir, 0777, true)) { throw new Exception("Error al crear el directori de càrrega ('chat_img/')."); } } if (!move_uploaded_file($file['tmp_name'], $target_file)) { throw new Exception("No s'ha pogut guardar l'arxiu al servidor."); } $message_body = 'img:' . $new_filename;

                // --- CORRECCIÓN MYSQL: datetime('now') -> NOW() ---
                $stmt = $db->prepare("INSERT INTO chat_messages (from_id, to_id, body, status, created_at) VALUES (:from_id, :to_id, :body, 'sent', NOW())");

                $stmt->execute([':from_id' => $user_id, ':to_id' => $patient_id_to_send, ':body' => $message_body]); $new_message_id = $db->lastInsertId();

                // ★★★ REGISTRAR LOG C14 (Mensaje de imagen) ★★★
                registrar_mensaje_chat_enviado($db, $user_id, $user_name, $patient_id_to_send, $patient_name, '[Imatge: ' . $new_filename . ']');


                echo json_encode(['status' => 'success', 'message' => 'Imatge enviada.', 'tempId' => $_POST['tempId'], 'newId' => $new_message_id, 'body' => $message_body, 'created_at' => date('Y-m-d H:i:s')]);
                break;
            // --- ★★★ FIN BLOQUE upload_chat_image ★★★ ---

            case 'delete_chat_message':
                 // (Código sin cambios)
                $message_id = (int)($_POST['message_id'] ?? 0); if ($message_id === 0) { throw new Exception("ID de missatge no vàlid."); }
                $stmt_check = $db->prepare("SELECT from_id, body FROM chat_messages WHERE id = ?"); $stmt_check->execute([$message_id]); $message = $stmt_check->fetch(PDO::FETCH_ASSOC); if (!$message) { throw new Exception("Missatge no trobat."); } if ($message['from_id'] != $user_id) { throw new Exception("No tens permís per eliminar aquest missatge."); }
                $stmt_delete = $db->prepare("DELETE FROM chat_messages WHERE id = ?"); $stmt_delete->execute([$message_id]);
                if ($stmt_delete->rowCount() > 0) { $body = $message['body']; if (strpos($body, 'img:') === 0) { $filename = substr($body, 4); $filepath = $upload_dir . $filename; if (file_exists($filepath)) { @unlink($filepath); } } echo json_encode(['status' => 'success', 'message' => 'Imatge eliminada permanentment.']); } else { throw new Exception("No s'ha pogut eliminar el missatge de la base de dades."); }
                break;

            case 'delete_conversation':
                $patient_id_to_delete = (int)$_POST['patient_id']; $mode = (string)($_POST['mode'] ?? 'self');
                if ($patient_id_to_delete === 0) { throw new Exception("ID de pacient no vàlid."); } if (!isset($user_id) || empty($user_id)) { throw new Exception("Error interno: ID de usuario no disponible."); }

                // Obtener nombre del paciente para el log
                $stmt_name = $db->prepare("SELECT nombre, apellido FROM cuentas WHERE id = ?");
                $stmt_name->execute([$patient_id_to_delete]);
                $patient_data = $stmt_name->fetch(PDO::FETCH_ASSOC);
                $patient_name = $patient_data ? ($patient_data['nombre'] . ' ' . $patient_data['apellido']) : 'Pacient desconegut';

                if ($mode === 'both') {
                    $stmt_files = $db->prepare("SELECT body FROM chat_messages WHERE ((from_id = :user_id AND to_id = :patient_id) OR (from_id = :patient_id AND to_id = :user_id)) AND body LIKE 'img:%'"); $stmt_files->execute([':user_id' => $user_id, ':patient_id' => $patient_id_to_delete]); $files_to_delete = $stmt_files->fetchAll(PDO::FETCH_COLUMN); $stmt_delete = $db->prepare("DELETE FROM chat_messages WHERE (from_id = :user_id AND to_id = :patient_id) OR (from_id = :patient_id AND to_id = :user_id)"); $stmt_delete->execute([':user_id' => $user_id, ':patient_id' => $patient_id_to_delete]); $stmt_clear_visibility = $db->prepare("DELETE FROM chat_conversation_visibility WHERE (user_id = :user_id AND other_user_id = :patient_id) OR (user_id = :patient_id AND other_user_id = :user_id)"); $stmt_clear_visibility->execute([':user_id' => $user_id, ':patient_id' => $patient_id_to_delete]); foreach ($files_to_delete as $body_with_prefix) { $filename = substr($body_with_prefix, 4); $filepath = $upload_dir . $filename; if (file_exists($filepath)) { @unlink($filepath); } }

                    // ★★★ REGISTRAR LOG C15 (Borrado permanente) ★★★
                    registrar_conversacion_borrada($db, $user_id, $user_name, $patient_id_to_delete, $patient_name, 'both');

                    echo json_encode(['status' => 'success', 'message' => 'Conversa eliminada permanentment per a ambdós usuaris.']);
                } else { $stmt_check_other = $db->prepare("SELECT 1 FROM chat_conversation_visibility WHERE user_id = :patient_id AND other_user_id = :user_id"); $stmt_check_other->execute([':patient_id' => $patient_id_to_delete, ':user_id' => $user_id]); if ($stmt_check_other->fetch()) { $stmt_files = $db->prepare("SELECT body FROM chat_messages WHERE ((from_id = :user_id AND to_id = :patient_id) OR (from_id = :patient_id AND to_id = :user_id)) AND body LIKE 'img:%'"); $stmt_files->execute([':user_id' => $user_id, ':patient_id' => $patient_id_to_delete]); $files_to_delete = $stmt_files->fetchAll(PDO::FETCH_COLUMN); $stmt_delete = $db->prepare("DELETE FROM chat_messages WHERE (from_id = :user_id AND to_id = :patient_id) OR (from_id = :patient_id AND to_id = :user_id)"); $stmt_delete->execute([':user_id' => $user_id, ':patient_id' => $patient_id_to_delete]); $stmt_clear_visibility = $db->prepare("DELETE FROM chat_conversation_visibility WHERE (user_id = :user_id AND other_user_id = :patient_id) OR (user_id = :patient_id AND other_user_id = :user_id)"); $stmt_clear_visibility->execute([':user_id' => $user_id, ':patient_id' => $patient_id_to_delete]); foreach ($files_to_delete as $body_with_prefix) { $filename = substr($body_with_prefix, 4); $filepath = $upload_dir . $filename; if (file_exists($filepath)) { @unlink($filepath); } }

                    // ★★★ REGISTRAR LOG C15 (Borrado permanente, caso especial) ★★★
                    registrar_conversacion_borrada($db, $user_id, $user_name, $patient_id_to_delete, $patient_name, 'both');

                    echo json_encode(['status' => 'success', 'message' => 'Conversa eliminada permanentment (ambdós usuaris l\'havien ocultat).']);
              } else {
                                  // --- CORRECCIÓN MYSQL: datetime('now') -> NOW() ---
                                  // --- CORRECCIÓN MYSQL: ON CONFLICT -> ON DUPLICATE KEY UPDATE ---
                                  $stmt_self = $db->prepare("
                                      INSERT INTO chat_conversation_visibility (user_id, other_user_id, deleted_until)
                                      VALUES (:user_id, :patient_id, NOW())
                                      ON DUPLICATE KEY UPDATE deleted_until = NOW()
                                  ");
                                  $stmt_self->execute([':user_id' => $user_id, ':patient_id' => $patient_id_to_delete]);

                                  // ★★★ REGISTRAR LOG C15 (Ocultado/Borrador para sí mismo) ★★★
                                  registrar_conversacion_borrada($db, $user_id, $user_name, $patient_id_to_delete, $patient_name, 'self');

                                  echo json_encode(['status' => 'success', 'message' => 'Conversa ocultada només per a tu.']);
                              } }
                              // --- ★★★ INICIO BLOQUE CORREGIDO (Error de sintaxis) ★★★ ---
                              // Faltaba el punto y coma (;)
                              break;
                              // --- ★★★ FIN BLOQUE CORREGIDO ★★★ ---

            // --- ★ INICIO: CÓDIGO AÑADIDO (Movido desde ajax_handler.php) ---
            case 'send_quick_feedback':

                // 1. Validar entradas
                if (!isset($_POST['to_patient_id']) || !is_numeric($_POST['to_patient_id'])) {
                    throw new Exception("ID de paciente destinatario no válido.");
                }
                if (!isset($_POST['message_body']) || empty(trim($_POST['message_body']))) {
                    throw new Exception("El cuerpo del mensaje no puede estar vacío.");
                }

                $from_fisio_id = $user_id; // Viene de la sesión (definido al inicio de chat_inbox.php)
                $to_patient_id = (int)$_POST['to_patient_id'];
                $message_body = trim($_POST['message_body']);

                // 2. Comprobar que el paciente existe y es un paciente (por seguridad)
                $stmt_check = $db->prepare("SELECT rol, nombre, apellido FROM cuentas WHERE id = ?");
                $stmt_check->execute([$to_patient_id]);
                $patient_data = $stmt_check->fetch(PDO::FETCH_ASSOC);

                if (!$patient_data || $patient_data['rol'] !== 'paciente') {
                    http_response_code(404); // Not Found
                    throw new Exception("El paciente destinatario no existe o no es un paciente.");
                }
                $patient_name = $patient_data['nombre'] . ' ' . $patient_data['apellido'];


                // 3. Insertar el mensaje en la BBDD
                                // --- CORRECCIÓN MYSQL: Añadir NOW() explícitamente ---
                                $stmt_insert = $db->prepare(
                                    "INSERT INTO chat_messages (from_id, to_id, body, status, created_at)
                                     VALUES (?, ?, ?, 'sent', NOW())"
                                );
                                $stmt_insert->execute([$from_fisio_id, $to_patient_id, $message_body]);

                if ($stmt_insert->rowCount() > 0) {

                    // ★★★ REGISTRAR LOG C14 (Quick Feedback) ★★★
                    registrar_mensaje_chat_enviado($db, $from_fisio_id, $user_name, $to_patient_id, $patient_name, $message_body);

                    echo json_encode(['status' => 'success', 'message' => 'Mensaje enviado.']);
                } else {
                    throw new Exception("No se ha podido enviar el mensaje.");
                }
                break;
            // --- ★ FIN: CÓDIGO AÑADIDO ---

            default:
                throw new Exception('Acció no vàlida.');
        }
    } catch (Exception $e) {
        $errorCode = ($e instanceof PDOException) ? 500 : 400;
        http_response_code($errorCode);
        error_log("Error AJAX en chat_inbox.php: Action='{$action}', UserID='{$user_id}', Error: " . $e->getMessage());
        echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
    }
    exit;
}
// Si no es una petición AJAX, continúa con la carga normal de la página HTML

$page_title = "Bandeja d'Entrada - AVANT ONLINE";
include 'partials/header.php'; // Incluye el header de admin/fisio
?>
<link rel="stylesheet" href="chat_interface.css?v=1.1">
<main class="main-content container mt-4" style="max-width: 1420px;">

    <div class="d-flex justify-content-between align-items-center mb-3">
        <h3><i class="bi bi-chat-dots me-2"></i>Xat</h3>
        <button type="button" class="btn btn-sm btn-outline-secondary" onclick="history.back();">
            <i class="bi bi-arrow-left-short me-1"></i> Tornar
        </button>
    </div>
    <div class="card shadow-sm">
        <div class="card-body p-0">
            <div class="chat-app">
                <div class="chat-sidebar">
                    <div class="chat-sidebar-header">
                        <div class="input-group">
                            <span class="input-group-text bg-light border-0"><i class="bi bi-search"></i></span>
                            <input type="text" id="contactSearchInput" class="form-control bg-light border-0" placeholder="Cercar pacients...">
                        </div>
                    </div>
                    <ul class="chat-contacts-list" id="conversations-list">
                        <div class="text-center p-5 initial-spinner">
                            <div class="spinner-border text-primary" role="status">
                                <span class="visually-hidden">Carregant...</span>
                            </div>
                        </div>
                    </ul>
                </div>

                <div class="chat-main">
                    <div id="chat-welcome-screen" class="no-chat-selected">
                        <i class="bi bi-chat-right-text"></i>
                        <h4 class="mt-3">Benvingut a la teva bústia</h4>
                        <p>Selecciona una conversa de la llista per començar a xatejar.</p>
                    </div>

                    <div id="chat-conversation-screen" class="d-none h-100 d-flex flex-column">
                        <div class="chat-header d-flex align-items-center">

                            <a class="back-to-list-btn" id="back-to-chat-list-fisio" href="#">
                                <i class="bi bi-arrow-left"></i>
                            </a>
                            <strong id="chat-with-name" class="flex-grow-1"></strong>
                            </div>
                        <div class="chat-history" id="chat-history-panel">
                            </div>

                        <div class="chat-input-area">
                            <form id="sendMessageFormFisio" class="d-flex">
                                <button type="button" class="btn btn-outline-secondary me-2" id="attach-file-btn" title="Adjuntar Imatge" disabled>
                                    <i class="bi bi-paperclip"></i>
                                </button>
                                <input type="text" id="chat-message-input" class="form-control" placeholder="Escriu un missatge..." required disabled autocomplete="off">
                                <button class="btn btn-primary" type="submit" id="sendMessageBtnFisio" disabled>
                                    <i class="bi bi-send-fill"></i>
                                </button>
                            </form>
                            <input type="file" id="image-input-file" accept="image/jpeg,image/png,image/gif" style="display: none;">
                        </div>
                        </div>
                </div>
            </div>
        </div>
    </div>
</main>

<div class="modal fade" id="imagePreviewModal" tabindex="-1" aria-labelledby="imagePreviewModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="imagePreviewModalLabel">Imatge Adjunta</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Tancar"></button>
            </div>
            <div class="modal-body text-center">
                <img src="" id="modal-preview-image" class="img-fluid" alt="Previsualització d'imatge" style="max-height: 80vh;">
            </div>
        </div>
    </div>
</div>
<?php include 'partials/footer.php'; ?>

<script>
$(document).ready(function() {
    let currentPatientId = null;
    const currentUserId = <?= $user_id ?>;
    let chatPollingInterval = null; // No implementado aún
    const POLLING_INTERVAL_MS = 15000;

    let deleteFisioChatModal = null;
    if ($('#deleteChatFisioModal').length) {
         deleteFisioChatModal = new bootstrap.Modal(document.getElementById('deleteChatFisioModal'));
    }

    // --- Inicializar Modal Imagen (sin cambios) ---
    let imagePreviewModalInstance = null;
    if ($('#imagePreviewModal').length) {
        imagePreviewModalInstance = new bootstrap.Modal(document.getElementById('imagePreviewModal'));
        $('#imagePreviewModal').on('hidden.bs.modal', function () { $(this).find('#modal-preview-image').attr('src', ''); });
    }

    // --- Funciones auxiliares (sin cambios) ---
    function escapeHtml(text) { /* ... */ if (typeof text !== 'string') return ''; const map = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#039;' }; return text.replace(/[&<>"']/g, m => map[m]); }
    function formatTime(dateTimeStr) { /* ... */ if (!dateTimeStr) return ''; try { const date = new Date(dateTimeStr.includes('Z') ? dateTimeStr : dateTimeStr.replace(' ', 'T') + 'Z'); if (isNaN(date)) return ''; return date.toLocaleTimeString('ca-ES', { hour: '2-digit', minute:'2-digit' }); } catch (e) { console.error("Error formatting date:", dateTimeStr, e); return ''; } }

    // --- ★ INICIO MODIFICACIÓN: renderMessage (para formato gris/cursiva) ---
    function renderMessage(msg) {
        const isSent = msg.from_id == currentUserId;
        const messageClass = isSent ? 'message-sent' : 'message-received';
        let bodyContent;
        let ticksHtml = '';
        const rawBody = msg.body || '';

        // 1. Comprobar si es imagen
        if (rawBody.startsWith('img:')) {
            const filename = rawBody.substring(4);
            if (filename.startsWith('(Càrrega...')) {
                bodyContent = `<p class="mb-0 text-muted"><span class="spinner-border spinner-border-sm me-2"></span>Enviant imatge...</p>`;
            } else {
                const imagePath = `chat_img/${filename}`;
                const deleteButtonHtml = isSent ? `<button class="btn btn-danger btn-sm delete-image-btn" data-message-id="${msg.id}" title="Eliminar imatge permanentment"><i class="bi bi-trash3" style="pointer-events: none;"></i></button>` : '';
                bodyContent = `<a href="#" class="chat-image-link" data-image-src="${imagePath}" title="Ampliar imatge"><img src="${imagePath}" class="chat-image-preview" alt="Imatge adjunta"/>${deleteButtonHtml}</a>`;
            }
        // 2. ★ NUEVO: Comprobar si es un mensaje de feedback con formato
        } else if (rawBody.startsWith('Sobre el ejercicio "') && rawBody.includes('\n')) {

            // Lo partimos por el primer salto de línea
            const parts = rawBody.split('\n');
            const contextLine = escapeHtml(parts[0]);
            const messageLines = escapeHtml(parts.slice(1).join('\n')).replace(/\n/g, '<br>');

            // Generamos el HTML con el formato gris/cursiva
            // (Añadimos 'mb-0' al mensaje real)
            bodyContent = `
                <p class="fst-italic text-muted" style="font-size: 0.9em; margin-bottom: 4px; opacity: 0.8;">
                    ${contextLine}
                </p>
                <p class="mb-0">${messageLines}</p>
            `;

        // 3. Mensaje de texto normal
        } else {
            bodyContent = escapeHtml(rawBody).replace(/\n/g, '<br>');
        }

        // Ticks (sin cambios)
        if (isSent) {
            let icon = 'bi-check2';
            let title = 'Enviat';
            if (msg.status === 'read') {
                icon = 'bi-check2-all text-primary';
                title = 'Llegit';
            } else if (msg.status === 'delivered') {
                icon = 'bi-check2-all';
                title = 'Entregat';
            }
            ticksHtml = `<span class="ticks ticks-${msg.status}" title="${title}"><i class="bi ${icon}"></i></span>`;
        }

        return `
            <div class="message ${messageClass}" data-message-id="${msg.id || ('temp-' + Date.now())}">
                <div class="message-body">${bodyContent}</div>
                <div class="message-meta">
                    <span class="timestamp">${formatTime(msg.created_at)}</span>
                    <span class="status-icon">${ticksHtml}</span>
                </div>
            </div>`;
    }
    // --- ★ FIN MODIFICACIÓN: renderMessage ---


    // --- loadConversations y renderConversations (sin cambios) ---
    function loadConversations() { /* ... (código igual que antes) ... */ const list = $('#conversations-list'); if (list.children(':not(.alert):not(.text-muted)').length === 0) { list.empty().html('<div class="text-center p-5 initial-spinner"><div class="spinner-border text-primary"></div></div>'); } $.getJSON('chat_inbox.php', { ajax: true, action: 'get_conversations', _: Date.now() }).done(function(response) { list.find('.initial-spinner').remove(); if (response.status === 'success' && response.conversations) { renderConversations(response.conversations); } else { list.html('<div class="text-muted text-center p-3 small">No s\'han trobat pacients amb tractaments actius.</div>'); if (!currentPatientId) { $('#chat-conversation-screen').addClass('d-none'); $('#chat-welcome-screen').removeClass('d-none'); } } }).fail(function(jqXHR) { list.find('.initial-spinner').remove(); console.error("Error al cargar conversaciones:", jqXHR.responseText); if (list.children(':not(.alert)').length === 0) { list.html('<div class="alert alert-warning m-3 small">Error en carregar les converses. <button class="btn btn-sm btn-link p-0 reload-conv-link">Reintentar</button></div>'); } else { showToast('Error en refrescar la llista.', 'danger'); } }); }
    $('#conversations-list').on('click', '.reload-conv-link', function(e){ e.preventDefault(); loadConversations(); });
    function renderConversations(conversations) { /* ... (código igual que antes) ... */ const list = $('#conversations-list'); const currentActiveId = currentPatientId; list.empty(); let activeFoundInNewList = false; if (conversations.length === 0) { list.html('<div class="text-muted text-center p-3 small">No tens pacients amb tractaments actius.</div>'); $('#chat-conversation-screen').addClass('d-none'); $('#chat-welcome-screen').removeClass('d-none'); currentPatientId = null; $('#chat-message-input, #sendMessageBtnFisio, #attach-file-btn').prop('disabled', true); return; } conversations.forEach(conv => { if(conv.id == currentActiveId) activeFoundInNewList = true; const unreadBadge = conv.unread_count > 0 ? `<span class="badge bg-danger rounded-pill unread-badge">${conv.unread_count}</span>` : ''; let lastMessageDisplay = 'Cap missatge encara...'; let lastMessageTitle = ''; if (conv.last_message === null && conv.deleted_until !== null) { lastMessageDisplay = '<i>Historial buit...</i>'; } else if (conv.last_message !== null) { if (conv.last_message.startsWith('img:')) { lastMessageDisplay = '[Imatge enviada]'; lastMessageTitle = '[Imatge enviada]'; } else { lastMessageDisplay = escapeHtml(conv.last_message); lastMessageTitle = escapeHtml(conv.last_message); } } const contactHtml = `<li class="chat-contact ${conv.id == currentActiveId ? 'active' : ''}" data-patient-id="${conv.id}" data-patient-name="${escapeHtml(conv.nombre)} ${escapeHtml(conv.apellido)}"><div class="initial-circle me-3">${escapeHtml(conv.initials)}</div><div class="contact-info"><strong>${escapeHtml(conv.apellido)}, ${escapeHtml(conv.nombre)}</strong><div class="text-muted small text-truncate last-message" title="${lastMessageTitle}">${lastMessageDisplay}</div></div><button class="btn btn-sm btn-outline-danger ms-auto me-2 delete-conversation-btn-fisio" data-patient-id="${conv.id}" title="Buidar historial de conversa" style="padding: 0.1rem 0.4rem; font-size: 0.8rem;"><i class="bi bi-trash3" style="pointer-events: none;"></i></button>${unreadBadge}</li>`; list.append(contactHtml); }); if (currentActiveId && !activeFoundInNewList) { console.log(`Patient ${currentActiveId} no longer in active list. Returning to welcome screen.`); $('#chat-conversation-screen').addClass('d-none'); $('#chat-welcome-screen').removeClass('d-none'); currentPatientId = null; $('#chat-message-input, #sendMessageBtnFisio, #attach-file-btn').prop('disabled', true); } else if (currentActiveId) { $('#chat-welcome-screen').addClass('d-none'); $('#chat-conversation-screen').removeClass('d-none'); $('#chat-message-input, #sendMessageBtnFisio, #attach-file-btn').prop('disabled', false); } }

    // --- CARGA Y RENDERIZADO DE MENSAJES (CORREGIDO) ---
    // --- ****** INICIO: CORRECCIÓN loadMessages (Fisio) ****** ---
    function loadMessages(patientId, patientName) {
        // --- 1. Caso: Clic en la conversación YA ACTIVA ---
        if (patientId === currentPatientId && $('#chat-history-panel').children(':not(.spinner-border)').length > 0) {
            console.log("loadMessages skipped: Patient already active.");
            $(`.chat-contact[data-patient-id=${patientId}]`).find('.unread-badge').remove();
            if (typeof checkUnreadMessages === 'function') {
                setTimeout(() => checkUnreadMessages(true), 100);
            }
            $('#chat-message-input').focus();

            // ★★★ AÑADIDO: Forzar modo conversación si no estaba (ej. al recargar)
            $('.chat-app').addClass('modo-conversacion');
            return;
        }

        // --- 2. Caso: Clic en una conversación NUEVA ---
        currentPatientId = patientId;

        // ★★★ AÑADIDO: Activar modo conversación en móvil ★★★
        $('.chat-app').addClass('modo-conversacion');

        $('#chat-welcome-screen').addClass('d-none');
        $('#chat-conversation-screen').removeClass('d-none');
        $('.chat-contact').removeClass('active');
        const $activeListItem = $(`.chat-contact[data-patient-id=${patientId}]`);
        if($activeListItem.length) {
             $activeListItem.addClass('active').find('.unread-badge').remove();
             if (typeof checkUnreadMessages === 'function') {
                 setTimeout(() => checkUnreadMessages(true), 100);
             }
        } else {
            console.warn(`List item for patient ${patientId} not found after click.`);
            $('#chat-conversation-screen').addClass('d-none');
            $('#chat-welcome-screen').removeClass('d-none');
            currentPatientId = null;
            $('#chat-message-input, #sendMessageBtnFisio, #attach-file-btn').prop('disabled', true);

            // ★★★ AÑADIDO: Salir del modo conversación si el paciente no existe
            $('.chat-app').removeClass('modo-conversacion');
            return;
        }

        $('#chat-with-name').text(`${patientName}`);
        const historyPanel = $('#chat-history-panel');
        historyPanel.html('<div class="text-center p-5"><div class="spinner-border text-primary"></div></div>');

        const inputElement = $('#chat-message-input');
        const sendButton = $('#sendMessageBtnFisio');
        const attachButton = $('#attach-file-btn');

        inputElement.prop('disabled', false);
        sendButton.prop('disabled', false);
        attachButton.prop('disabled', false);

        $.getJSON('chat_inbox.php', { ajax: true, action: 'get_messages', patient_id: patientId })
        .done(function(response) {
             if (patientId !== currentPatientId) return;

            if (response.status === 'success') {
                historyPanel.empty();
                if (response.messages && response.messages.length > 0) {
                    response.messages.forEach(msg => historyPanel.append(renderMessage(msg)));
                     setTimeout(() => {
                          if (historyPanel.prop("scrollHeight") > historyPanel.outerHeight()) {
                              historyPanel.scrollTop(historyPanel[0].scrollHeight);
                          }
                     }, 50);
                } else {
                    historyPanel.html('<p class="text-center text-muted mt-3">Comença a escriure per iniciar la conversa.</p>');
                }
                inputElement.focus();
                if (typeof checkUnreadMessages === 'function') {
                   setTimeout(() => checkUnreadMessages(true), 100);
                }

            } else {
                historyPanel.html('<div class="alert alert-warning m-3">No s\'ha pogut carregar l\'historial.</div>');
                 inputElement.prop('disabled', true);
                 sendButton.prop('disabled', true);
                 attachButton.prop('disabled', true);
            }
        }).fail(function(jqXHR) {
             console.error("Error al cargar mensajes:", jqXHR.responseText);
             if (patientId === currentPatientId) {
                 historyPanel.html('<div class="alert alert-danger m-3">Error de connexió.</div>');
                 inputElement.prop('disabled', true);
                 sendButton.prop('disabled', true);
                 attachButton.prop('disabled', true);
             }
        });
    } // Fin loadMessages
    // --- ****** FIN: CORRECCIÓN loadMessages (Fisio) ****** ---


    // --- MANEJADORES DE EVENTOS ---

    // Clic en conversación (sin cambios aquí, la lógica está en loadMessages)
    $('#conversations-list').on('click', '.chat-contact', function(e) {
        if ($(e.target).closest('.delete-conversation-btn-fisio').length > 0) {
            e.stopPropagation(); return;
        }
        const patientId = $(this).data('patient-id');
        const patientName = $(this).data('patient-name');
        loadMessages(patientId, patientName);
    });

    // Clic en imagen y botón borrar (sin cambios)
    $('#chat-history-panel').on('click', '.chat-image-link', function(e) { /* ... */ e.preventDefault(); e.stopPropagation(); if ($(e.target).closest('.delete-image-btn').length > 0) { return; } if (imagePreviewModalInstance) { const imageSrc = $(this).data('image-src'); if (imageSrc) { $('#modal-preview-image').attr('src', imageSrc); imagePreviewModalInstance.show(); } } });
    $('#chat-history-panel').on('click', '.delete-image-btn', function(e) { /* ... */ e.preventDefault(); e.stopPropagation(); e.stopImmediatePropagation(); if (imagePreviewModalInstance) { imagePreviewModalInstance.hide(); } const $button = $(this); const messageId = $button.data('message-id'); const $messageElement = $button.closest('.message'); if (!messageId) return; if (confirm("Estàs segur/a que vols eliminar aquesta imatge PERMANENTMENT? Aquesta acció no es pot desfer.")) { $button.prop('disabled', true).html('<i class="bi bi-arrow-repeat fa-spin"></i>'); $.post('chat_inbox.php', { ajax: true, action: 'delete_chat_message', message_id: messageId }, 'json').done(function(response) { if (response.status === 'success') { $messageElement.fadeOut(300, function() { $(this).remove(); }); if (typeof showToast === 'function') { showToast(response.message || 'Imatge eliminada.', 'success'); } } else { if (typeof showToast === 'function') { showToast(response.message || 'Error en eliminar la imatge.', 'danger'); } $button.prop('disabled', false).html('<i class="bi bi-trash3"></i>'); } }).fail(function(jqXHR) { console.error("Error al eliminar imagen:", jqXHR.responseText); let errorMsg = 'Error de connexió.'; try { const errResp = JSON.parse(jqXHR.responseText); if(errResp && errResp.message) errorMsg = errResp.message; } catch(e) {} if (typeof showToast === 'function') { showToast(errorMsg, 'danger'); } $button.prop('disabled', false).html('<i class="bi bi-trash3"></i>'); }); } });

    // Subir imagen (sin cambios)
    $('#attach-file-btn').on('click', function() { /* ... */ if (currentPatientId > 0) { $('#image-input-file').click(); } else { if (typeof showToast === 'function') { showToast("Selecciona una conversa primer.", 'warning'); } } });
    $('#image-input-file').on('change', function(e) { /* ... (código igual que antes) ... */ const file = e.target.files[0]; if (!file) return; const MAX_SIZE = 2 * 1024 * 1024; if (file.size > MAX_SIZE) { if (typeof showToast === 'function') { showToast("La imatge és massa gran (màx. 2MB).", 'danger'); } $(this).val(''); return; } if (!file.type.match('image/(jpeg|png|gif)')) { if (typeof showToast === 'function') { showToast("Només s'accepten imatges JPG, PNG o GIF.", 'danger'); } $(this).val(''); return; } const currentActivePatient = currentPatientId; const tempId = 'temp-' + Date.now(); const tempMessage = { id: tempId, from_id: currentUserId, body: `img:(Càrrega... ${file.name})`, status: 'sent', created_at: new Date().toISOString() }; const chatBody = $('#chat-history-panel'); if (chatBody.find('p.text-muted').length > 0 && chatBody.find('.message').length === 0) { chatBody.empty(); } const $newMessage = $(renderMessage(tempMessage)); chatBody.append($newMessage); chatBody.animate({ scrollTop: chatBody.prop("scrollHeight") }, 300); $('#chat-message-input, #sendMessageBtnFisio, #attach-file-btn').prop('disabled', true); const formData = new FormData(); formData.append('ajax', true); formData.append('action', 'upload_chat_image'); formData.append('patient_id', currentActivePatient); formData.append('chat_image', file); formData.append('tempId', tempId); $.ajax({ url: 'chat_inbox.php', type: 'POST', data: formData, processData: false, contentType: false, dataType: 'json' }).done(function(response) { if (response.status === 'success') { const $tempMessage = $(`div.message[data-message-id=${response.tempId}]`); if ($tempMessage.length) { const realMessage = { id: response.newId, from_id: currentUserId, body: response.body, status: 'sent', created_at: response.created_at }; $tempMessage.replaceWith(renderMessage(realMessage)); const $listItem = $(`.chat-contact[data-patient-id=${currentActivePatient}]`); if ($listItem.length > 0) { const messagePreview = "[Imatge]"; $listItem.find('.last-message').text(messagePreview).prop('title', messagePreview); $listItem.prependTo('#conversations-list'); } } } else { $(`div.message[data-message-id=${response.tempId}]`).find('.message-body').html(`<p class="mb-0 text-danger"><i class="bi bi-exclamation-triangle-fill me-2"></i> ${response.message || 'Error de càrrega.'}</p>`); if (typeof showToast === 'function') { showToast(response.message || 'Error al pujar la imatge.', 'danger'); } } }).fail((jqXHR) => { console.error("Error AJAX en upload_chat_image:", jqXHR.responseText); $(`div.message[data-message-id=${tempId}]`).find('.message-body').html('<p class="mb-0 text-danger"><i class="bi bi-exclamation-triangle-fill me-2"></i> Error de xarxa al pujar.</p>'); if (typeof showToast === 'function') { showToast('Error de connexió al servidor.', 'danger'); } }).always(() => { if (currentActivePatient === currentPatientId) { $('#chat-message-input, #sendMessageBtnFisio, #attach-file-btn').prop('disabled', false); $('#chat-message-input').focus(); } $('#image-input-file').val(''); }); });

    // Enviar mensaje (sin cambios)
    $('#sendMessageFormFisio').on('submit', function(e) { /* ... (código igual que antes) ... */ e.preventDefault(); const input = $('#chat-message-input'); const messageText = input.val().trim(); const recipientPatientId = currentPatientId; if (!messageText || !recipientPatientId) return; input.prop('disabled', true).addClass('disabled'); $('#sendMessageBtnFisio').prop('disabled', true).addClass('disabled'); $('#attach-file-btn').prop('disabled', true).addClass('disabled'); const tempTime = new Date().toISOString(); const tempMsg = { id: 'temp-' + Date.now(), from_id: currentUserId, body: messageText, status: 'sent', created_at: tempTime }; const $newMessage = $(renderMessage(tempMsg)); const historyPanel = $('#chat-history-panel'); if (historyPanel.find('p.text-muted').length > 0 && historyPanel.find('.message').length === 0) { historyPanel.empty(); } historyPanel.append($newMessage); historyPanel.animate({ scrollTop: historyPanel[0].scrollHeight }, 300); input.val(''); const $listItem = $(`.chat-contact[data-patient-id=${recipientPatientId}]`); if ($listItem.length > 0) { const escapedBody = escapeHtml(messageText); $listItem.find('.last-message').html(escapedBody).prop('title', escapedBody); $listItem.prependTo('#conversations-list'); } $.post('chat_inbox.php', { ajax: true, action: 'send_message', to_id: recipientPatientId, message: messageText }, 'json').done(function(response) { if (recipientPatientId !== currentPatientId) return; if (response.status !== 'success') { $newMessage.addClass('message-error').attr('title', response.message || 'Error'); $newMessage.find('.status-icon').html(`<i class="bi bi-exclamation-triangle-fill text-danger" title="${escapeHtml(response.message || 'Error')}"></i>`); if(response.message) showToast(response.message, 'danger'); } }).fail(function(jqXHR) { if (recipientPatientId !== currentPatientId) return; console.error("Error al enviar mensaje:", jqXHR.responseText); $newMessage.addClass('message-error').attr('title', 'Error de xarxa'); $newMessage.find('.status-icon').html('<i class="bi bi-exclamation-triangle-fill text-danger" title="Error de xarxa"></i>'); let errorMsg = 'Error de xarxa.'; try { const errResp = JSON.parse(jqXHR.responseText); if(errResp && errResp.message) errorMsg = errResp.message; } catch(e) {} showToast(errorMsg, 'danger'); }).always(function() { if (recipientPatientId === currentPatientId) { input.prop('disabled', false).removeClass('disabled').focus(); $('#sendMessageBtnFisio').prop('disabled', false).removeClass('disabled'); $('#attach-file-btn').prop('disabled', false).removeClass('disabled'); } }); });

    // Borrar conversación (Fisio) (sin cambios)
    $('#conversations-list').on('click', '.delete-conversation-btn-fisio', function(e) { /* ... */ e.stopPropagation(); const patientId = $(this).data('patient-id'); $('#deleteFisioChatPatientId').val(patientId); $('#deleteChatFisioModal .modal-body > p:first').text("Com vols buidar l'historial d'aquesta conversa?"); $('#confirmDeleteFisioChatBtn').text("Buidar Historial"); $('#deleteModeSelf').prop('checked', true); if (deleteFisioChatModal) { deleteFisioChatModal.show(); } else { console.error("Modal not found"); if (confirm("Vols buidar l'historial només per a tu?")) handleDeleteConfirmationFisio(patientId, 'self'); } });
    $(document).on('click', '#confirmDeleteFisioChatBtn', function() { /* ... */ const patientId = $('#deleteFisioChatPatientId').val(); const mode = $('input[name="deleteChatMode"]:checked').val(); handleDeleteConfirmationFisio(patientId, mode, $(this)); });
    function handleDeleteConfirmationFisio(patientId, mode, $button = null) { /* ... (código igual que antes) ... */ if (!patientId) return; const originalButtonText = $button ? $button.html() : 'Buidar Historial'; if ($button) { $button.prop('disabled', true).html('<span class="spinner-border spinner-border-sm"></span> Buidant...'); } $.post('chat_inbox.php', { ajax: true, action: 'delete_conversation', patient_id: patientId, mode: mode }, 'json').done(function(response) { if (response.status === 'success') { if (patientId == currentPatientId) { $('#chat-history-panel').html('<p class="text-center text-muted mt-3">Historial de missatges buidat. Pots continuar escrivint.</p>'); $('#chat-history-panel').scrollTop(0); } const $listItem = $(`.chat-contact[data-patient-id=${patientId}]`); if ($listItem.length > 0) { $listItem.find('.last-message').html('<i>Historial buit...</i>').prop('title', ''); } showToast(response.message || 'Historial buidat.', 'success'); if (deleteFisioChatModal) deleteFisioChatModal.hide(); } else { showToast(response.message || 'Error en buidar.', 'danger'); } }).fail((jqXHR) => { console.error("Error al buidar historial (fisio):", jqXHR.responseText); let errorMsg = 'Error de connexió.'; try { const errResp = JSON.parse(jqXHR.responseText); if(errResp && errResp.message) errorMsg = errResp.message; } catch(e) {} showToast(errorMsg, 'danger'); }).always(() => { if ($button) { $button.prop('disabled', false).html(originalButtonText); } }); }

    // Búsqueda (sin cambios)
    $('#contactSearchInput').on('keyup', function() { /* ... */ const searchTerm = $(this).val().toLowerCase(); let visibleCount = 0; $('#conversations-list .chat-contact').each(function() { const contactName = $(this).data('patient-name').toLowerCase(); const isVisible = contactName.includes(searchTerm); $(this).toggle(isVisible); if(isVisible) visibleCount++; }); $('#no-search-results-fisio').remove(); if (visibleCount === 0 && $('#conversations-list').children(':not(.text-muted):not(.alert)').length > 0) { $('#conversations-list').append('<li id="no-search-results-fisio" class="text-muted text-center p-3 small">No s\'han trobat coincidències.</li>'); } });

    // ★★★ INICIO: CÓDIGO AÑADIDO (Botón "Volver" en móvil) ★★★
    $(document).on('click', '#back-to-chat-list-fisio', function(e) {
        e.preventDefault();
        // Quitar la clase para volver a la lista
        $('.chat-app').removeClass('modo-conversacion');

        // Opcional: Deseleccionar al paciente actual y mostrar bienvenida
        currentPatientId = null;
        $('.chat-contact').removeClass('active');
        $('#chat-conversation-screen').addClass('d-none');
        $('#chat-welcome-screen').removeClass('d-none');
        $('#chat-message-input, #sendMessageBtnFisio, #attach-file-btn').prop('disabled', true);
    });
    // ★★★ FIN: CÓDIGO AÑADIDO ★★★

    // --- INICIALIZACIÓN (sin cambios) ---
    loadConversations();
     const urlParams = new URLSearchParams(window.location.search); const initialPatientId = urlParams.get('patient_id'); if (initialPatientId) { setTimeout(() => { const $initialItem = $(`.chat-contact[data-patient-id=${initialPatientId}]`); if ($initialItem.length) { console.log("Loading initial patient from URL:", initialPatientId); loadMessages(initialPatientId, $initialItem.data('patient-name')); } else { console.warn("Patient ID from URL not found in the initial list."); } }, 500); }

});
</script>

</body>
</html>
