<?php
// /treatments.php
// VERSIÓN REFACTORIZADA (Corregida para MySQL)
// v2: Logs de Tratamientos C5, C6, C7, C8 implementados

// --- 1. GESTIÓ DE SESSIÓ I DEPENDÈNCIES ---
session_start();
if (!isset($_SESSION['user_id'])) { header('Location: index.php'); exit; }
require_once 'db.php';
require_once 'mail_helpers.php'; // <-- ★★★ S'HA AFEGIT PER PODER ENVIAR EMAILS ★★★
require_once 'logger.php'; // <-- ★★★ AHORA ES FUNDAMENTAL ★★★
// ★★★ MODIFICACIÓ 1: Incloure helpers d'avatar per obtenir la constant de ruta ★★★
require_once 'avatar_helpers.php';

$user_rol = $_SESSION['user_rol'];
$user_id = $_SESSION['user_id'];
if (!defined('TREATMENTS_PER_PAGE')) {
    define('TREATMENTS_PER_PAGE', $_SESSION['records_per_page'] ?? 8);
}

// --- OBTENER PREFERENCIA DE FILTRO Y VISTA DEL USUARIO ---
$filtro_defecto = 0;
$user_view_prefs_json = '{}'; // Por defecto, un JSON vacío
if (in_array($user_rol, ['superadmin', 'fisio'])) {
    $stmt_prefs = $db->prepare("SELECT filtro_personal_defecto, vista_defecto FROM cuentas WHERE id = ?");
    $stmt_prefs->execute([$user_id]);
    if ($user_prefs = $stmt_prefs->fetch(PDO::FETCH_ASSOC)) {
        // ★★★ CORRECCIÓN 1 (Sintaxis JS): Forzar $filtro_defecto a entero
        $filtro_defecto = (int) $user_prefs['filtro_personal_defecto'];
        // treatments.php (Línea 27 CORREGIDA)
        $user_view_prefs_json = !empty($user_prefs['vista_defecto']) ? $user_prefs['vista_defecto'] : '{}';
    }
}

// --- DEFINICIÓN DE LA URL BASE DINÁMICA (Portable) ---
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
$domain_root = $protocol . $_SERVER['HTTP_HOST'];
// Esto hace que $app_base_url esté disponible para los bloques AJAX (send_treatment_notification)
$app_base_url = rtrim($domain_root . dirname($_SERVER['SCRIPT_NAME']), '/') . '/';


// --- 2. GESTOR DE PETICIONS AJAX ---
if (isset($_REQUEST['ajax'])) {
    header('Content-Type: application/json');
    $action = $_REQUEST['action'] ?? 'read';

    try {

        // --- ★ INICIO DE LA MODIFICACIÓN: COMPROBAR SI LOS EMAILS ESTÁN HABILITADOS ★ ---
        $stmt_email_check = $db->query("SELECT IS_ENABLED FROM email_settings LIMIT 1");
        // Por defecto, deshabilitado si no se encuentra la configuración o es 0
        $smtp_is_enabled = false;
        if ($stmt_email_check) {
            // (int) '1' -> 1, (int) '0' -> 0. Convertimos a booleano.
            $smtp_is_enabled = (bool) $stmt_email_check->fetchColumn();
        }
        // --- ★ FIN DE LA MODIFICACIÓN ★ ---


        // --- ★ INICIO: FUNCIONES COPIADAS DESDE ajax_handler.php ---

        function checkTreatmentPermission(PDO $db, int $treatment_id, int $user_id) {

                    // --- INICI DE LA MODIFICACIÓ ---
                    // Si l'usuari és Superadmin, no cal comprovar res més.
                    if (isset($_SESSION['user_rol']) && $_SESSION['user_rol'] === 'superadmin') {
                        return; // El Superadmin té permís
                    }
                    // --- FI DE LA MODIFICACIÓ ---

                    $stmt_check = $db->prepare(
                        "SELECT t.id FROM tratamientos t
                         LEFT JOIN tratamiento_fisios_asignados tfa ON t.id = tfa.tratamiento_id
                         WHERE t.id = :treatment_id AND (t.creator_fisio_id = :user_id OR tfa.fisio_id = :user_id)
                         GROUP BY t.id"
                    );
                    $stmt_check->execute([':treatment_id' => $treatment_id, ':user_id' => $user_id]);

                    if (!$stmt_check->fetch()) {
                        http_response_code(403); // Forbidden
                        throw new Exception("No teniu permisos per modificar aquest tractament o no existeix.");
                    }
                }

        /**
         * Calcula el percentatge d'adherència per a un tractament donat.
         */
        function calculate_adherence_percentage(int $treatment_id, PDO $db): int {
            try {
                $ex_stmt = $db->prepare("
                    SELECT te.id, te.ejercicio_id, te.frecuencia, t.start_date, t.end_date
                    FROM tratamiento_ejercicios te
                    JOIN tratamientos t ON te.tratamiento_id = t.id
                    WHERE te.tratamiento_id = ? ORDER BY te.id
                ");
                $ex_stmt->execute([$treatment_id]);
                $exercises_with_dates = $ex_stmt->fetchAll(PDO::FETCH_ASSOC);

                if (empty($exercises_with_dates)) {
                    return 0;
                }

                $treatmentDetails = [
                    'start_date' => $exercises_with_dates[0]['start_date'],
                    'end_date' => $exercises_with_dates[0]['end_date']
                ];
                $exercises = $exercises_with_dates;

                $stmt_evo = $db->prepare("
                    SELECT DISTINCT ev.fecha_realizacion, te.id as tratamiento_ejercicio_id
                    FROM tratamiento_evolucion ev
                    JOIN tratamiento_ejercicios te ON ev.tratamiento_ejercicio_id = te.id
                    WHERE te.tratamiento_id = ?
                ");
                $stmt_evo->execute([$treatment_id]);
                $all_evolution_records = $stmt_evo->fetchAll(PDO::FETCH_ASSOC);

                $evolution_map = [];
                foreach ($all_evolution_records as $rec) {
                    $evolution_map[$rec['fecha_realizacion']][$rec['tratamiento_ejercicio_id']] = true;
                }

                $total_scheduled = 0;
                $total_completed = 0;

                $loop_start_date = new DateTimeImmutable($treatmentDetails['start_date']);
                $loop_end_date = new DateTimeImmutable($treatmentDetails['end_date']);
                $today = new DateTimeImmutable('now');
                if ($loop_end_date > $today) {
                    $loop_end_date = $today;
                }

                $current_loop_date = $loop_start_date;

                while ($current_loop_date <= $loop_end_date) {
                    $dateStr = $current_loop_date->format('Y-m-d');
                    $dayOfWeek = (int)$current_loop_date->format('w'); // 0=Diumenge, 1=Dilluns...

                    foreach ($exercises as $ex) {
                        $is_scheduled = false;
                        $freq = $ex['frecuencia'];

                        if (!$freq || $freq === 'Diari') { $is_scheduled = true; }
                        else if ($freq === '3xSetmana' && in_array($dayOfWeek, [1, 3, 5])) { $is_scheduled = true; }
                        else if ($freq === '2xSetmana' && in_array($dayOfWeek, [2, 4])) { $is_scheduled = true; }
                        else if ($freq === 'Altern') {
                            $dayDiff = $loop_start_date->diff($current_loop_date)->days;
                            if ($dayDiff >= 0 && $dayDiff % 2 === 0) { $is_scheduled = true; }
                        } else {
                            $is_scheduled = true;
                        }

                        if ($is_scheduled) {
                            $total_scheduled++;
                            if (isset($evolution_map[$dateStr][$ex['id']])) {
                                $total_completed++;
                            }
                        }
                    }
                    $current_loop_date = $current_loop_date->modify('+1 day');
                }

                return ($total_scheduled > 0) ? (int)round(($total_completed / $total_scheduled) * 100) : 0;

            } catch (Exception $e) {
                error_log("Error calculant adherència per a treatment ID $treatment_id: " . $e->getMessage());
                return 0;
            }
        }
        // --- ★ FIN: FUNCIONES COPIADAS ---


        switch ($action) {

          case 'read_treatments':
                          $page = (int)($_GET['page'] ?? 1);
                          $search = $_GET['search'] ?? '';
                          $status = $_GET['status'] ?? '';
                          // ★★★ AÑADIR ESTA LÍNEA ★★★
                          $categoryId = $_GET['categoryId'] ?? '';
                          // ★★★ FIN ★★★

                          // --- ★ TAREA 2 (Default Sort) ---
                          // 1. Añadir 'created_at' a las ordenaciones válidas
                          $valid_sorts = ['start_date', 'title', 'paciente_apellido', 'status', 'creator_surname', 'collaborators', 'created_at'];
                          // 2. Cambiar el 'sort' por defecto a 'created_at'
                          $sort = in_array($_GET['sort'] ?? '', $valid_sorts) ? $_GET['sort'] : 'created_at';
                          // --- ★ FIN TAREA 2 ---

                          $order = ($_GET['order'] ?? 'DESC') === 'ASC' ? 'ASC' : 'DESC';
                          $filterMine = ($_GET['filterMine'] ?? 'false') === 'true';

                          $params = [':search' => '%' . $search . '%'];
                          $joins = "
                              JOIN cuentas p ON t.paciente_id = p.id
                              LEFT JOIN cuentas c ON t.creator_fisio_id = c.id
                          ";
                          $whereClause = "WHERE t.is_protocol = 0 AND (p.nombre LIKE :search OR p.apellido LIKE :search OR t.title LIKE :search)";

                          if (!empty($status)) {
                              $whereClause .= " AND t.status = :status";
                              $params[':status'] = $status;
                          }

                          // ★★★ AÑADIR ESTE BLOQUE ★★★
                          if (!empty($categoryId)) {
                              $whereClause .= " AND EXISTS (
                                  SELECT 1 FROM tratamiento_ejercicios te
                                  JOIN ejercicios e ON te.ejercicio_id = e.id
                                  WHERE te.tratamiento_id = t.id AND e.id_categoria = :category_id
                              )";
                              $params[':category_id'] = $categoryId;
                          }
                          // ★★★ FIN ★★★

                          if ($filterMine && in_array($user_rol, ['superadmin', 'fisio'])) {
                              $whereClause .= " AND (
                                  t.creator_fisio_id = :user_id
                                  OR EXISTS (
                                      SELECT 1 FROM tratamiento_fisios_asignados tfa
                                      WHERE tfa.tratamiento_id = t.id AND tfa.fisio_id = :user_id
                                  )
                              )";
                              $params[':user_id'] = $user_id;
                          }

                          if (in_array($user_rol, ['superadmin', 'fisio'])) {
                              $whereClause .= " AND NOT EXISTS (SELECT 1 FROM archivado_personal ap WHERE ap.item_id = t.id AND ap.item_type = 'treatment' AND ap.fisio_id = :current_fisio_id)";
                              $params[':current_fisio_id'] = $user_id;
                          }

                          $totalQuery = "SELECT COUNT(t.id) FROM tratamientos t $joins $whereClause";
                          $totalStmt = $db->prepare($totalQuery);
                          $totalStmt->execute($params);
                          $totalRecords = $totalStmt->fetchColumn();
                          $totalPages = ceil($totalRecords / TREATMENTS_PER_PAGE);

                          $offset = ($page - 1) * TREATMENTS_PER_PAGE;
                          $exerciseCountSubquery = "(SELECT COUNT(te.id) FROM tratamiento_ejercicios te JOIN ejercicios e ON te.ejercicio_id = e.id WHERE te.tratamiento_id = t.id)";

                          // --- ★ TAREA 2 (Default Sort) ---
                          // 3. Añadir 'created_at' al 'match'
                          // 4. Cambiar el 'default' a 'created_at'
                          $orderByColumn = match ($sort) {
                              'paciente_apellido' => 'LOWER(p.apellido)',
                              'title' => 'LOWER(t.title)',
                              'status' => 't.status',
                              'start_date' => 't.start_date',
                              'creator_surname' => 'LOWER(c.apellido)',
                              'collaborators' => "CASE WHEN collaborators IS NULL OR collaborators = '' THEN 1 ELSE 0 END, LOWER(collaborators)",
                              'created_at' => 't.created_at', // <-- 3. Añadido
                              default => 't.created_at', // <-- 4. Cambiado
                          };
                          // --- ★ FIN TAREA 2 ---

                          $dataQuery = "
                              SELECT t.id, t.title, t.status, t.start_date, t.end_date, t.creator_fisio_id, t.created_at,
                                     t.realizacion_percent,
                                     p.id as paciente_id, p.nombre as paciente_nombre, p.apellido as paciente_apellido,
                                     p.avatar as paciente_avatar,
                                     c.nombre as creator_fisio_name, c.apellido as creator_fisio_surname,
                                     (SELECT GROUP_CONCAT(CONCAT(colab.nombre, ' ', colab.apellido) SEPARATOR ', ')
                                      FROM tratamiento_fisios_asignados tfa
                                      JOIN cuentas colab ON tfa.fisio_id = colab.id
                                      WHERE tfa.tratamiento_id = t.id AND tfa.fisio_id != t.creator_fisio_id
                                     ) as collaborators,
                                     (SELECT GROUP_CONCAT(tfa.fisio_id)
                                      FROM tratamiento_fisios_asignados tfa
                                      WHERE tfa.tratamiento_id = t.id
                                     ) as collaborator_ids,
                                     $exerciseCountSubquery as exercise_count,
                                     (SELECT v.filename FROM tratamiento_ejercicios te JOIN ejercicios e ON te.ejercicio_id = e.id LEFT JOIN videos v ON e.id_video = v.id WHERE te.tratamiento_id = t.id ORDER BY te.orden ASC, te.id ASC LIMIT 1) as first_video_filename,
                                     (SELECT i.filename FROM tratamiento_ejercicios te JOIN ejercicios e ON te.ejercicio_id = e.id LEFT JOIN images i ON e.id_image = i.id WHERE te.tratamiento_id = t.id ORDER BY te.orden ASC, te.id ASC LIMIT 1) as first_image_filename
                              FROM tratamientos t $joins $whereClause
                              ORDER BY $orderByColumn $order
                              LIMIT :limit OFFSET :offset
                          ";

                          $dataStmt = $db->prepare($dataQuery);
                          foreach ($params as $key => $val) {
                              $dataStmt->bindValue($key, $val);
                          }
                          $dataStmt->bindValue(':limit', TREATMENTS_PER_PAGE, PDO::PARAM_INT);
                          $dataStmt->bindValue(':offset', $offset, PDO::PARAM_INT);
                          $dataStmt->execute();
                          $treatments = $dataStmt->fetchAll(PDO::FETCH_ASSOC);

                          foreach ($treatments as &$treatment) {
                              $treatment['paciente_fullname'] = $treatment['paciente_nombre'] . ' ' . $treatment['paciente_apellido'];
                              $treatment['paciente_initials'] = strtoupper(mb_substr($treatment['paciente_nombre'], 0, 1) . mb_substr($treatment['paciente_apellido'], 0, 1));
                              if ($treatment['collaborators'] === null) {
                                 $treatment['collaborators'] = '';
                              }
                          }

                          echo json_encode(['status' => 'success', 'treatments' => $treatments, 'pagination' => ['currentPage' => $page, 'totalPages' => $totalPages, 'currentSort' => $sort, 'currentOrder' => $order]]);
                          break;

            case 'personal_archive':
                if (!in_array($user_rol, ['superadmin', 'fisio'])) { throw new Exception('Accés denegat.'); }
                $stmt = $db->prepare("INSERT IGNORE INTO archivado_personal (fisio_id, item_id, item_type) VALUES (?, ?, 'treatment')");
                $stmt->execute([$user_id, (int)$_POST['id']]);
                echo json_encode(['status' => 'success', 'message' => 'Tractament arxivat correctament a la teua vista.']);
                break;

            case 'check_treatment_usage':
                $id = (int)$_GET['id'];
                $stmt = $db->prepare("SELECT status FROM tratamientos WHERE id = :id");
                $stmt->execute([':id' => $id]);
                $status = $stmt->fetchColumn();
                $is_active = $status === 'En curs';
                echo json_encode(['is_active' => $is_active]);
                break;

            case 'get_form_data':
                $pacientesStmt = $db->query("SELECT id, nombre, apellido FROM cuentas WHERE rol = 'paciente' AND is_archived = 0 ORDER BY apellido, nombre");
                $fisiosStmt = $db->query("SELECT id, nombre, apellido, rol FROM cuentas WHERE rol IN ('fisio', 'superadmin') AND is_archived = 0 ORDER BY apellido, nombre");
                echo json_encode(['status' => 'success', 'pacients' => $pacientesStmt->fetchAll(PDO::FETCH_ASSOC), 'fisios' => $fisiosStmt->fetchAll(PDO::FETCH_ASSOC)]);
                break;
                case 'get_form_data':
                $pacientesStmt = $db->query("SELECT id, nombre, apellido FROM cuentas WHERE rol = 'paciente' AND is_archived = 0 ORDER BY apellido, nombre");
                $fisiosStmt = $db->query("SELECT id, nombre, apellido, rol FROM cuentas WHERE rol IN ('fisio', 'superadmin') AND is_archived = 0 ORDER BY apellido, nombre");
                echo json_encode(['status' => 'success', 'pacients' => $pacientesStmt->fetchAll(PDO::FETCH_ASSOC), 'fisios' => $fisiosStmt->fetchAll(PDO::FETCH_ASSOC)]);
                break;

            // =======================================================
            // ===== INICIO: create_treatment (MODIFICADO) =========
            // =======================================================
            case 'create_treatment':
                $db->beginTransaction();
                if (empty($_POST['paciente_id'])) { throw new Exception('El pacient és obligatori.'); }
                $paciente_id_para_email = (int)$_POST['paciente_id']; // <-- ★ Variable para email
                if (empty($_POST['title'])) { throw new Exception('El títol és obligatori.'); }
                $titulo_para_email = $_POST['title']; // <-- ★ Variable para email
                if (empty($_POST['start_date']) || empty($_POST['end_date'])) { throw new Exception('Les dates d\'inici i fi són obligatòries.'); }
                $assignedExercisesData = json_decode($_POST['assigned_exercises'], true) ?? [];
                if (empty($assignedExercisesData)) { throw new Exception('És obligatori seleccionar almenys un exercici.'); }

                // --- ★ INICIO DE LA CORRECCIÓN DE LÓGICA ★ ---
                $startDate = $_POST['start_date'];
                $activationDate = date('Y-m-d'); // Data d'avui

                // Lógica robusta: El estado se decide SÓLO por la fecha de inicio
                if (strtotime($startDate) > strtotime($activationDate)) {
                    $status = 'Programat';
                } else {
                    $status = 'En curs';
                }
                // --- ★ FIN DE LA CORRECCIÓN DE LÓGICA ★ ---

                // ★★★ CORRECCIÓN 2 (MySQL NOW()) ★★★
                $stmt = $db->prepare("INSERT INTO tratamientos (paciente_id, creator_fisio_id, title, start_date, end_date, anamnesis, diagnostico, status, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW())");
                $stmt->execute([$paciente_id_para_email, $user_id, $titulo_para_email, $startDate, $_POST['end_date'], $_POST['anamnesis'], $_POST['diagnostico'], $status]);
                $treatmentId = $db->lastInsertId();
                if (!$treatmentId || $treatmentId == 0) { throw new Exception('Error: No s\'ha pogut crear el tractament principal.'); }

                $assignedFisios = $_POST['assigned_fisios'] ?? [];
                if (!in_array($user_id, $assignedFisios)) { $assignedFisios[] = $user_id; }

                // ★★★ CORRECCIÓN 2 (MySQL NOW()) ★★★
                $fisioStmt = $db->prepare("INSERT INTO tratamiento_fisios_asignados (tratamiento_id, fisio_id, fecha_asignacion) VALUES (?, ?, NOW())");
                foreach($assignedFisios as $fisioId) { if(!empty($fisioId)) { $fisioStmt->execute([$treatmentId, $fisioId]); } }

                $exerStmt = $db->prepare("INSERT INTO tratamiento_ejercicios (tratamiento_id, ejercicio_id, frecuencia, series, repetitions, rest_time, notes, orden) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
                                foreach($assignedExercisesData as $index => $ex) {
                                    $exerStmt->execute([$treatmentId, $ex['id'], $ex['frecuencia'], $ex['series'], $ex['repetitions'], $ex['rest_time'], $ex['notes'], $index]);
                                }


                // --- ★★★ INICIO LOG C5 (Creación) ★★★ ---
                $log_details = "Tratamiento CREADO (ID: $treatmentId) para Paciente ID: $paciente_id_para_email. Título: $titulo_para_email";
                registrar_log($db, 'TREATMENT_CREATED', $user_id, $_SESSION['user_nombre'], $log_details, $paciente_id_para_email, $treatmentId);
                // --- ★★★ FIN LOG C5 ★★★ ---

                $db->commit();

                // --- ★★★ BLOQUE DE EMAIL ELIMINADO ★★★ ---
                // El email ahora se gestiona de forma asíncrona por 'send_treatment_notification'

                // Devolvemos el new_treatment_id para que JS pueda disparar el email
                echo json_encode(['status' => 'success', 'message' => 'Tractament creat correctament.', 'new_treatment_id' => $treatmentId]);
                break;
            // =======================================================
            // ===== FIN: create_treatment (MODIFICADO) ============
            // =======================================================


            case 'check_single_exercise_data_loss':
                $treatmentId = (int)($_POST['treatment_id'] ?? 0);
                $exerciseId = (int)($_POST['exercise_id'] ?? 0);
                if ($treatmentId === 0 || $exerciseId === 0) {
                    echo json_encode(['has_data' => false]);
                    break;
                }
                $stmt = $db->prepare("
                    SELECT 1
                    FROM tratamiento_evolucion tev
                    JOIN tratamiento_ejercicios te ON tev.tratamiento_ejercicio_id = te.id
                    WHERE te.tratamiento_id = ? AND te.ejercicio_id = ?
                    LIMIT 1
                ");
                $stmt->execute([$treatmentId, $exerciseId]);
                $has_data = $stmt->fetchColumn() !== false;
                echo json_encode(['has_data' => $has_data]);
                break;

                // =======================================================
                            // ===== INICIO: update_treatment (MODIFICADO) =========
                            // =======================================================
                            case 'update_treatment':
                                $db->beginTransaction();
                                $treatmentId = (int)$_POST['id'];

                                if ($user_rol === 'fisio') {
                                    $permStmt = $db->prepare("
                                        SELECT 1 FROM tratamientos t
                                        LEFT JOIN tratamiento_fisios_asignados tfa ON t.id = tfa.tratamiento_id
                                        WHERE t.id = ? AND (t.creator_fisio_id = ? OR tfa.fisio_id = ?)
                                        LIMIT 1
                                    ");
                                    $permStmt->execute([$treatmentId, $user_id, $user_id]);
                                    if (!$permStmt->fetch()) {
                                        throw new Exception("No tens permís per a editar aquest tractament.");
                                    }
                                }

                                // --- ★ INICIO MODIFICACIÓN: Detectar cambio de paciente ---
                                // 1. Obtenemos el ID del paciente ANTIGUO antes de actualizar
                                $stmt_old_patient = $db->prepare("SELECT paciente_id FROM tratamientos WHERE id = ?");
                                $stmt_old_patient->execute([$treatmentId]);
                                $old_paciente_id = $stmt_old_patient->fetchColumn();


                                // 2. Guardamos los datos del POST en variables
                                $new_paciente_id_para_email = (int)$_POST['paciente_id'];
                                $titulo_para_email = $_POST['title'];
                                $startDate_para_email = $_POST['start_date'];

                                // 3. ★ CORRECCIÓN DE BUG: Definir $reassigned DESPUÉS de $new_paciente_id_para_email
                                $reassigned = ($old_paciente_id != $new_paciente_id_para_email && $new_paciente_id_para_email > 0);
                                // --- ★ FIN MODIFICACIÓN ---


                                // --- INICIO DE LA CORRECCIÓN DE LÓGICA (Lógica de status) ---
                                $startDate = $_POST['start_date'];
                                $activationDate = date('Y-m-d'); // Data d'avui
                                if (strtotime($startDate) > strtotime($activationDate)) {
                                    $status = 'Programat';
                                } else {
                                    $status = 'En curs';
                                }
                                // --- ★ FIN DE LA CORRECCIÓN DE LÓGICA ---

                                $query = "UPDATE tratamientos SET paciente_id=?, title=?, start_date=?, end_date=?, anamnesis=?, diagnostico=?, status=? WHERE id=?";
                                $params = [$new_paciente_id_para_email, $titulo_para_email, $startDate_para_email, $_POST['end_date'], $_POST['anamnesis'], $_POST['diagnostico'], $status, $treatmentId];
                                $stmt = $db->prepare($query);
                                $stmt->execute($params);

                                $creatorStmt = $db->prepare("SELECT creator_fisio_id FROM tratamientos WHERE id = ?");
                                $creatorStmt->execute([$treatmentId]);
                                $creator_id = $creatorStmt->fetchColumn();

                                if ($user_rol === 'superadmin' || $user_id == $creator_id) {
                                    $db->prepare("DELETE FROM tratamiento_fisios_asignados WHERE tratamiento_id = ?")->execute([$treatmentId]);
                                    $assignedFisios = $_POST['assigned_fisios'] ?? [];
                                    if ($creator_id && !in_array($creator_id, $assignedFisios)) {
                                        $assignedFisios[] = $creator_id;
                                    }
                                    $fisioStmt = $db->prepare("INSERT INTO tratamiento_fisios_asignados (tratamiento_id, fisio_id, fecha_asignacion) VALUES (?, ?, NOW())");
                                    foreach($assignedFisios as $fisioId) {
                                        if(!empty($fisioId)) $fisioStmt->execute([$treatmentId, $fisioId]);
                                    }
                                }

                                // --- ======================================================= ---
                                // --- ★★★ INICIO DE LA MODIFICACIÓN (GUARDAR ORDEN) ★★★ ---
                                // --- ======================================================= ---
                                // La lógica anterior (diff/intersect) era eficiente pero no guardaba el orden.
                                // La reemplazamos por la lógica de "borrar y re-insertar",
                                // que es la única forma de reordenar los IDs (ya que el orden depende de 'te.id').
                                // --> CORRECCIÓN: Esta lógica es incorrecta y borra datos.
                                // --> APLICAMOS LA LÓGICA CORRECTA QUE NO BORRA DATOS DE EVOLUCIÓN.

                                $newExercisesData = json_decode($_POST['assigned_exercises'], true) ?? [];
                                if (empty($newExercisesData)) { throw new Exception('És obligatori seleccionar almenys un exercici.'); }

                                $newExerciseIds = []; // Array simple de IDs [23, 12, 55]
                                $newExerciseMap = []; // Mapa de [id => pauta]
                                foreach ($newExercisesData as $ex) {
                                    $newExerciseIds[] = (int)$ex['id'];
                                    $newExerciseMap[(int)$ex['id']] = $ex; // Guardar la pauta
                                }

                                // 1. Obtener ejercicios actuales de la BBDD
                                $stmtCurrent = $db->prepare("SELECT ejercicio_id FROM tratamiento_ejercicios WHERE tratamiento_id = ?");
                                $stmtCurrent->execute([$treatmentId]);
                                $currentExerciseIds = $stmtCurrent->fetchAll(PDO::FETCH_COLUMN); // [12, 23, 99]

                                // 2. Identificar cambios
                                $idsToDelete = array_diff($currentExerciseIds, $newExerciseIds); // [99]
                                $idsToAdd = array_diff($newExerciseIds, $currentExerciseIds); // [55]
                                $idsToKeep = array_intersect($currentExerciseIds, $newExerciseIds); // [12, 23]

                                // 3. Borrar los que ya no están (Esto asume que el JS ha advertido de la pérdida de datos de evolución)
                                if (!empty($idsToDelete)) {
                                    $deletePlaceholders = implode(',', array_fill(0, count($idsToDelete), '?'));
                                    $stmtDelete = $db->prepare("DELETE FROM tratamiento_ejercicios WHERE tratamiento_id = ? AND ejercicio_id IN ($deletePlaceholders)");
                                    $stmtDelete->execute(array_merge([$treatmentId], $idsToDelete));
                                }

                                // 4. Añadir los nuevos (con el 'orden' correcto)
                                if (!empty($idsToAdd)) {
                                    $addStmt = $db->prepare("INSERT INTO tratamiento_ejercicios (tratamiento_id, ejercicio_id, frecuencia, series, repetitions, rest_time, notes, orden) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
                                    foreach ($newExerciseIds as $index => $exId) { // Recorrer la *nueva* lista ordenada
                                        if (in_array($exId, $idsToAdd)) {
                                            $ex = $newExerciseMap[$exId];
                                            $addStmt->execute([$treatmentId, $ex['id'], $ex['frecuencia'], $ex['series'], $ex['repetitions'], $ex['rest_time'], $ex['notes'], $index]);
                                        }
                                    }
                                }

                                // 5. Actualizar el ORDEN y la PAUTA de los que se quedan
                                if (!empty($idsToKeep)) {
                                    $updateStmt = $db->prepare("UPDATE tratamiento_ejercicios SET frecuencia=?, series=?, repetitions=?, rest_time=?, notes=?, orden=? WHERE tratamiento_id = ? AND ejercicio_id = ?");
                                    foreach ($newExerciseIds as $index => $exId) { // Recorrer la *nueva* lista ordenada
                                        if (in_array($exId, $idsToKeep)) {
                                            $ex = $newExerciseMap[$exId];
                                            $updateStmt->execute([$ex['frecuencia'], $ex['series'], $ex['repetitions'], $ex['rest_time'], $ex['notes'], $index, $treatmentId, $ex['id']]);
                                        }
                                    }
                                }
                                // --- ======================================================= ---
                                // --- ★★★ FIN DE LA MODIFICACIÓN ★★★ ---
                                // --- ======================================================= ---


                                // --- ★★★ BLOQUE DE EMAIL ELIMINADO ★★★ ---
                                // El email de reasignación ahora se gestiona de forma asíncrona

                                $db->commit();

                                // --- ★★★ INICIO LOG C6 (Actualización) ★★★ ---
                                $log_details_update = "Tratamiento ACTUALIZADO (ID: $treatmentId) para Paciente ID: $new_paciente_id_para_email. Título: $titulo_para_email";
                                registrar_log($db, 'TREATMENT_UPDATED', $user_id, $_SESSION['user_nombre'], $log_details_update, $new_paciente_id_para_email, $treatmentId);
                                // --- ★★★ FIN LOG C6 ★★★ ---

                                // ★ CORRECCIÓN DE BUG: Arreglar la línea 'echo' rota
                                $response = ['status' => 'success', 'message' => 'Tractament actualitzat correctament.'];
                                if ($reassigned) {
                                    $response['reassigned_treatment_id'] = $treatmentId;
                                }
                                echo json_encode($response);
                                break;
                            // =======================================================
                            // ===== FIN: update_treatment (MODIFICADO) ============
                            // =======================================================

                            case 'get_treatment_details':
                                            $id = (int)$_GET['id'];
                                            // ★★★ CORRECCIÓN 4 (MySQL CONCAT) ★★★
                                            $query = "SELECT t.*, p.nombre as paciente_nombre, p.apellido as paciente_apellido,
                                                             c.nombre as creator_fisio_name, c.apellido as creator_fisio_surname,
                                                             (SELECT GROUP_CONCAT(CONCAT(colab.nombre, ' ', colab.apellido) SEPARATOR ', ')
                                                              FROM tratamiento_fisios_asignados tfa
                                                              JOIN cuentas colab ON tfa.fisio_id = colab.id
                                                              WHERE tfa.tratamiento_id = t.id AND tfa.fisio_id != t.creator_fisio_id
                                                             ) as collaborators
                                                       FROM tratamientos t
                                                       JOIN cuentas p ON t.paciente_id = p.id
                                                       LEFT JOIN cuentas c ON t.creator_fisio_id = c.id
                                                       WHERE t.id = ?";
                                            $stmt = $db->prepare($query);
                                            $stmt->execute([$id]);
                                            $treatment = $stmt->fetch(PDO::FETCH_ASSOC);
                                            if(!$treatment) throw new Exception("Tractament no trobat.");
                                            $stmtFisios = $db->prepare("SELECT fisio_id FROM tratamiento_fisios_asignados WHERE tratamiento_id = ?");
                                            $stmtFisios->execute([$id]);
                                            $treatment['assigned_fisios'] = $stmtFisios->fetchAll(PDO::FETCH_COLUMN);

                                            // --- ======================================================= ---
                                            // --- ★★★ INICIO DE LA MODIFICACIÓN (ORDENAR EJERCICIOS) ★★★ ---
                                            // --- ======================================================= ---
                                            $stmtExercises = $db->prepare("
                                                SELECT e.*, v.filename as video_filename, i.filename as image_filename, te.frecuencia, te.series, te.repetitions, te.rest_time, te.notes as pauta_notes
                                                FROM tratamiento_ejercicios te
                                                JOIN ejercicios e ON te.ejercicio_id = e.id
                                                LEFT JOIN videos v ON e.id_video = v.id
                                                LEFT JOIN images i ON e.id_image = i.id
                                                WHERE te.tratamiento_id = ? ORDER BY te.orden ASC, te.id ASC
                                            ");
                                            // --- ======================================================= ---
                                            // --- ★★★ FIN DE LA MODIFICACIÓN ★★★ ---
                                            // --- ======================================================= ---

                                            $stmtExercises->execute([$id]);
                                            $treatment['assigned_exercises'] = $stmtExercises->fetchAll(PDO::FETCH_ASSOC);
                                             if ($treatment['collaborators'] === null) {
                                                $treatment['collaborators'] = '';
                                             }
                                            echo json_encode(['status' => 'success', 'treatment' => $treatment]);
                                            break;

            // =======================================================
            // ===== INICIO: clone_treatment (MODIFICADO) ==========
            // =======================================================
            case 'clone_treatment':
                $originalTreatmentId = (int)$_POST['original_treatment_id'];
                $newPacienteId = (int)$_POST['paciente_id'];
                $newTitle = $_POST['title'];
                // [MYSQL CORREGIDO] Ya no usamos NOW() aquí
                $db->beginTransaction();

                // --- ★ TAREA 3: Pedimos también la fecha de creación original ---
                $stmtOrig = $db->prepare("SELECT *, created_at as original_created_at FROM tratamientos WHERE id = ?");
                $stmtOrig->execute([$originalTreatmentId]);
                $originalTreatment = $stmtOrig->fetch(PDO::FETCH_ASSOC);
                if (!$originalTreatment) { throw new Exception("El tractament original no existeix."); }

                // --- ★ TAREA 3: [MYSQL CORREGIDO] Usamos DATE_ADD() para sumar 1 segundo a la fecha original ---
                $stmtNew = $db->prepare("
                    INSERT INTO tratamientos (paciente_id, creator_fisio_id, title, start_date, end_date, anamnesis, diagnostico, status, created_at)
                    VALUES (?, ?, ?, ?, ?, ?, ?, 'Programat', DATE_ADD(?, INTERVAL 1 SECOND))
                ");
                $stmtNew->execute([
                    $newPacienteId,
                    $user_id,
                    $newTitle,
                    $originalTreatment['start_date'],
                    $originalTreatment['end_date'],
                    $originalTreatment['anamnesis'],
                    $originalTreatment['diagnostico'],
                    $originalTreatment['original_created_at'] // <-- Pasamos la fecha original
                ]);

                $newTreatmentId = $db->lastInsertId();
                $stmtFisio = $db->prepare("INSERT INTO tratamiento_fisios_asignados (tratamiento_id, fisio_id) VALUES (?, ?)");
                $stmtFisio->execute([$newTreatmentId, $user_id]);
                $stmtExerOrig = $db->prepare("SELECT * FROM tratamiento_ejercicios WHERE tratamiento_id = ?");
                $stmtExerOrig->execute([$originalTreatmentId]);
                $originalExercises = $stmtExerOrig->fetchAll();
                $stmtExerNew = $db->prepare("INSERT INTO tratamiento_ejercicios (tratamiento_id, ejercicio_id, frecuencia, series, repetitions, rest_time, notes) VALUES (?, ?, ?, ?, ?, ?, ?)");
                foreach ($originalExercises as $ex) {
                    $stmtExerNew->execute([$newTreatmentId, $ex['ejercicio_id'], $ex['frecuencia'], $ex['series'], $ex['repetitions'], $ex['rest_time'], $ex['notes']]);
                }

                // --- ★★★ BLOQUE DE EMAIL ELIMINADO ★★★ ---
                // El email ahora se gestiona de forma asíncrona por 'send_treatment_notification'

                // --- ★★★ INICIO LOG C5 (Clonación) ★★★ ---
                $log_details_clone = "Tratamiento CREADO por CLONACIÓN (Nuevo ID: $newTreatmentId) desde (ID: $originalTreatmentId). Asignado a Paciente ID: $newPacienteId. Título: $newTitle";
                registrar_log($db, 'TREATMENT_CREATED', $user_id, $_SESSION['user_nombre'], $log_details_clone, $newPacienteId, $newTreatmentId);
                // --- ★★★ FIN LOG C5 ★★★ ---

                $db->commit();
                // Devolvemos el new_treatment_id para que JS pueda disparar el email
                echo json_encode([
                    'status' => 'success',
                    'message' => 'Tractament clonat correctament.',
                    'new_treatment_id' => $newTreatmentId
                ]);
                break;
            // =======================================================
            // ===== FIN: clone_treatment (MODIFICADO) =============
            // =======================================================


            case 'delete_treatment':
                $id = (int)$_POST['id'];

                $stmtUsage = $db->prepare("SELECT status FROM tratamientos WHERE id = ?");
                $stmtUsage->execute([$id]);
                $currentStatus = $stmtUsage->fetchColumn();
                if ($currentStatus === 'En curs') {
                    throw new Exception("El tractament està 'En curs' i no es pot eliminar directament. Marca'l com a 'Completat' o 'Omés' primer.");
                }

                $db->beginTransaction();
                try {
                    $query = "DELETE FROM tratamientos WHERE id = ?";
                    $params = [$id];
                    if ($user_rol !== 'superadmin') {
                        $stmtCheckCreator = $db->prepare("SELECT 1 FROM tratamientos WHERE id = ? AND creator_fisio_id = ?");
                        $stmtCheckCreator->execute([$id, $user_id]);
                        if (!$stmtCheckCreator->fetch()) {
                            throw new Exception('No tens permís per a eliminar este tractament (només el creador o superadmin poden).');
                        }
                        $query .= " AND creator_fisio_id = ?";
                        $params[] = $user_id;
                    }
                    $stmt = $db->prepare($query);
                    $stmt->execute($params);

                    if ($stmt->rowCount() === 0 && $user_rol !== 'superadmin') {
                        throw new Exception('No s\'ha trobat el tractament o no tens permís.');
                    } elseif ($stmt->rowCount() === 0 && $user_rol === 'superadmin') {
                         throw new Exception('No s\'ha trobat el tractament amb l\'ID proporcionat.');
                    }

                    $stmtDeleteExercises = $db->prepare("DELETE FROM tratamiento_ejercicios WHERE tratamiento_id = ?");
                    $stmtDeleteExercises->execute([$id]);
                    $stmtDeleteFisios = $db->prepare("DELETE FROM tratamiento_fisios_asignados WHERE tratamiento_id = ?");
                    $stmtDeleteFisios->execute([$id]);

                    // --- ★★★ INICIO LOG C7 (Eliminación) ★★★ ---
                    $log_details_delete = "Tratamiento ELIMINADO (ID: $id).";
                    // El target_object_id es el ID del tratamiento eliminado.
                    registrar_log($db, 'TREATMENT_DELETED', $user_id, $_SESSION['user_nombre'], $log_details_delete, null, $id);
                    // --- ★★★ FIN LOG C7 ★★★ ---

                    $db->commit();
                    echo json_encode(['status' => 'success', 'message' => 'Tractament i les seves associacions eliminats correctament.']);

                } catch (Exception $e) {
                    $db->rollBack();
                    throw $e;
                }
                break;

            // =======================================================
            // ===== INICIO: set_manual_status (MODIFICADO) ========
            // =======================================================
            case 'set_manual_status':
                if (!in_array($user_rol, ['superadmin', 'fisio'])) { throw new Exception('Accés denegat.'); }
                $id = (int)$_POST['id'];
                $finalStatus = $_POST['status'];
                if (!in_array($finalStatus, ['Completat', 'Omés'])) { throw new Exception('Estat final no vàlid.'); }

                $realizacion_percent_value = null;

                if ($finalStatus === 'Omés') {
                    $realizacion_percent_value = 0;
                } else if ($finalStatus === 'Completat') {
                    $stmt_details = $db->prepare("SELECT start_date, end_date FROM tratamientos WHERE id = ?");
                    $stmt_details->execute([$id]);
                    $treatmentDetails = $stmt_details->fetch(PDO::FETCH_ASSOC);

                    if ($treatmentDetails) {
                        $realizacion_percent_value = calculate_adherence_percentage($id, $db);
                    }
                }

                $stmt = $db->prepare("UPDATE tratamientos SET status = ?, realizacion_percent = ? WHERE id = ?");
                $stmt->execute([$finalStatus, $realizacion_percent_value, $id]);

                // --- ★★★ BLOQUE DE EMAIL ELIMINADO ★★★ ---
                // El email ahora se gestiona de forma asíncrona por 'send_treatment_notification'

                // Devolvemos los IDs para que JS pueda disparar el email
                echo json_encode([
                    'status' => 'success',
                    'message' => 'L\'estat del tractament s\'ha actualitzat.',
                    'treatment_id' => $id,
                    'new_status' => $finalStatus
                ]);
                break;
            // =======================================================
            // ===== FIN: set_manual_status (MODIFICADO) ===========
            // =======================================================


            case 'reactivate_treatment':
                if (!in_array($user_rol, ['superadmin', 'fisio'])) { throw new Exception('Accés denegat.'); }
                $id = (int)$_POST['id'];
                $stmt = $db->prepare("SELECT start_date FROM tratamientos WHERE id = ?");
                $stmt->execute([$id]);
                $startDate = $stmt->fetchColumn();
                $newStatus = (strtotime($startDate) > strtotime(date('Y-m-d'))) ? 'Programat' : 'En curs';

                $stmtUpdate = $db->prepare("UPDATE tratamientos SET status = ?, realizacion_percent = NULL WHERE id = ?");
                $stmtUpdate->execute([$newStatus, $id]);

                // --- ★ INICIO DE LA MODIFICACIÓN ★ ---
                // Devolvemos el ID y una acción para que el JS sepa qué hacer
                echo json_encode([
                    'status' => 'success',
                    'message' => 'Tractament reactivat correctament.',
                    'action' => 'reactivated',
                    'treatment_id' => $id
                ]);
                // --- ★ FIN DE LA MODIFICACIÓN ★ ---
                break;

            case 'extend_treatment_duration':
                if (!isset($_POST['treatment_id']) || !is_numeric($_POST['treatment_id'])) {
                    throw new Exception("ID de tractament no vàlid.");
                }
                if (!isset($_POST['days_to_extend']) || !is_numeric($_POST['days_to_extend']) || $_POST['days_to_extend'] <= 0) {
                    throw new Exception("Nombre de dies no vàlid.");
                }
                $treatment_id = (int)$_POST['treatment_id'];
                $days_to_extend = (int)$_POST['days_to_extend'];

                // ★★★ CORRECCIÓN 6 (MySQL DATE_ADD) ★★★
                $days_modifier_str = (string)$days_to_extend;

                checkTreatmentPermission($db, $treatment_id, $user_id);

                $stmt_update = $db->prepare(
                    "UPDATE tratamientos
                     SET end_date = DATE_ADD(end_date, INTERVAL :days_modifier DAY)
                     WHERE id = :treatment_id"
                );
                $stmt_update->execute([
                    ':days_modifier' => $days_modifier_str,
                    ':treatment_id' => $treatment_id
                ]);

                if ($stmt_update->rowCount() > 0) {
                    $stmt_get_new_date = $db->prepare("SELECT end_date FROM tratamientos WHERE id = ?");
                    $stmt_get_new_date->execute([$treatment_id]);
                    $new_end_date_db = $stmt_get_new_date->fetchColumn();
                    $new_end_date_formatted = date('d/m/Y', strtotime($new_end_date_db));

                    echo json_encode([
                        'status' => 'success',
                        'message' => 'Tractament ampliat.',
                        'new_end_date' => $new_end_date_formatted
                    ]);
                } else {
                    throw new Exception("No s'ha pogut ampliar el tractament.");
                }
                break;

                // --- ★★★ INICIO NUEVA ACCIÓN: TRANSFER_TREATMENT (CON EMAIL) ★★★ ---
                            case 'transfer_treatment':
                                if ($user_rol !== 'superadmin') {
                                    throw new Exception('Accés denegat. Només els Superadmins poden transferir tractaments.');
                                }

                                $treatment_id = (int)($_POST['treatment_id'] ?? 0);
                                $new_fisio_id = (int)($_POST['new_fisio_id'] ?? 0);

                                if ($treatment_id === 0 || $new_fisio_id === 0) {
                                    throw new Exception("ID de tractament o de fisio no vàlids.");
                                }

                                $db->beginTransaction();

                                // 1. Obtener el fisio creador actual
                                $stmt_get_old = $db->prepare("SELECT creator_fisio_id FROM tratamientos WHERE id = ?");
                                $stmt_get_old->execute([$treatment_id]);
                                $old_creator_id = $stmt_get_old->fetchColumn();

                                if (!$old_creator_id) {
                                    throw new Exception("No s'ha trobat el tractament.");
                                }

                                // 2. Actualizar el creador (propietario) del tratamiento
                                $stmt_update = $db->prepare("UPDATE tratamientos SET creator_fisio_id = ? WHERE id = ?");
                                $stmt_update->execute([$new_fisio_id, $treatment_id]);

                                // 3. Añadir al antiguo creador como colaborador (si no es él mismo)
                                if ($old_creator_id != $new_fisio_id) {
                                    $stmt_add_old = $db->prepare("INSERT IGNORE INTO tratamiento_fisios_asignados (tratamiento_id, fisio_id, fecha_asignacion) VALUES (?, ?, NOW())");
                                    $stmt_add_old->execute([$treatment_id, $old_creator_id]);
                                }

                                // 4. Asegurarse de que el nuevo creador también esté en la tabla de asignados
                                $stmt_add_new = $db->prepare("INSERT IGNORE INTO tratamiento_fisios_asignados (tratamiento_id, fisio_id, fecha_asignacion) VALUES (?, ?, NOW())");
                                $stmt_add_new->execute([$treatment_id, $new_fisio_id]);

                                // --- ======================================================= ---
                                // --- ★★★ INICIO DE LA MODIFICACIÓN (BLOQUE DE EMAIL ELIMINADO) ★★★ ---
                                // --- ======================================================= ---

                                // El bloque de envío de email síncrono que estaba aquí (líneas 667-730)
                                // ha sido eliminado. La notificación ahora se disparará desde el
                                // JavaScript (línea 1205) usando la acción 'send_treatment_notification',
                                // la cual SÍ comprueba el interruptor 'treatment_transferred'.

                                // --- ======================================================= ---
                                // --- ★★★ FIN DE LA MODIFICACIÓN ★★★ ---
                                // --- ======================================================= ---

                                // --- ★★★ INICIO LOG C8 (Transferencia) ★★★ ---
                                $log_details_transfer = "Tratamiento TRANSFERIDO (ID: $treatment_id). Propietario anterior: $old_creator_id. Nuevo propietario: $new_fisio_id.";
                                registrar_log($db, 'TREATMENT_TRANSFERRED', $user_id, $_SESSION['user_nombre'], $log_details_transfer, $new_fisio_id, $treatment_id);
                                // --- ★★★ FIN LOG C8 ★★★ ---

                                $db->commit();

                                echo json_encode(['status' => 'success', 'message' => 'Tractament transferit correctament.']);
                                break;
                            // --- ★★★ FIN NUEVA ACCIÓN: TRANSFER_TREATMENT (CON EMAIL) ★★★ ---

            case 'send_treatment_notification':
                // *** NOTA: $app_base_url está disponible gracias a la definición global al inicio del script. ***
                if (!$smtp_is_enabled) {
                    echo json_encode(['status' => 'success', 'message' => 'SMTP deshabilitado, email no enviado.']);
                    exit;
                }

                $treatment_id = (int)($_POST['treatment_id'] ?? 0);
                $type = $_POST['type'] ?? 'new_treatment';

                if ($treatment_id === 0) {
                    throw new Exception('ID de tratamiento no proporcionado para el email.');
                }

                // --- LÓGICA DE LOS TOGGLES ---
                $email_on_assign = false;
                $email_on_complete = false;
                // --- ★★★ MODIFICACIÓN: La variable debe existir ★★★ ---
                $email_on_transfer = false;
                // --- ★★★ FIN MODIFICACIÓN ★★★ ---
                try {
                    $stmt_settings = $db->query("SELECT setting_name, is_enabled FROM email_settings");
                    while ($setting = $stmt_settings->fetch(PDO::FETCH_ASSOC)) {
                        if ($setting['setting_name'] === 'new_treatment_assigned') {
                            $email_on_assign = (bool)$setting['is_enabled'];
                        }
                        if ($setting['setting_name'] === 'treatment_finished') {
                            $email_on_complete = (bool)$setting['is_enabled'];
                        }
                        if ($setting['setting_name'] === 'treatment_transferred') {
                            $email_on_transfer = (bool)$setting['is_enabled'];
                        }
                    }
                } catch (Exception $e) {
                     error_log("Error al leer email_settings: " . $e->getMessage());
                }

                if (in_array($type, ['new_treatment', 'clone', 'reassign']) && !$email_on_assign) {
                    echo json_encode(['status' => 'success', 'message' => 'Email de asignación desactivado por el admin.']);
                    exit;
                }
                if (in_array($type, ['complete', 'omit']) && !$email_on_complete) {
                    echo json_encode(['status' => 'success', 'message' => 'Email de finalización desactivado por el admin.']);
                    exit;
                }
                if ($type === 'transfer' && !$email_on_transfer) {
                    echo json_encode(['status' => 'success', 'message' => 'Email de transferencia desactivado por el admin.']);
                    exit;
                }
                // --- FIN LÓGICA DE TOGGLES ---

                try {
                    // Obtener datos básicos (para la mayoría de emails)
                    $stmt_data = $db->prepare("
                        SELECT t.title, t.start_date, t.status,
                               c.email as paciente_email, c.nombre as paciente_nombre
                        FROM tratamientos t
                        JOIN cuentas c ON t.paciente_id = c.id
                        WHERE t.id = ?
                    ");
                    $stmt_data->execute([$treatment_id]);
                    $data = $stmt_data->fetch();

                    // --- ★★★ MODIFICACIÓN: $data puede ser 'false' si el type es 'transfer' ★★★ ---
                    if (!$data && $type !== 'transfer') {
                    // --- ★★★ FIN MODIFICACIÓN ★★★ ---
                        throw new Exception('Datos no encontrados para enviar email.');
                    }

                    // Definir imagen
                    $logo_path = __DIR__ . '/logos/img_defecte.png';
                    $embedded_logo = [['path' => $logo_path, 'cid' => 'logo_avant']];
                    $body_paciente = "";
                    $subject_paciente = "";
                    // --- ★★★ MODIFICACIÓN: $email_recipient puede cambiar ★★★ ---
                    $email_recipient = $data['paciente_email'] ?? ''; // Por defecto se envía al paciente
                    // --- ★★★ FIN MODIFICACIÓN ★★★ ---

                    if (in_array($type, ['new_treatment', 'clone', 'reassign'])) {
                        // --- Email para PACIENTE (Asignación) ---
                        $subject_paciente = "T'han assignat un nou tractament!";
                        $status_text = ($data['status'] === 'Programat' ? "no podràs començar fins a la data d'inici." : "ja pots començar hui mateix.");
                        $body_paciente = "
                        <div style='font-family: Arial, sans-serif; line-height: 1.6; max-width: 600px; margin: auto; padding: 20px; border: 1px solid #ddd; border-radius: 8px;'>
                            <div style='text-align: center; margin-bottom: 20px;'>
                                <img src='cid:logo_avant' alt='Logo de la Clínica' style='width: 250px; height: auto;'>
                            </div>
                            <h1 style='color: #333; text-align: center; font-size: 24px;'>Hola, " . htmlspecialchars($data['paciente_nombre']) . "!</h1>
                            <p>El teu fisioterapeuta t'ha assignat un nou tractament a la plataforma AVANT ONLINE.</p>
                            <ul style='list-style-type: none; padding-left: 0; background-color: #f9f9f9; border: 1px solid #eee; padding: 15px; border-radius: 5px;'>
                                <li><strong>Tractament:</strong> " . htmlspecialchars($data['title']) . "</li>
                                <li><strong>Data d'inici:</strong> " . htmlspecialchars(date('d/m/Y', strtotime($data['start_date']))) . "</li>
                            </ul>
                            <p>Recorda que " . $status_text . "</p>
                            <p style='text-align: center; margin-top: 30px;'>
                                <a href='" . $app_base_url . "patient_dashboard.php' style='background-color: #0d6efd; color: white; padding: 12px 20px; text-decoration: none; border-radius: 5px; font-weight: bold;'>
                                    Accedir al Meu Portal
                                </a>
                            </p>
                        </div>
                        ";

                    } elseif ($type === 'complete' || $type === 'omit') {
                        // --- Email para PACIENTE (Finalización) ---
                        $finalStatus = ($type === 'complete') ? 'Completat' : 'Omés';
                        $status_text = ($finalStatus === 'Completat') ? 'ha sigut marcat com a "Completat"' : 'ha sigut marcat com a "Omés"';
                        $subject_paciente = "El teu tractament ha finalitzat";
                        $body_paciente = "
                        <div style='font-family: Arial, sans-serif; line-height: 1.6; max-width: 600px; margin: auto; padding: 20px; border: 1px solid #ddd; border-radius: 8px;'>
                            <div style='text-align: center; margin-bottom: 20px;'>
                                <img src='cid:logo_avant' alt='Logo de la Clínica' style='width: 250px; height: auto;'>
                            </div>
                            <h1 style='color: #333; text-align: center; font-size: 24px;'>Hola, " . htmlspecialchars($data['paciente_nombre']) . "!</h1>
                            <p>T'informem que el teu tractament a AVANT ONLINE anomenat <strong>\"" . htmlspecialchars($data['title']) . "\"</strong> " . $status_text . ".</p>
                            " . ($finalStatus === 'Completat' ? "<p>Enhorabona per completar la teua pauta d'exercicis!</p>" : "<p>Aquest tractament ja no apareixerà com a actiu.</p>") . "
                            <p>Pots consultar-lo en qualsevol moment des de l'historial del teu portal.</p>
                            <p style='text-align: center; margin-top: 30px;'>
                                <a href='" . $app_base_url . "patient_dashboard.php' style='background-color: #0d6efd; color: white; padding: 12px 20px; text-decoration: none; border-radius: 5px; font-weight: bold;'>
                                    Accedir al Meu Portal
                                </a>
                            </p>
                        </div>
                        ";

                    // --- ★★★ INICIO: NUEVO BLOQUE 'ELSEIF' PARA TRANSFERENCIA ★★★ ---
                    } elseif ($type === 'transfer') {
                        // --- Email para NUEVO FISIO (Transferencia) ---
                        // 1. Obtener los datos necesarios para este email
                        $stmt_transfer_data = $db->prepare("
                            SELECT
                                t.title as treatment_title,
                                p.nombre as patient_nombre, p.apellido as patient_apellido,
                                new_fisio.email as new_fisio_email, new_fisio.nombre as new_fisio_nombre,
                                (SELECT c.nombre FROM log_auditoria l JOIN cuentas c ON l.actor_user_id = c.id WHERE l.target_object_id = t.id AND l.action = 'TREATMENT_TRANSFERRED' ORDER BY l.timestamp DESC LIMIT 1) as old_fisio_nombre,
                                (SELECT c.apellido FROM log_auditoria l JOIN cuentas c ON l.actor_user_id = c.id WHERE l.target_object_id = t.id AND l.action = 'TREATMENT_TRANSFERRED' ORDER BY l.timestamp DESC LIMIT 1) as old_fisio_apellido
                            FROM tratamientos t
                            JOIN cuentas p ON t.paciente_id = p.id
                            JOIN cuentas new_fisio ON t.creator_fisio_id = new_fisio.id
                            WHERE t.id = :treatment_id
                        ");

                        $stmt_transfer_data->execute([':treatment_id' => $treatment_id]);
                        $transfer_data = $stmt_transfer_data->fetch();

                        if ($transfer_data) {
                            $email_recipient = $transfer_data['new_fisio_email']; // Cambiamos el destinatario
                            $subject_paciente = "T'han transferit un tractament"; // (Reutilizamos la variable)
                            $body_paciente = "
                            <div style='font-family: Arial, sans-serif; line-height: 1.6; max-width: 600px; margin: auto; padding: 20px; border: 1px solid #ddd; border-radius: 8px;'>
                                <div style='text-align: center; margin-bottom: 20px;'>
                                    <img src='cid:logo_avant' alt='Logo de la Clínica' style='width: 250px; height: auto;'>
                                </div>
                                <h1 style='color: #333; text-align: center; font-size: 24px;'>Hola, " . htmlspecialchars($transfer_data['new_fisio_nombre']) . "!</h1>
                                <p>Se t'ha transferit la propietat d'un tractament a AVANT ONLINE.</p>
                                <p>Ara ets el fisioterapeuta principal d'aquest tractament i rebràs les seves notificacions.</p>
                                <ul style='list-style-type: none; padding-left: 0; background-color: #f9f9f9; border: 1px solid #eee; padding: 15px; border-radius: 5px;'>
                                    <li><strong>Tractament:</strong> " . htmlspecialchars($transfer_data['treatment_title']) . "</li>
                                    <li><strong>Pacient:</strong> " . htmlspecialchars($transfer_data['patient_nombre']) . " " . htmlspecialchars($transfer_data['patient_apellido']) . "</li>
                                    <li><strong>Propietari anterior:</strong> " . htmlspecialchars($transfer_data['old_fisio_nombre'] . " " . $transfer_data['old_fisio_apellido']) . "</li>
                                </ul>
                                <p style='text-align: center; margin-top: 30px;'>
                                    <a href='" . $app_base_url . "treatments.php' style='background-color: #0d6efd; color: white; padding: 12px 20px; text-decoration: none; border-radius: 5px; font-weight: bold;'>
                                        Anar a Tractaments
                                    </a>
                                </p>
                            </div>
                            ";
                        } else {
                            // Si falla la consulta de datos de transferencia, no se envía email
                             error_log("FALLO EMAIL TRANSFER: No s'han trobat les dades per l'email de transferència (ID: $treatment_id)");
                             $body_paciente = ""; // Forzar a que no se envíe
                        }
                    }
                    // --- ★★★ FIN NUEVO BLOQUE 'ELSEIF' ★★★ ---


                    // Enviar
                    if (!empty($body_paciente) && !empty($email_recipient)) {
                        send_platform_email(
                            $email_recipient,
                            $subject_paciente,
                            $body_paciente,
                            true, // isHtml
                            $embedded_logo
                        );
                    }

                    echo json_encode(['status' => 'success', 'message' => 'Email enviado en segundo plano.']);

                } catch (Exception $e) {
                    error_log("FALLO EN ENVÍO DE EMAIL (Asíncrono, $type, ID: $treatment_id): " . $e->getMessage());
                    echo json_encode(['status' => 'success', 'message' => 'Email no enviado (error de servidor), pero la acción principal tuvo éxito.']);
                }

                break;
            // --- ★★★ FIN NUEVA ACCIÓN (VERSIÓN 3) ★★★ ---

        } // Fin Switch
      } catch (Exception $e) {
      if ($db->inTransaction()) $db->rollBack();
      http_response_code(400);
       error_log("Error en treatments AJAX action=$action: " . $e->getMessage() . "\nTrace: " . $e->getTraceAsString());
      echo json_encode(['status' => 'error', 'message' => 'S\'ha produït un error al processar la sol·licitud.']);
  }
  exit;
}

$page_title = "Gestió de Tractaments";
include 'partials/header.php';

// --- ★ INICIO CORRECCIÓN: Definir $app_base_url para el JS ---
// NOTA: Esta sección original ya no es necesaria ya que la definimos al inicio para que esté disponible para AJAX
// La dejamos como estaba para no tocar la estructura HTML/JS, aunque PHP ya la tiene definida arriba.
// $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
// $domain_root = $protocol . $_SERVER['HTTP_HOST'];
// $app_base_url = rtrim($domain_root . dirname($_SERVER['SCRIPT_NAME']), '/') . '/';
// --- ★ FIN CORRECCIÓN ---

// ★★★ MODIFICACIÓ 3: Definir la ruta de avatares para el JS ★★★
$avatar_db_path_js = AVATAR_DB_PATH;
?>

<style>
  .card-img-top { position: relative; cursor: pointer; }
  .no-media-placeholder { display: flex; align-items: center; justify-content: center; height: 100%; background-color: #f8f9fa; color: #6c757d;}
  .initial-circle-overlay { position: absolute; top: 8px; left: 8px; width: 40px; height: 40px; border-radius: 50%; background-color: var(--custom-brand-purple); color: white; display: flex; align-items: center; justify-content: center; font-weight: bold; z-index: 10; border: 2px solid white; box-shadow: 0 1px 3px rgba(0,0,0,0.3); }
  .list-thumbnail { width: 120px; height: 67px; object-fit: cover; border-radius: 0.25rem; background-color: #e9ecef; }
  .view-ex-thumb { width: 100px; height: 60px; object-fit: cover; border-radius: 0.25rem; background-color: #343a40; }
  .sortable-header { cursor: pointer; user-select: none; }
  .drag-handle { cursor: grab; font-size: 1.2rem; color: #adb5bd; }
  .sortable-ghost { background: #f0faff; border: 1px dashed #0d6efd; }
  .status-badge-group { display: flex; flex-direction: column; align-items: flex-start; gap: 4px; }
  .dropdown-item i.bi { margin-right: 0.5rem; }
  .dropdown .btn.dropdown-toggle:hover {
      color: #FFF !important;
  }

  /* REGLA CLAVE para los menús desplegables */
  td .dropdown, .card-body .dropdown {
      position: static;
  }

  .table td.wrap-text {
      white-space: normal;
      word-wrap: break-word;
      max-width: 150px; /* Adjust as needed */
      font-size: 0.85rem; /* Slightly smaller font for collaborators */
      line-height: 1.3;
  }
  #treatments-table-container thead th {
      white-space: nowrap !important;
  }

  /* --- CSS para el avatar pequeño en lista --- */
  .avatar-small {
        width: 40px;
        height: 40px;
        border-radius: 50%;
        object-fit: cover;
        border: 2px solid white;
        box-shadow: 0 1px 3px rgba(0,0,0,0.3);
    }

  /* Aseguramos que el círculo de iniciales también es 40px */
  .initial-circle {
      width: 40px;
      height: 40px;
      border-radius: 50%;
      background-color: var(--custom-brand-purple);
      color: white;
      display: flex;
      align-items: center;
      justify-content: center;
      font-weight: bold;
      flex-shrink: 0;
      border: 2px solid white;
      box-shadow: 0 1px 3px rgba(0,0,0,0.3);
  }

  /* ★★★ INICIO DE LA MODIFICACIÓN PARA MÓVIL ★★★ */
  @media (max-width: 767.98px) {
      /* Ocultamos los botones de cambiar vista (Grid/List) en móvil */
      .toggle-view-btn {
          display: none !important;
      }
  }
  /* ★★★ FIN DE LA MODIFICACIÓN PARA MÓVIL ★★★ */
</style>


<main class="main-content container mt-4" style="max-width: 1420px;">
  <div class="d-flex justify-content-between align-items-center mb-3 treatments-header-bar">
<h4><i class="bi bi-journal-medical me-2"></i> Historial de Tractaments</h4>
      <button class="btn btn-primary" id="addTreatmentBtn"><i class="bi bi-plus-circle"></i> Nou Tractament</button>
  </div>

  <div class="card shadow-sm">
      <div class="card-body">

          <div class="row g-2 mb-4">

              <div class="col-12 col-lg-6">
                  <div class="d-flex align-items-center h-100 flex-wrap gap-2">
                      <?php if (in_array($user_rol, ['superadmin', 'fisio'])): ?>
                      <div class="form-check form-switch text-nowrap">
                          <input class="form-check-input" type="checkbox" role="switch" id="filterMyTreatments">
                          <label class="form-check-label" for="filterMyTreatments">Només els meus</label>
                      </div>
                      <?php endif; ?>

                      <div class="flex-grow-1 mobile-filter-flex-grow" style="min-width: 180px; max-width: 220px;">
                          <select id="categoryFilter" class="form-select">
                             <option value="">Totes les Categories</option>
                         </select>
                      </div>

                      <div class="flex-grow-1 mobile-filter-flex-grow" style="min-width: 180px; max-width: 220px;">
                          <select id="statusFilter" class="form-select">
                              <option value="">Tots els estats</option>
                              <option value="En curs">En curs</option>
                              <option value="Programat">Programat</option>
                              <option value="Completat">Completat</option>
                              <option value="Omés">Omés</option>
                          </select>
                      </div>
                  </div>
              </div>

              <div class="col-12 col-lg-6">
                  <div class="d-flex align-items-center justify-content-start justify-content-lg-end flex-wrap gap-2">

                      <div class="input-group mobile-filter-full-width" style="max-width: 300px; position: relative;">
                          <span class="input-group-text"><i class="bi bi-search"></i></span>
                          <input type="text" id="searchInput" class="form-control" placeholder="Cercar per pacient o títol...">
                          <button class="clear-search-btn" type="button" id="clearSearchBtn"><i class="bi bi-x"></i></button>
                      </div>

                      <div class="btn-group mobile-filter-btn-group" role="group">
                          <button type="button" class="btn btn-outline-secondary toggle-view-btn active" id="listViewBtn" title="Vista en Llista"><i class="bi bi-list"></i></button>
                          <button type="button" class="btn btn-outline-secondary toggle-view-btn" id="gridViewBtn" title="Vista en Quadrícula"><i class="bi bi-grid-fill"></i></button>
                      </div>

                      <div class="btn-group mobile-filter-btn-group" id="sort-buttons-group">
                          <button class="btn btn-outline-secondary sort-btn" data-sort="start_date" data-order="DESC" title="Ordenar per Data d'Inici"><i class="bi bi-calendar3"></i></button>
                          <button class="btn btn-outline-secondary sort-btn" data-sort="paciente_apellido" data-order="ASC" title="Ordenar per Pacient"><i class="bi bi-sort-alpha-down"></i></button>
                      </div>
                  </div>
              </div>
          </div>
          <div id="treatments-list-container"></div>
          <div id="pagination-container" class="mt-4"></div>
      </div>
  </div>
</main>

<div class="modal fade" id="transferTreatmentModal" tabindex="-1">
  <div class="modal-dialog">
      <div class="modal-content">
          <div class="modal-header">
              <h5 class="modal-title">Transferir Propietat del Tractament</h5>
              <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
          </div>
          <div class="modal-body">
              <p>Estàs a punt de transferir el tractament: <br><strong><span id="transferTreatmentName">...</span></strong></p>
              <p class="mb-3">Propietari actual: <strong><span id="transferOldFisioName">...</span></strong></p>

              <div class="mb-3">
                  <label for="transferNewFisioSelect" class="form-label">Selecciona el nou propietari (fisio):</label>
                  <select id="transferNewFisioSelect" class="form-select" required>
                      <option value="">Carregant fisios...</option>
                  </select>
              </div>
          </div>
          <div class="modal-footer">
              <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel·lar</button>
              <button type="button" class="btn btn-primary" id="proceedToWarningBtn">Continuar...</button>
          </div>
      </div>
  </div>
</div>

<div class="modal fade" id="transferWarningModal" tabindex="-1">
  <div class="modal-dialog modal-lg modal-dialog-centered">
      <div class="modal-content">
          <div class="modal-header bg-warning">
              <h5 class="modal-title"><i class="bi bi-exclamation-triangle-fill me-2"></i> Confirmació de Transferència</h5>
              <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
          </div>
          <div class="modal-body">
              <p>Estàs a punt de transferir el tractament de <strong id="warnOldFisio">...</strong> a <strong id="warnNewFisio">...</strong>.</p>
              <p>Això tindrà les següents **conseqüències permanents**:</p>
              <ul class="list-group">
                  <li class="list-group-item">
                      <i class="bi bi-person-check-fill text-success me-2"></i>
                      <strong>Nou Propietari:</strong> <span id="warnNewFisio2">...</span> serà el nou `creator_fisio_id` i tindrà control total d'edició.
                  </li>
                  <li class="list-group-item">
                      <i class="bi bi-people-fill text-info me-2"></i>
                      <strong>Antic Propietari:</strong> <span id="warnOldFisio2">...</span> s'afegirà automàticament com a col·laborador per a mantenir la visibilitat.
                  </li>
                  <li class="list-group-item">
                      <i class="bi bi-bell-fill text-primary me-2"></i>
                      <strong>Notificacions:</strong> Totes les *futures* alertes de dolor/esforç i notificacions d'activitat s'enviaran al nou propietari.
                  </li>
                  <li class="list-group-item">
                      <i class="bi bi-chat-dots-fill text-danger me-2"></i>
                      <strong>Historial de Xat:</strong> El nou propietari **NO VEURÀ** l'historial de xat antic entre el pacient i l'antic propietari. La seua conversa començarà buida.
                  </li>
              </ul>
              <p class="fw-bold mt-3">Aquesta acció no es pot desfer. Estàs segur/a que vols continuar?</p>
          </div>
          <div class="modal-footer">
              <button type="button" class="btn btn-secondary" data-bs-target="#transferTreatmentModal" data-bs-toggle="modal">Enrere</button>
              <button type="button" class="btn btn-warning" id="confirmTransferBtn" data-treatment-id="" data-new-fisio-id="" data-old-creator-id="">
                  Sí, Entenc i Vull Transferir
              </button>
          </div>
      </div>
  </div>
</div>
<?php include 'partials/footer.php'; ?>

<script>
  // Pasa las preferencias de vista al script de JavaScript
  const USER_VIEW_PREFERENCES = <?php echo $user_view_prefs_json; ?>;
// ★★★ MODIFICACIÓ 3: Pasar la ruta de avatares a JS ★★★
  const AVATAR_BASE_URL = "<?php echo $avatar_db_path_js; ?>";
// ★★★ FI MODIFICACIÓ ★★★
</script>

<script>
$(document).ready(function() {
  new bootstrap.Tooltip(document.body, { selector: "[data-bs-toggle='tooltip']" });

  // --- CONSTANTES ---
  const CURRENT_USER_ID = <?= $user_id ?>;
  const IS_SUPERADMIN = '<?= $user_rol ?>' === 'superadmin';
  const FILTER_MINE_DEFAULT = <?= $filtro_defecto ?> == 1;
  const initialTreatmentView = USER_VIEW_PREFERENCES['treatments'] || 'list';
  // --- ★ INICIO CORRECCIÓN: Definir APP_BASE_URL ---
  const APP_BASE_URL = "<?php echo $app_base_url; ?>";
  // --- ★ FIN CORRECCIÓN ---

function isMobileView() {
      return window.innerWidth < 767.98;
  }

  // --- ESTADO DE LA PÁGINA ---
let appState = {
    currentPage: 1, searchQuery: '', status: '',
    // --- ★ TAREA 2 (Default Sort) ---
    sortBy: 'created_at', sortOrder: 'DESC',
    // --- ★ FIN TAREA 2 ---
    filterMine: FILTER_MINE_DEFAULT,
    viewMode: isMobileView() ? 'grid' : initialTreatmentView, // <-- MODIFICADO AQUÍ: Forzar 'grid' en móvil
    categoryId: ''
};

  let allPacients = [], allFisios = [], allCategories = [], allTags = []; // Para los modales
  let itemToManage = { id: null, name: '', ownerId: null, patientName: '' }; // Para modal manage
  let pendingAction = null, pendingId = null, pendingStatus = null; // Para modal confirmation
  let pageModalFunctions = {}; // --- ★ MODIFICACIÓN: Declarar pageModalFunctions en el scope superior ★ ---

  // --- FUNCIONES DE RENDERIZADO DE PÁGINA ---

  function getInitialSortIcon(currentSort, currentOrder, columnName) {
      if (currentSort === columnName) {
          return currentOrder === 'ASC' ? '<i class="bi bi-caret-up-fill ms-2"></i>' : '<i class="bi bi-caret-down-fill ms-2"></i>';
      }
      const sortableColumns = ['start_date', 'title', 'paciente_apellido', 'status', 'creator_surname', 'collaborators', 'created_at'];
      if (!sortableColumns.includes(columnName)) {
          return '';
      }
      return '<i class="bi bi-arrow-down-up ms-2 text-muted opacity-50"></i>';
  }

  function fetchTreatments() {
      // ATENUAMOS la lista, no la borramos
      $('#treatments-list-container').css('opacity', 0.5);
      const params = {
          ajax: true, action: 'read_treatments',
          page: appState.currentPage, search: appState.searchQuery,
          status: appState.status, sort: appState.sortBy,
          order: appState.sortOrder, filterMine: appState.filterMine,
          categoryId: appState.categoryId // <-- ★★★ AÑADIR ESTA LÍNEA ★★★
      };

      return $.getJSON(APP_BASE_URL + 'treatments.php', params)
      .done(response => {
          // RESTAURAMOS la opacidad antes de renderizar
          $('#treatments-list-container').css('opacity', 1);
          if (response.status === 'success') {
              renderTreatments(response.treatments, response.pagination.currentSort, response.pagination.currentOrder);
              renderPagination(response.pagination);
              updateSortButtons(response.pagination.currentSort, response.pagination.currentOrder);
          } else {
               $('#treatments-list-container').html(`<div class="alert alert-warning">${escapeHtml(response.message || 'Error')}</div>`);
          }
      }).fail(xhr => {
          // RESTAURAMOS la opacidad si falla
          $('#treatments-list-container').css('opacity', 1).html('<div class="alert alert-danger">Error en carregar els tractaments.</div>');
      });
  }

  // --- ★ TAREA 2 (Honest UI) ---
  function updateSortButtons(currentSort, currentOrder) {
      $('.sort-btn').removeClass('active');
      // Solo añade 'active' si el 'currentSort' coincide EXACTAMENTE con un botón
      const targetButton = $(`.sort-btn[data-sort="${currentSort}"]`);
      if(targetButton.length > 0) {
          targetButton.first().addClass('active');
      }
      // Si no hay match (p.ej. el default 'created_at'), ningún botón se activa.
  }
  // --- ★ FIN TAREA 2 ---

  function renderTreatments(treatments, currentSort, currentOrder) {
        const container = $('#treatments-list-container');
        container.empty();

        if (treatments.length === 0) {
            container.html('<div class="alert alert-secondary text-center">No s\'han trobat tractaments.</div>');
            return;
        }

        // --- VISTA CUADRÍCULA (GRID) ---
        if (appState.viewMode === 'grid') {
            container.removeClass('table-responsive').addClass('row g-4');

            treatments.forEach(t => {
                let thumbnailHtml = '';

                if (t.first_video_filename) {
                    if (t.first_video_filename.startsWith('http')) {
                        const ytMatch = t.first_video_filename.match(/youtube\.com\/embed\/([a-zA-Z0-9\-_]+)/);

                        if (ytMatch) {
                            // Es YouTube
                            thumbnailHtml = `<img src="https://img.youtube.com/vi/${ytMatch[1]}/mqdefault.jpg" alt="Miniatura" class="w-100 h-100 object-fit-cover">`;
                        } else {
                            // ★ CORRECCIÓN GRID: Es URL externa directa (MP4) -> Usamos VIDEO
                            thumbnailHtml = `<video src="${t.first_video_filename}#t=0.5" preload="metadata" class="w-100 h-100" style="object-fit: cover;"></video>`;
                        }
                    } else {
                        // Es video local
                        thumbnailHtml = `<video src="videos/${t.first_video_filename}#t=0.5" preload="metadata" class="w-100 h-100" style="object-fit: cover;"></video>`;
                    }
                } else if (t.first_image_filename) {
                    thumbnailHtml = `<img src="images/${t.first_image_filename}" alt="Miniatura" class="w-100 h-100 object-fit-cover">`;
                } else {
                    thumbnailHtml = `<div class="w-100 h-100 no-media-placeholder d-flex align-items-center justify-content-center"><div class="text-center"><i class="bi bi-camera-video-off fs-1"></i><p class="mb-0 mt-2 small">Sense medis associats</p></div></div>`;
                }

                const initialCircleOverlay = `<div class="initial-circle-overlay">${escapeHtml(t.paciente_initials)}</div>`;
                const imageContainer = `<div class="card-img-top ratio ratio-16x9 view-treatment-btn" data-id="${t.id}">${thumbnailHtml}${initialCircleOverlay}</div>`;
                const buttonsHtml = renderActionButtons(t);
                let statusBadge = getStatusBadge(t.status, t.realizacion_percent);
                const startDate = new Date(t.start_date).toLocaleDateString('ca-ES');
                const endDate = t.end_date ? new Date(t.end_date).toLocaleDateString('ca-ES') : 'N/A';
                const collaboratorsHtml = t.collaborators ? `<p class="card-text small text-muted mb-2">Col·laboren: ${escapeHtml(t.collaborators)}</p>` : '';

                container.append(`<div class="col-md-6 col-lg-4 col-xl-3"><div class="card h-100 shadow-sm">
                    ${imageContainer}
                    <div class="card-body d-flex flex-column">
                        <h5 class="card-title">${escapeHtml(t.title)}</h5>
                        <p class="card-text small text-muted mb-1">Per a: <a href="fitxa_pacient.php?id=${t.paciente_id}" class="text-dark text-decoration-none"><strong>${escapeHtml(t.paciente_apellido)}, ${escapeHtml(t.paciente_nombre)}</strong></a></p>
                        <p class="card-text small text-muted mb-2">Creat per: ${escapeHtml(t.creator_fisio_name)} ${escapeHtml(t.creator_fisio_surname)}</p>
                        ${collaboratorsHtml}
                        <div class="mt-auto">
                            <p class="card-text small text-muted mb-1">Conté <strong>${t.exercise_count}</strong> exercicis</p>
                            <p class="card-text small text-muted mb-2">(${startDate} - ${endDate})</p>
                            <div class="d-flex justify-content-between align-items-center">${statusBadge}<div class="btn-group">${buttonsHtml}</div></div>
                        </div>
                    </div>
                </div></div>`);
            });

        // --- VISTA LISTA (TABLA) - AQUÍ ESTABA EL ERROR DE TU CAPTURA ---
        } else {
            container.addClass('table-responsive').removeClass('row g-4');
            let tableHtml = `<table class="table table-hover align-middle">
                <thead><tr>
                    <th style="width: 120px;">Recurs</th>
                    <th class="sortable-header" data-sort="paciente_apellido" style="width: 15%;">Pacient${getInitialSortIcon(currentSort, currentOrder, 'paciente_apellido')}</th>
                    <th class="sortable-header" data-sort="title" style="width: 15%;">Tractament${getInitialSortIcon(currentSort, currentOrder, 'title')}</th>
                    <th class="sortable-header" data-sort="creator_surname" style="width: 12%;">Creat per${getInitialSortIcon(currentSort, currentOrder, 'creator_surname')}</th>
                    <th class="sortable-header" data-sort="collaborators" style="width: 12%;">Col·laboradors${getInitialSortIcon(currentSort, currentOrder, 'collaborators')}</th>
                    <th class="sortable-header" data-sort="created_at" style="width: 10%;">Data${getInitialSortIcon(currentSort, currentOrder, 'created_at')}</th>
                    <th class="sortable-header" data-sort="start_date" style="width: 10%;">Període${getInitialSortIcon(currentSort, currentOrder, 'start_date')}</th>
                    <th class="text-center" style="width: 5%;">Nº Ex.</th>
                    <th class="sortable-header" data-sort="status" style="width: 8%;">Estat${getInitialSortIcon(currentSort, currentOrder, 'status')}</th>
                    <th class="text-end" style="width: 5%;">Accions</th>
                </tr></thead><tbody>`;

            treatments.forEach(t => {
                const buttonsHtml = renderActionButtons(t);

                let avatarContent;
                if (t.paciente_avatar) {
                     avatarContent = `<img src="${APP_BASE_URL}${AVATAR_BASE_URL}${t.paciente_avatar.split('/').pop()}" alt="Avatar" class="avatar-small me-3">`;
                } else {
                     avatarContent = `<div class="initial-circle me-3">${escapeHtml(t.paciente_initials)}</div>`;
                }
                const nameCell = `<a href="fitxa_pacient.php?id=${t.paciente_id}" class="text-decoration-none text-dark d-flex align-items-center">${avatarContent}<div class="fw-bold">${escapeHtml(t.paciente_apellido)}, ${escapeHtml(t.paciente_nombre)}</div></a>`;

                let thumbnailHtml = '';

                if (t.first_video_filename) {
                    if (t.first_video_filename.startsWith('http')) {
                        const ytMatch = t.first_video_filename.match(/youtube\.com\/embed\/([a-zA-Z0-9\-_]+)/);

                        if (ytMatch) {
                            // Es YouTube
                            thumbnailHtml = `<img src="https://img.youtube.com/vi/${ytMatch[1]}/mqdefault.jpg" class="list-thumbnail" alt="Miniatura">`;
                        } else {
                            // ★ CORRECCIÓN LISTA: Es URL externa directa (MP4) -> Usamos VIDEO
                            // Antes aquí había un div "list-thumbnail no-media-placeholder" con texto "URL"
                            thumbnailHtml = `<video src="${t.first_video_filename}#t=0.5" class="list-thumbnail" preload="metadata"></video>`;
                        }
                    } else {
                        // Es video local
                        thumbnailHtml = `<video src="videos/${t.first_video_filename}#t=0.5" class="list-thumbnail" preload="metadata"></video>`;
                    }
                } else if (t.first_image_filename) {
                    thumbnailHtml = `<img src="images/${t.first_image_filename}" class="list-thumbnail" alt="Miniatura">`;
                } else {
                     thumbnailHtml = `<div class="list-thumbnail no-media-placeholder d-flex align-items-center justify-content-center"><div class="text-center"><i class="bi bi-camera-video-off fs-4"></i><span class="d-block small" style="font-size: 0.65rem;">Sense medis</span></div></div>`;
                }

                const createdDate = t.created_at ? new Date(t.created_at).toLocaleDateString('ca-ES', { day: '2-digit', month: '2-digit', year: 'numeric' }) : 'N/A';
                const startDate = t.start_date ? new Date(t.start_date).toLocaleDateString('ca-ES', { day: '2-digit', month: '2-digit', year: 'numeric' }) : 'N/A';
                const endDate = t.end_date ? new Date(t.end_date).toLocaleDateString('ca-ES', { day: '2-digit', month: '2-digit', year: 'numeric' }) : 'N/A';
                const collaboratorsCell = `<td class="small wrap-text">${escapeHtml(t.collaborators) || 'Cap'}</td>`;

                tableHtml += `<tr>
                    <td>${thumbnailHtml}</td>
                    <td>${nameCell}</td>
                    <td>${escapeHtml(t.title)}</td>
                    <td>${escapeHtml(t.creator_fisio_name)} ${escapeHtml(t.creator_fisio_surname)}</td>
                    ${collaboratorsCell}
                    <td class="small"><span class="text-nowrap">${createdDate}</span></td>
                    <td class="small"><span class="text-nowrap">${startDate}</span> - <span class="text-nowrap">${endDate}</span></td>
                    <td class="text-center"><span class="badge bg-secondary">${t.exercise_count}</span></td>
                    <td>${getStatusBadge(t.status, t.realizacion_percent)}</td>
                    <td class="text-end">${buttonsHtml}</td>
                </tr>`;
            });
            container.html(tableHtml + '</tbody></table>');
        }
        $('[data-bs-toggle="tooltip"]').tooltip('dispose').tooltip();
    }


  function getStatusBadge(status, realizacion_percent) {
      let badgeHtml = '', tooltipTitle = '';
      switch(status) {
          case 'En curs': badgeHtml = `<span class="badge bg-warning text-dark">En curs</span>`; tooltipTitle = 'Tractament actiu dins del rang de dates.'; break;
          case 'Programat': badgeHtml = `<span class="badge bg-info">Programat</span>`; tooltipTitle = "Pendent de començar en la data d'inici."; break;
          case 'Completat': badgeHtml = `<span class="badge bg-success">Completat</span>`; tooltipTitle = 'Marcat com a completat (manual o automàtic).'; break;
          case 'Omés': badgeHtml = `<span class="badge bg-secondary">Omés</span>`; tooltipTitle = 'Marcat com a omés (manual o automàtic).'; break;
          default: badgeHtml = `<span class="badge bg-light text-dark">${escapeHtml(status)}</span>`; tooltipTitle = `Estat: ${escapeHtml(status)}`; break;
      }
      badgeHtml = badgeHtml.replace('>', ` data-bs-toggle="tooltip" title="${escapeHtml(tooltipTitle)}">`);
      let percentHtml = '';
      if (realizacion_percent !== null && realizacion_percent !== undefined) {
           if (status === 'Completat' || status === 'Omés') {
               percentHtml = `<span class="badge bg-light text-dark fw-normal">${realizacion_percent}% realitzat</span>`;
           }
      }
      return `<div class="status-badge-group">${badgeHtml}${percentHtml}</div>`;
  }

  function renderActionButtons(treatment) {
          const isCreator = treatment.creator_fisio_id == CURRENT_USER_ID;
          const collaboratorIdsArray = treatment.collaborator_ids ? treatment.collaborator_ids.split(',') : [];
          const isCollaborator = collaboratorIdsArray.includes(String(CURRENT_USER_ID));
          const canModify = IS_SUPERADMIN || isCreator || isCollaborator;
          const canManage = IS_SUPERADMIN || isCreator;
          const status = treatment.status;
          const t_id = treatment.id;
          const t_title_safe = escapeHtml(treatment.title);
          const t_patient_name_safe = escapeHtml(treatment.paciente_fullname);
          const t_owner_id = treatment.creator_fisio_id;
          const manage_data = `data-id="${t_id}" data-name='${t_title_safe}' data-owner-id="${t_owner_id}" data-patient-name='${t_patient_name_safe}'`;

          let commonItems = `
              <li><a class="dropdown-item view-treatment-btn" href="#" data-id="${t_id}">
                  <i class="bi bi-eye"></i> Veure Detalls
              </a></li>
              <li>
                  <a class="dropdown-item ${!canModify ? 'disabled' : ''}"
                     href="${canModify ? `fitxa_pacient.php?id=${treatment.paciente_id}` : '#'}"
                     ${!canModify ? 'aria-disabled="true" tabindex="-1"' : ''}
                     title="${!canModify ? "No tens permisos per a accedir a la fitxa d'aquest tractament específic" : "Anar a l'àrea de tractaments del pacient"}">
                      <i class="bi bi-person-badge"></i> Àrea de Tractaments
                  </a>
              </li>
              <li><hr class="dropdown-divider"></li>
              <li>
                  <a class="dropdown-item edit-treatment-btn ${!canModify ? 'disabled' : ''}"
                     href="#"
                     data-id="${t_id}"
                     ${!canModify ? 'aria-disabled="true" tabindex="-1"' : ''}
                  >
                      <i class="bi bi-pencil"></i> Editar
                  </a>
              </li>
              <li><a class="dropdown-item clone-btn" href="#" data-id="${t_id}" data-title="${t_title_safe}">
                  <i class="bi bi-copy"></i> Clonar
              </a></li>
              <li><hr class="dropdown-divider"></li>
              <li><a class="dropdown-item ${!canModify ? 'disabled' : ''}"
                     href="${canModify ? `reports/treatment_report.php?id=${t_id}&return_to=${encodeURIComponent(window.location.pathname + window.location.search)}` : '#'}"
                     ${!canModify ? 'aria-disabled="true" tabindex="-1" title="Només creador/col·laborador pot imprimir"' : ''}
                     >
                  <i class="bi bi-printer"></i> Imprimir Informe
              </a></li>
              `;

          let finalItems = '';
          if (status === 'En curs' || status === 'Programat') {
              finalItems = `
                  <li><hr class="dropdown-divider"></li>
                  <li><h6 class="dropdown-header">Finalitzar Manualment</h6></li>
                  <li>
                      <a class="dropdown-item set-status-btn ${!canModify ? 'disabled' : ''}"
                         href="#"
                         data-id="${t_id}" data-status="Completat"
                         ${!canModify ? 'aria-disabled="true" tabindex="-1" title="Només creador/col·laborador pot finalitzar"' : ''}
                      >
                          <i class="bi bi-check-circle-fill text-success"></i> Marcar com a Completat
                      </a>
                  </li>
                  <li>
                      <a class="dropdown-item set-status-btn ${!canModify ? 'disabled' : ''}"
                         href="#"
                         data-id="${t_id}" data-status="Omés"
                         ${!canModify ? 'aria-disabled="true" tabindex="-1" title="Només creador/col·laborador pot finalitzar"' : ''}
                      >
                          <i class="bi bi-x-octagon-fill text-secondary"></i> Marcar com a Omés
                      </a>
                  </li>
              `;
          } else {
              const canReactivate = IS_SUPERADMIN || isCreator || isCollaborator;
              finalItems = `
                  <li><hr class="dropdown-divider"></li>
                  <li><a class="dropdown-item reactivate-btn ${!canReactivate ? 'disabled' : ''}"
                         href="#"
                         data-id="${t_id}"
                         ${!canReactivate ? 'aria-disabled="true" tabindex="-1"' : ''}
                      >
                          <i class="bi bi-arrow-counterclockwise text-primary"></i> Reactivar Tractament
                      </a></li>
              `;
          }

          // --- ★★★ INICIO MODIFICACIÓN: AÑADIR BOTÓN TRANSFER ★★★ ---
          let transferItem = '';
          if (IS_SUPERADMIN) {
              const t_creator_name_safe = escapeHtml(`${treatment.creator_fisio_name} ${treatment.creator_fisio_surname}`);
              transferItem = `
                  <li><hr class="dropdown-divider"></li>
                  <li><a class="dropdown-item transfer-btn" href="#" data-id="${t_id}" data-name='${t_title_safe}' data-creator-name='${t_creator_name_safe}' data-creator-id="${t_owner_id}">
                      <i class="bi bi-person-arrow-right text-info"></i> Transferir Propietat
                  </a></li>
              `;
          }
          // --- ★★★ FIN MODIFICACIÓN ★★★ ---

          return `
              <div class="dropdown">
                  <button class="btn btn-sm btn-outline-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false">
                      <i class="bi bi-gear-fill"></i>
                  </button>
                  <ul class="dropdown-menu dropdown-menu-end">
                      ${commonItems}
                      ${finalItems}
                      ${transferItem}
                      <li><hr class="dropdown-divider"></li>
                      <li><a class="dropdown-item manage-btn ${!canManage ? 'disabled' : ''}"
                         href="#"
                         ${manage_data}
                         ${!canManage ? 'aria-disabled="true" tabindex="-1"' : ''}
                      >
                          <i class="bi bi-shield-slash"></i> Arxivar / Eliminar
                      </a></li>
                  </ul>
              </div>
          `;
      }

  function renderPagination(pagination) {
      const container = $('#pagination-container');
      container.empty();
      if (pagination.totalPages <= 1) return;
      let paginationHtml = `<nav><ul class="pagination justify-content-center">`;
      for (let i = 1; i <= pagination.totalPages; i++) {
          paginationHtml += `<li class="page-item ${i === pagination.currentPage ? 'active' : ''}"><a class="page-link" href="#" data-page="${i}">${i}</a></li>`;
      }
      paginationHtml += `</ul></nav>`;
      container.html(paginationHtml);
  }

  // --- MANEJADORES DE EVENTOS DE PÁGINA ---

  // Vista
  // --- ★ TAREA EXTRA (Ocultar botones) ---
  $('.toggle-view-btn').on('click', function() {
      const newViewMode = $(this).attr('id') === 'gridViewBtn' ? 'grid' : 'list';
      if (appState.viewMode === newViewMode) return;

      appState.viewMode = newViewMode;
      $('.toggle-view-btn').removeClass('active');
      $(this).addClass('active');

      // --- ★ INICIO DE LA MODIFICACIÓN ★ ---
      if (newViewMode === 'list') {
          $('#sort-buttons-group').hide(); // Ocultar botones en Lista
      } else {
          $('#sort-buttons-group').show(); // Mostrar botones en Rejilla
      }
      // --- ★ FIN DE LA MODIFICACIÓN ★ ---


      // --- ★ CORRECCIÓN: Usar APP_BASE_URL ---
      $.post(APP_BASE_URL + 'dashboard.php', {
          ajax: true,
          action: 'save_view_preference',
          page_name: 'treatments',
          view_mode: newViewMode
      }, 'json')
      .done(res => {
          if(res.status === 'success') { console.log('Vista guardada: treatments -> ' + newViewMode); }
      })
      .fail(xhr => {
           console.error('Error guardant la preferència de vista.', xhr.responseText);
      });

      fetchTreatments();
  });
  // --- ★ FIN TAREA EXTRA ---

  // Modales específicos de esta página
  $(document).on('click', '.view-treatment-btn', function(e) {
      e.preventDefault();
      const id = $(this).data('id');
      $('#viewTreatmentModalBody').html('<div class="text-center p-5"><div class="spinner-border"></div></div>');
      bootstrap.Modal.getOrCreateInstance(document.getElementById('viewTreatmentModal')).show();

      // --- ★ CORRECCIÓN: Usar APP_BASE_URL ---
      $.getJSON(APP_BASE_URL + 'treatments.php', { ajax: true, action: 'get_treatment_details', id: id }, response => {
          if (response.status === 'success' && response.treatment) {
              const t = response.treatment;
              $('#viewTreatmentModalLabel').text(escapeHtml(t.title));
              let headerHtml = `<div class="row mb-4 small">
                                  <div class="col-md-4 mb-2 mb-md-0"><h6 class="text-dark mb-1"><i class="bi bi-person-badge me-2"></i>Pacient</h6><p class="ps-3 mb-0">${escapeHtml(t.paciente_apellido)}, ${escapeHtml(t.paciente_nombre)}</p></div>
                                  <div class="col-md-4 mb-2 mb-md-0"><h6 class="text-dark mb-1"><i class="bi bi-check-circle me-2"></i>Estat</h6><p class="ps-3 mb-0">${getStatusBadge(t.status, t.realizacion_percent)}</p></div>
                                  <div class="col-md-4 mb-2 mb-md-0"><h6 class="text-dark mb-1"><i class="bi bi-calendar-range me-2"></i>Rang de Dates</h6><p class="ps-3 mb-0">${new Date(t.start_date).toLocaleDateString('ca-ES')} - ${t.end_date ? new Date(t.end_date).toLocaleDateString('ca-ES') : 'N/A'}</p></div>
                              </div>
                              <div class="row mb-4 small">
                                  <div class="col-md-4 mb-2 mb-md-0"><h6 class="text-dark mb-1"><i class="bi bi-person-circle me-2"></i>Creat per</h6><p class="ps-3 mb-0">${escapeHtml(t.creator_fisio_name)} ${escapeHtml(t.creator_fisio_surname)}</p></div>
                                  <div class="col-md-4 mb-2 mb-md-0"><h6 class="text-dark mb-1"><i class="bi bi-calendar-plus me-2"></i>Data de Creació</h6><p class="ps-3 mb-0">${t.created_at ? new Date(t.created_at).toLocaleDateString('ca-ES') : 'N/A'}</p></div>
                                  <div class="col-md-4 mb-2 mb-md-0"><h6 class="text-dark mb-1"><i class="bi bi-people me-2"></i>Fisios Col·laboradors</h6><p class="ps-3 mb-0">${escapeHtml(t.collaborators) || 'Cap'}</p></div>
                              </div><hr>`;
              let evaluationHtml = `<h5 class="mb-3">Avaluació Inicial</h5><div class="row mb-4"><div class="col-md-6"><h6><i class="bi bi-file-text me-2"></i>Anamnesi</h6><p class="text-muted ps-4">${escapeHtml(t.anamnesis) || 'No especificat'}</p></div><div class="col-md-6"><h6><i class="bi bi-clipboard-check me-2"></i>Diagnòstic</h6><p class="text-muted ps-4">${escapeHtml(t.diagnostico) || 'No especificat'}</p></div></div><hr>`;
              let exercisesHtml = `<h5 class="mb-3"><i class="bi bi-list-ol me-2"></i>Pauta d'Exercicis (${t.assigned_exercises.length})</h5><div class="list-group list-group-flush">`;
              t.assigned_exercises.forEach(ex => {
                  let thumbnailHtml = '';
                  if(ex.video_filename) {
                      const isEmbed = ex.video_filename.startsWith('http');
                      const ytMatch = isEmbed ? ex.video_filename.match(/youtube\.com\/embed\/([a-zA-Z0-9\-_]+)/) : null;
                      thumbnailHtml = isEmbed ? `<img src="${ytMatch ? `https://img.youtube.com/vi/${ytMatch[1]}/mqdefault.jpg` : ''}" class="view-ex-thumb" alt="Miniatura Video">` : `<video src="videos/${ex.video_filename}#t=0.5" class="view-ex-thumb"></video>`;
                  } else if (ex.image_filename) {
                       thumbnailHtml = `<img src="images/${ex.image_filename}" class="view-ex-thumb" alt="Miniatura Imatge">`;
                  } else {
                       thumbnailHtml = `<div class="view-ex-thumb d-flex align-items-center justify-content-center bg-light border"><i class="bi bi-camera-video-off fs-4 text-muted"></i></div>`;
                  }
                  exercisesHtml += `<div class="list-group-item px-0"><div class="d-flex w-100"><div class="flex-shrink-0 me-3" style="width:100px;">${thumbnailHtml}</div><div class="flex-grow-1"><h6 class="mb-1">${escapeHtml(ex.title)}</h6><p class="mb-1 small"><strong>Pauta:</strong> ${escapeHtml(ex.frecuencia)} | ${escapeHtml(ex.series)} sèries | ${escapeHtml(ex.repetitions)} reps | ${escapeHtml(ex.rest_time)} descans</p>${ex.pauta_notes ? `<p class="mb-0 small text-muted fst-italic"><strong>Notes específiques:</strong> ${escapeHtml(ex.pauta_notes)}</p>` : ''}</div></div></div>`;
              });
              exercisesHtml += `</div>`;
              $('#viewTreatmentModalBody').html(headerHtml + evaluationHtml + exercisesHtml);
              $('[data-bs-toggle="tooltip"]').tooltip('dispose').tooltip();
          } else {
               $('#viewTreatmentModalBody').html('<div class="alert alert-danger">No s\'han pogut carregar les dades del tractament.</div>');
          }
      }).fail(() => {
           $('#viewTreatmentModalBody').html('<div class="alert alert-danger">Error de connexió al carregar el tractament.</div>');
      });
  });

  $(document).on('click', '.clone-btn', function(e) {
      e.preventDefault();
      $('#cloneTreatmentForm input[name="original_treatment_id"]').val($(this).data('id'));
      $('#cloneTreatmentForm input[name="title"]').val(`Còpia de: ${$(this).data('title')}`);
      const select = $('#cloneTreatmentForm [name="paciente_id"]');
      select.empty().append(new Option('Selecciona Pacient', '', true, true));
      allPacients.forEach(p => select.append(new Option(`${p.apellido}, ${p.nombre}`, p.id)));
      if (typeof TomSelect !== 'undefined' && select[0].tomselect) select[0].tomselect.destroy();
      new TomSelect(select[0], { create: false, placeholder: 'Selecciona un pacient...' });
      bootstrap.Modal.getOrCreateInstance(document.getElementById('cloneTreatmentModal')).show();
  });

  // =======================================================
  // ===== INICIO: cloneTreatmentForm (MODIFICADO) =========
  // =======================================================
  $('#cloneTreatmentForm').on('submit', function(e) {
      e.preventDefault();

      const $submitBtn = $(this).find('button[type="submit"]'); // <<< AÑADIDO
      const originalBtnText = $submitBtn.html(); // <<< AÑADIDO
      $submitBtn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true"></span>Clonant...'); // <<< AÑADIDO

      // --- ★ CORRECCIÓN: Usar APP_BASE_URL ---
      $.post(APP_BASE_URL + 'treatments.php', `ajax=true&action=clone_treatment&${$(this).serialize()}`, 'json')
      .done(res => {
          showToast(res.message, 'success');
          bootstrap.Modal.getOrCreateInstance(document.getElementById('cloneTreatmentModal')).hide();

          // --- ★★★ INICIO: MODIFICACIÓN PARA FLASHEAR EL NUEVO ELEMENTO ★★★ ---
          // --- ★ TAREA 3 (Clonación Lógica): Ya no reiniciamos la página ---
          // appState.currentPage = 1; // <-- ELIMINADO
          const newIdToFlash = res.new_treatment_id;
          fetchTreatments().done(() => {
                if (newIdToFlash) {
                    let elementToFlash;
                    if (appState.viewMode === 'grid') {
                        elementToFlash = $(`.card-img-top[data-id="${newIdToFlash}"]`).closest('.card');
                    } else {
                        elementToFlash = $(`tr .view-treatment-btn[data-id="${newIdToFlash}"]`).closest('tr');
                    }
                    // Usar la función global de footer.php
                    if (typeof flashElement === 'function' && elementToFlash && elementToFlash.length > 0) {
                        flashElement(elementToFlash);
                    }
                }
          });
          // --- ★★★ FIN: MODIFICACIÓN PARA FLASHEAR ★★★ ---

          // --- ★★★ INICIO: NUEVA LLAMADA ASÍNCRONA PARA EMAIL ★★★ ---
          if (res.new_treatment_id) {
              $.post('treatments.php', {
                  ajax: true,
                  action: 'send_treatment_notification',
                  treatment_id: res.new_treatment_id,
                  type: 'clone' // Le decimos al PHP qué email enviar
              })
              .fail(function(err) {
                  console.error('Error enviando email de clonación', err);
              });
          }
          // --- ★★★ FIN: NUEVA LLAMADA ASÍNCRONA PARA EMAIL ★★★ ---

      })
      .fail(xhr => showToast(xhr.responseJSON.message, 'danger'))
      .always(() => {
           $submitBtn.prop('disabled', false).html(originalBtnText); // <<< AÑADIDO
      });
  });
  // =======================================================
  // ===== FIN: cloneTreatmentForm (MODIFICADO) ============
  // =======================================================


  $(document).on('click', '.set-status-btn', function(e) {
      e.preventDefault();
      triggerConfirmationModal($(this).data('id'), 'set_manual_status', $(this).data('status'));
  });

  $(document).on('click', '.reactivate-btn', function(e) {
      e.preventDefault();
       if ($(this).hasClass('disabled')) return;
      triggerConfirmationModal($(this).data('id'), 'reactivate_treatment');
  });

  function triggerConfirmationModal(id, action, status = null) {
      pendingId = id;
      pendingAction = action;
      pendingStatus = status;

      const modalTitle = $('#confirmationModalLabel');
      const modalBody = $('#confirmationModalBody');
      const confirmBtn = $('#confirmActionButton');
      let titleText, bodyText, btnText, headerClass = 'bg-warning text-dark', btnClass = 'btn-warning';

      if (action === 'set_manual_status') {
          const statusText = status === 'Completat' ? 'Completat' : 'Omès';
          titleText = `Confirmar: ${statusText}`;
          bodyText = `<p>Estàs a punt de marcar el tractament com a <strong>"${statusText}"</strong>. Aquesta acció és reversible.</p>`;
          btnText = `Sí, Marcar com a ${statusText}`;
          if(status === 'Completat') { headerClass = 'bg-success text-white'; btnClass = 'btn-success'; }
          else { headerClass = 'bg-secondary text-white'; btnClass = 'btn-secondary'; }
      } else if (action === 'reactivate_treatment') {
          titleText = 'Confirmar Reactivació';
          bodyText = '<p>Vols reactivar el tractament? El seu estat tornarà a "En curs" o "Programat".</p>';
          btnText = 'Sí, Reactivar';
          headerClass = 'bg-primary text-white'; btnClass = 'btn-primary';
      }
      modalTitle.text(titleText);
      modalBody.html(bodyText);
      confirmBtn.text(btnText).removeClass('btn-warning btn-success btn-secondary btn-primary btn-danger').addClass(btnClass).prop('disabled', false);
      $('#confirmationModal .modal-header').removeClass('bg-warning bg-success bg-secondary bg-primary text-dark text-white').addClass(headerClass);

      bootstrap.Modal.getOrCreateInstance(document.getElementById('confirmationModal')).show();
  }

  // =======================================================
  // ===== INICIO: confirmActionButton (MODIFICADO) ========
  // =======================================================
  $('#confirmActionButton').off('click').on('click', function() {
      if (!pendingAction) return;
      const currentAction = pendingAction, currentId = pendingId, currentStatus = pendingStatus;
      const $button = $(this);
      $button.prop('disabled', true).html('<span class="spinner-border spinner-border-sm"></span> Processant...');
      const confirmationModalInstance = bootstrap.Modal.getOrCreateInstance(document.getElementById('confirmationModal'));

      // --- ★ CORRECCIÓN: Usar APP_BASE_URL ---
      $.post(APP_BASE_URL + 'treatments.php', { ajax: true, action: currentAction, id: currentId, status: currentStatus }, 'json')
          .done(res => {
              showToast(res.message, 'success');
              fetchTreatments();

              // --- ▼▼▼ INICIO BLOQUE AÑADIDO (Email para set_manual_status) ▼▼▼ ---
              if (currentAction === 'set_manual_status' && res.treatment_id && res.new_status) {
                  $.post(APP_BASE_URL + 'treatments.php', {
                      ajax: true,
                      action: 'send_treatment_notification',
                      treatment_id: res.treatment_id,
                      type: (res.new_status === 'Completat' ? 'complete' : 'omit')
                  })
                  .fail(err => console.error('Error enviando email de finalización', err));
              }
              // --- ▲▲▲ FIN BLOQUE AÑADIDO ▲▲▲ ---

              // --- ★ INICIO DE LA MODIFICACIÓN (Reactivar con Modal) ★ ---
              if (currentAction === 'reactivate_treatment' && res.action === 'reactivated' && res.treatment_id) {
                  confirmationModalInstance.hide();
                  showToast("Tractament reactivat. Si us plau, revisa les dates.", 'success');
                  if (typeof initializeTreatmentModalApp === 'function' && typeof pageModalFunctions.populateAndOpenModalCRUD === 'function') {
                      $.getJSON(APP_BASE_URL + 'treatments.php', { ajax: true, action: 'get_treatment_details', id: res.treatment_id })
                          .done(response => {
                              if (response.status === 'success') {
                                  pageModalFunctions.populateAndOpenModalCRUD(response.treatment);
                                  setTimeout(() => {
                                      const datePickerEl = document.getElementById('date_range_picker');
                                      const radioButtonsEl = document.getElementById('delivery-options-wrapper');
                                      if (datePickerEl) {
                                          datePickerEl.classList.add('flash-attention');
                                          $('#treatmentModal .modal-body').animate({
                                              scrollTop: $(datePickerEl).offset().top - $('#treatmentModal .modal-body').offset().top
                                          }, 500);
                                      }
                                      if (radioButtonsEl) {
                                          radioButtonsEl.classList.add('flash-attention');
                                      }
                                      setTimeout(() => {
                                          if (datePickerEl) datePickerEl.classList.remove('flash-attention');
                                          if (radioButtonsEl) radioButtonsEl.classList.remove('flash-attention');
                                      }, 3100);
                                  }, 700);
                              } else {
                                  showToast(response.message || 'Error en carregar dades per a editar.', 'danger');
                              }
                          })
                          .fail(() => showToast('Error de connexió en carregar dades per a editar.', 'danger'));

                  } else {
                      console.error("La funció 'populateAndOpenModalCRUD' no està disponible.");
                      alert("Tractament reactivat. Si us plau, edita les dates manualment.");
                  }

              } else {
                  // Comportament normal per a altres accions
                  confirmationModalInstance.hide();
              }
              // --- ★ FIN DE LA MODIFICACIÓN ★ ---
          })
          .fail(xhr => {
              showToast(xhr.responseJSON?.message || 'Error en l\'operació.', 'danger');
              confirmationModalInstance.hide();
          })
          .always(() => {
              pendingAction = null; pendingId = null; pendingStatus = null;
          });
  });
  // =======================================================
  // ===== FIN: confirmActionButton (MODIFICADO) ===========
  // =======================================================


  $(document).on('click', '.manage-btn', function(e) {
      e.preventDefault();
      if ($(this).is(':disabled') || $(this).hasClass('disabled')) return;
      itemToManage = { id: $(this).data('id'), name: $(this).data('name'), ownerId: $(this).data('owner-id'), patientName: $(this).data('patient-name') };
      const canModify = IS_SUPERADMIN || itemToManage.ownerId == CURRENT_USER_ID;
      // --- ★ CORRECCIÓN: Usar APP_BASE_URL ---
      $.getJSON(APP_BASE_URL + 'treatments.php', { ajax: true, action: 'check_treatment_usage', id: itemToManage.id }, response => {
          const isActive = response.is_active;
          $('#manageModalLabel').text(`Gestionar: ${itemToManage.name}`);
          const modalBody = $('#manageModalBody').empty().append(`<p>Pacient: <strong>${itemToManage.patientName}</strong>.</p>`);
          if (isActive) { modalBody.append(`<div class="alert alert-warning"><i class="bi bi-exclamation-triangle-fill me-2"></i>Aquest tractament està 'En curs' i no es pot eliminar.</div>`); }
          modalBody.append(`<p><strong>Arxivar</strong> l'ocultarà de la teua vista personal sense afectar altres usuaris.</p>`);
          $('#archiveBtn').off('click').on('click', handlePersonalArchive);
          if (canModify) {
              modalBody.append('<hr><p><strong>Eliminar</strong> esborrarà el tractament de forma permanent per a tots els usuaris.</p>');
              $('#deleteBtn').prop('disabled', isActive).attr('title', isActive ? 'No es pot eliminar porque està en ús' : '').show().off('click').on('click', handleDelete);
          } else { $('#deleteBtn').hide(); }
          bootstrap.Modal.getOrCreateInstance(document.getElementById('manageModal')).show();
      }).fail(() => showToast("Error al comprovar l'ús.", 'danger'));;
  });

  function handlePersonalArchive() {
      // --- ★ CORRECCIÓN: Usar APP_BASE_URL ---
      $.post(APP_BASE_URL + 'treatments.php', { ajax: true, action: 'personal_archive', id: itemToManage.id }, 'json')
      .done(res => {
          showToast(res.message, 'success');
          bootstrap.Modal.getOrCreateInstance(document.getElementById('manageModal')).hide();
          fetchTreatments();
      })
      .fail(xhr => showToast(xhr.responseJSON.message, 'danger'));
  }

  function handleDelete() {
        const manageModalInstance = bootstrap.Modal.getOrCreateInstance(document.getElementById('manageModal'));
        if (prompt(`Per a confirmar l'eliminació PERMANENT de "${itemToManage.name.replace(/&#39;/g, "'").replace(/&quot;/g, '"')}", escriu ELIMINAR ací baix:`) === 'ELIMINAR') {

            // --- ★ INICIO DE LA NUEVA LÓGICA DE FLASH ---
            const idToDelete = itemToManage.id;

            // 1. Encontrar el elemento ANTES de borrarlo
            let elementToDelete;
            if (appState.viewMode === 'grid') {
                // En grid, el .view-treatment-btn es el .card-img-top, buscamos la .card padre
                elementToDelete = $(`.card-img-top.view-treatment-btn[data-id="${idToDelete}"]`).closest('.card');
            } else {
                // En lista, buscamos el botón dentro de la fila (tr)
                elementToDelete = $(`tr .view-treatment-btn[data-id="${idToDelete}"]`).closest('tr');
            }

            // 2. Ocultar el modal inmediatamente
            manageModalInstance.hide();

            if (elementToDelete.length > 0) {
                // 3. Aplicar la animación de borrado (definida en style.css)
                elementToDelete.addClass('flash-delete');

                // 4. Esperar a que termine la animación (1.5s)
                setTimeout(() => {
                    // 5. Enviar la petición de borrado SOLO DESPUÉS de la animación
                    // --- ★ CORRECCIÓN: Usar APP_BASE_URL ---
                    $.post(APP_BASE_URL + 'treatments.php', { ajax: true, action: 'delete_treatment', id: idToDelete }, 'json')
                    .done(res => {
                        showToast(res.message, 'success');
                        // 6. Recargar la lista (el elemento ya está invisible)
                        fetchTreatments();
                    })
                    .fail(xhr => {
                        showToast(xhr.responseJSON.message, 'danger');
                        // Si falla, quitamos la clase para que reaparezca
                        elementToDelete.removeClass('flash-delete');
                    });
                }, 1500); // Debe coincidir con la duración de la animación CSS

            } else {
                // Fallback (si no se encontró el elemento, solo borrar y recargar)
                $.post(APP_BASE_URL + 'treatments.php', { ajax: true, action: 'delete_treatment', id: idToDelete }, 'json')
                .done(res => { showToast(res.message, 'success'); fetchTreatments(); })
                .fail(xhr => showToast(xhr.responseJSON.message, 'danger'));
            }
            // --- ★ FIN DE LA NUEVA LÓGICA DE FLASH ---

        } else {
            showToast("L'acció d'eliminació ha sigut cancel·lada.", 'info');
        }
    }

  // --- ★★★ INICIO NUEVOS HANDLERS: TRANSFERENCIA (MODIFICADOS) ★★★ ---
  const transferTreatmentModal = bootstrap.Modal.getOrCreateInstance(document.getElementById('transferTreatmentModal'));
  const transferWarningModal = bootstrap.Modal.getOrCreateInstance(document.getElementById('transferWarningModal'));
  let transferState = {
      treatmentId: null,
      oldCreatorName: '',
      oldCreatorId: null // <<<--- AÑADIDO
  };

  $(document).on('click', '.transfer-btn', function(e) {
      e.preventDefault();
      if ($(this).hasClass('disabled')) return;

      transferState.treatmentId = $(this).data('id');
      transferState.oldCreatorName = $(this).data('creator-name');
      transferState.oldCreatorId = $(this).data('creator-id'); // <<<--- AÑADIDO
      const currentCreatorId = $(this).data('creator-id');

      $('#transferTreatmentName').text($(this).data('name'));
      $('#transferOldFisioName').text(transferState.oldCreatorName);

      const select = $('#transferNewFisioSelect');
      select.empty().append('<option value="">Selecciona un nou fisio...</option>');

      if (allFisios && allFisios.length > 0) {
          allFisios.forEach(f => {
              if (f.id != currentCreatorId) {
                  select.append(new Option(`${f.nombre} ${f.apellido}`, f.id));
              }
          });
      } else {
          select.html('<option value="">Error: No s\'han trobat fisios.</option>');
      }
      transferTreatmentModal.show();
  });

  $('#proceedToWarningBtn').on('click', function() {
      const newFisioId = $('#transferNewFisioSelect').val();
      const newFisioName = $('#transferNewFisioSelect option:selected').text();

      if (!newFisioId) {
          showToast('Has de seleccionar un nou fisio.', 'danger');
          return;
      }

      // Poblar el modal de advertencia
      $('#warnOldFisio').text(transferState.oldCreatorName);
      $('#warnOldFisio2').text(transferState.oldCreatorName);
      $('#warnNewFisio').text(newFisioName);
      $('#warnNewFisio2').text(newFisioName);

      // Guardar los IDs en el botón de confirmación final
      $('#confirmTransferBtn').data('treatment-id', transferState.treatmentId);
      $('#confirmTransferBtn').data('new-fisio-id', newFisioId);
      $('#confirmTransferBtn').data('old-creator-id', transferState.oldCreatorId); // <<<--- AÑADIDO

      transferTreatmentModal.hide();
      transferWarningModal.show();
  });

  $('#confirmTransferBtn').on('click', function() {
      const $button = $(this);
      const treatmentId = $button.data('treatment-id');
      const newFisioId = $button.data('new-fisio-id');
      const oldCreatorId = $button.data('old-creator-id'); // <<<--- AÑADIDO

      $button.prop('disabled', true).html('<span class="spinner-border spinner-border-sm me-2"></span> Transferint...');

      // --- ★ CORRECCIÓN: Usar APP_BASE_URL ---
      $.post(APP_BASE_URL + 'treatments.php', {
          ajax: true,
          action: 'transfer_treatment',
          treatment_id: treatmentId,
          new_fisio_id: newFisioId
      }, 'json')
      .done(res => {
          if (res.status === 'success') {
              showToast(res.message, 'success');
              transferWarningModal.hide();

              // --- ======================================================= ---
              // --- ★★★ INICIO DE LA MODIFICACIÓN (LLAMADA ASÍNCRONA DE EMAIL) ★★★ ---
              // --- ======================================================= ---
              if (treatmentId) {
                  $.post('treatments.php', {
                      ajax: true,
                      action: 'send_treatment_notification',
                      treatment_id: treatmentId,
                      type: 'transfer' // Le decimos al PHP qué email enviar
                  })
                  .fail(function(err) {
                      console.error('Error enviando email de transferencia', err);
                  });
              }
              // --- ======================================================= ---
              // --- ★★★ FIN DE LA MODIFICACIÓN ★★★ ---
              // --- ======================================================= ---


              // --- ★★★ INICIO: MODIFICACIÓN PARA FLASHEAR EL ELEMENTO ★★★ ---
              // --- ★ TAREA 3 (Clonación Lógica): Ya no reiniciamos la página ---
              // appState.currentPage = 1; // <-- ELIMINADO
              const transferredIdToFlash = treatmentId; // 'treatmentId' está en scope
              fetchTreatments().done(() => {
                  if (transferredIdToFlash) {
                      let elementToFlash;
                      if (appState.viewMode === 'grid') {
                          elementToFlash = $(`.card-img-top[data-id="${transferredIdToFlash}"]`).closest('.card');
                      } else {
                          elementToFlash = $(`tr .view-treatment-btn[data-id="${transferredIdToFlash}"]`).closest('tr');
                      }
                      // Usar la función global de footer.php
                      if (typeof flashElement === 'function' && elementToFlash && elementToFlash.length > 0) {
                          flashElement(elementToFlash);
                      }
                  }
              });
              // --- ★★★ FIN: MODIFICACIÓN PARA FLASHEAR ★★★ ---

          } else {
              showToast(res.message || 'Error en la transferència.', 'danger');
          }
      })
      .fail(xhr => {
          showToast(xhr.responseJSON?.message || 'Error de connexió.', 'danger');
      })
      .always(() => {
          $button.prop('disabled', false).html('Sí, Entenc i Vull Transferir');
      });
  });
  // --- ★★★ FIN NUEVOS HANDLERS: TRANSFERENCIA ★★★ ---


  // Filtros / Sort / Paginación
  let searchTimeout;
  $('#searchInput').on('keyup', function() {
      $('#clearSearchBtn').toggle($(this).val().length > 0);
      clearTimeout(searchTimeout);
      searchTimeout = setTimeout(() => { appState.searchQuery = $(this).val(); appState.currentPage = 1; fetchTreatments(); }, 300);
  });
  $('#clearSearchBtn').on('click', () => $('#searchInput').val('').trigger('keyup').focus());
$('#statusFilter').on('change', function() { appState.status = $(this).val(); appState.currentPage = 1; fetchTreatments(); });

// --- AÑADIR ESTE BLOQUE ---
  $('#categoryFilter').on('change', function() {
      appState.categoryId = $(this).val();
      appState.currentPage = 1;
      fetchTreatments();
  });
  // --- FIN DE LA ADICIÓN ---

  $('#filterMyTreatments').on('change', function() { appState.filterMine = $(this).is(':checked'); appState.currentPage = 1; fetchTreatments(); });
  $(document).on('click', '.sortable-header, .sort-btn', function() {
      const newSortBy = $(this).data('sort');
       if(!newSortBy) return;

       // --- ★ TAREA 1 (Nueva Columna) ---
       // Añadir 'created_at' a las columnas válidas
       const sortableColumns = ['start_date', 'title', 'paciente_apellido', 'status', 'creator_surname', 'collaborators', 'created_at'];
       // --- ★ FIN TAREA 1 ---
       if (!sortableColumns.includes(newSortBy)) {
           return;
       }

      if (appState.sortBy === newSortBy) { appState.sortOrder = appState.sortOrder === 'ASC' ? 'DESC' : 'ASC'; }
      else {
          appState.sortBy = newSortBy;
          appState.sortOrder = (newSortBy === 'paciente_apellido' || newSortBy === 'title' || newSortBy === 'creator_surname' || newSortBy === 'collaborators') ? 'ASC' : 'DESC';
      }
      appState.currentPage = 1;
      fetchTreatments();
  });
   $(document).on('click', '.page-link', function(e) { e.preventDefault(); appState.currentPage = $(this).data('page'); fetchTreatments(); });

  // --- INICIALIZACIÓN ---

  function initializeApp() {
      if ($('#filterMyTreatments').length > 0) {
          // --- ★ INICIO CORRECCIÓN 2: Leer ?filter=mine de la URL ---
          const urlParams = new URLSearchParams(window.location.search);
          if (urlParams.get('filter') === 'mine') {
              appState.filterMine = true;
          }
          // --- ★ FIN CORRECCIÓN 2 ---
          $('#filterMyTreatments').prop('checked', appState.filterMine);
      }

      // --- ★ TAREA EXTRA (Ocultar botones) ---
      $('.toggle-view-btn').removeClass('active');
      if (appState.viewMode === 'grid') {
          $('#gridViewBtn').addClass('active');
          $('#sort-buttons-group').show();
      } else {
          $('#listViewBtn').addClass('active');
          $('#sort-buttons-group').hide();
      }
      // --- ★ FIN TAREA EXTRA ---

      // Carga dependencias (pacientes, fisios, categorías, tags)
      $.when(
          // --- ★ CORRECCIÓN: Usar APP_BASE_URL ---
          $.getJSON(APP_BASE_URL + 'treatments.php', { ajax: true, action: 'get_form_data' }),
          $.getJSON(APP_BASE_URL + 'exercises.php', { ajax: true, action: 'get_form_dependencies' })
      ).done(function(formDataRes, exerciseDepsRes){

          // Poblar datos para el modal global
          const formData = formDataRes[0];
          if (formData.status === 'success') {
              allPacients = formData.pacients || [];
              allFisios = formData.fisios || [];

              // Poblar el <select> de pacientes (que está en el modal de footer.php)
              const pacienteSelect = $('#paciente_id_select');
              pacienteSelect.empty().append('<option value="">Selecciona un pacient...</option>');
              allPacients.forEach(p => {
                  pacienteSelect.append(new Option(`${p.apellido}, ${p.nombre}`, p.id));
              });

          } else {
              showToast("Error crític carregant llistes d'usuaris.", 'danger');
          }

          const exerciseDeps = exerciseDepsRes[0];
          if (exerciseDeps.status === 'success') {
              allCategories = exerciseDeps.categories || [];
              allTags = exerciseDeps.tags || [];

              // ★★★ AÑADIR ESTE BLOQUE PARA POBLAR EL FILTRO ★★★
              const mainCategoryFilter = $('#categoryFilter');
              mainCategoryFilter.html('<option value="">Totes les Categories</option>');
              // Filtrar y ordenar padres
              const parents = allCategories.filter(c => !c.parent_id);
              parents.sort((a, b) => a.name.localeCompare(b.name));

              parents.forEach(p => {
                 mainCategoryFilter.append(new Option(p.name, p.id)); // Añadir padre
                 // Encontrar y ordenar hijos
                 const children = allCategories.filter(c => c.parent_id == p.id);
                 children.sort((a, b) => a.name.localeCompare(b.name));
                 children.forEach(c => {
                     mainCategoryFilter.append(new Option(`↳ ${c.name}`, c.id)); // Añadir hijo
                 });
              });
              // ★★★ FIN ★★★

          } else {
              showToast("Error crític carregant categories/etiquetes.", 'danger');
          }

          // *** LA LLAMADA CLAVE ***
          // Inicializar el script del modal global AHORA que tenemos los datos
          if (typeof initializeTreatmentModalApp === 'function') {
              // --- ★ MODIFICACIÓN: Asignar a la variable de scope superior ★ ---
              pageModalFunctions = initializeTreatmentModalApp({
                  allFisios: allFisios,
                  allCategories: allCategories,
                  allTags: allTags,
                  IS_SUPERADMIN: IS_SUPERADMIN,
                  CURRENT_USER_ID: CURRENT_USER_ID,
                  PATIENT_ID: null, // Nulo, porque esta NO es la ficha de un paciente
                  PATIENT_FULLNAME: null,


// CÓDIGO NECESARIO (en treatments.php, línea ~1537)
onSaveSuccess: function(idToHighlight) {
    // 1. Llama a la función de refresco (que ahora atenúa) y espera a que termine
    fetchTreatments().done(function() {
        // 2. Si no hay ID para resaltar (ej. al editar fechas de reactivación), no hagas nada
        if (!idToHighlight) return;

        // 3. Busca el elemento (fila de tabla o tarjeta de grid)
        let elementToFlash;
        if (appState.viewMode === 'grid') {
            // En grid, el data-id está en el botón. Buscamos la .card padre.
            elementToFlash = $(`.card-img-top[data-id="${idToHighlight}"]`).closest('.card');
        } else {
            // En lista, el data-id está en los botones de acción. Buscamos la <tr> padre.
            elementToFlash = $(`tr .view-treatment-btn[data-id="${idToHighlight}"]`).closest('tr');
        }

        // 4. Si lo encontramos, ¡hazlo brillar!
        if (elementToFlash && elementToFlash.length > 0) {

            // Damos 50ms al navegador para que termine de repintar la lista
            setTimeout(() => {
                // Nos aseguramos de que sea visible (scroll)
                // (La función flashElement ya hace esto, pero lo duplicamos por seguridad)
                $('html, body').animate({
                    scrollTop: elementToFlash.offset().top - 150 // -150px para dar margen
                }, 500);

                // Usamos la función global de footer.php para aplicar el flash
                if (typeof flashElement === 'function') {
                    flashElement(elementToFlash);
                } else {
                    // Fallback si flashElement no estuviera cargada
                    elementToFlash.addClass('flash-attention');
                    setTimeout(() => {
                        elementToFlash.removeClass('flash-attention');
                    }, 3500);
                }
            }, 50); // <-- Este delay es clave para la fluidez

        }
    });
}
                  // --- ★ FIN DE LA CORRECCIÓN ★ ---
              });
          } else {
              console.error("No se pudo inicializar treatment_modal.js");
              showToast("Error crític en carregar el formulari de tractaments.", 'danger');
          }

          // Carga inicial de tratamientos (de esta página)
          fetchTreatments();

      }).fail(function(){
            showToast("Error crític carregant dades inicials.", 'danger');
      });
  }

  initializeApp();

}); // Fin de $(document).ready()
</script>
</body>
</html>
