<?php
// /archive.php

// --- 1. GESTIÓN DE SESIÓN Y PERMISOS ---
session_start();
if (!isset($_SESSION['user_id'])) { header('Location: index.php'); exit; }
if (!in_array($_SESSION['user_rol'], ['superadmin', 'fisio'])) { header('Location: dashboard.php'); exit; }

require 'db.php';
$user_rol = $_SESSION['user_rol'];
$user_id = $_SESSION['user_id'];
define('RECORDS_PER_PAGE', 10);

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

    try {
        switch ($action) {
            // --- INICIO ELIMINACIÓN: Se ha borrado toda la lógica de 'read_archived_pacients', 'get_archived_patient_details', 'unarchive_user', 'delete_archived_user' y 'get_patient_history' ---

            // --- LÓGICA PARA ARCHIVO PERSONAL DE RECURSOS (FISIOS Y SUPERADMIN) ---
            case 'read_personal_archive':
                $item_type = $_GET['type'] ?? 'media';
                if (!in_array($item_type, ['media', 'video', 'image', 'ejercicio', 'protocol', 'treatment'])) { throw new Exception('Tipus d\'element no vàlid.'); }

                $query = "";
                 if ($item_type === 'media') {
                    $query = "
                        SELECT i.id, i.title, c.nombre as creator_name, 'video' as type, i.id_uploader as creator_id
                        FROM videos i JOIN archivado_personal ap ON i.id = ap.item_id JOIN cuentas c ON i.id_uploader = c.id
                        WHERE ap.fisio_id = :user_id AND ap.item_type = 'video'
                        UNION ALL
                        SELECT i.id, i.title, c.nombre as creator_name, 'image' as type, i.id_uploader as creator_id
                        FROM images i JOIN archivado_personal ap ON i.id = ap.item_id JOIN cuentas c ON i.id_uploader = c.id
                        WHERE ap.fisio_id = :user_id AND ap.item_type = 'image'
                        ORDER BY title
                    ";
                    $params = [':user_id' => $user_id];
                } else {
                    $table_map = ['ejercicio' => 'ejercicios', 'protocol' => 'tratamientos', 'treatment' => 'tratamientos'];
                    $creator_col_map = ['ejercicio' => 'id_creator', 'protocol' => 'creator_fisio_id', 'treatment' => 'creator_fisio_id'];
                    $table = $table_map[$item_type];
                    $creator_col = $creator_col_map[$item_type];

                    $extra_join = ($item_type === 'treatment') ? "JOIN cuentas p ON i.paciente_id = p.id" : "";

                    // --- MODIFICACIÓ: Afegim p.id as paciente_id ---
                    $extra_select = ($item_type === 'treatment') ? ", p.id as paciente_id, p.nombre as paciente_nombre, p.apellido as paciente_apellido" : "";


                    $query = "SELECT i.id, i.title, c.nombre as creator_name, i.$creator_col as creator_id $extra_select FROM $table i JOIN archivado_personal ap ON i.id = ap.item_id JOIN cuentas c ON i.$creator_col = c.id $extra_join WHERE ap.fisio_id = :user_id AND ap.item_type = :item_type ORDER BY i.title";
                    $params = [':user_id' => $user_id, ':item_type' => $item_type];
                }

                $stmt = $db->prepare($query);
                $stmt->execute($params);
                echo json_encode(['status' => 'success', 'items' => $stmt->fetchAll()]);
                break;

            case 'get_archived_item_details':
                $id = (int)$_GET['id'];
                $type = $_GET['type'];
                $data = [];

                if ($type === 'video' || $type === 'image') {
                    $table = ($type === 'video') ? 'videos' : 'images';
                    $stmt = $db->prepare("SELECT title, description, filename FROM $table WHERE id = ?");
                    $stmt->execute([$id]);
                    $data = $stmt->fetch(PDO::FETCH_ASSOC);
                } else if ($type === 'ejercicio') {
                    $stmt = $db->prepare("SELECT e.*, v.filename as video_filename, i.filename as image_filename, cat.name as category_name FROM ejercicios e LEFT JOIN videos v ON e.id_video = v.id LEFT JOIN images i ON e.id_image = i.id LEFT JOIN categorias cat ON e.id_categoria = cat.id WHERE e.id = ?");
                    $stmt->execute([$id]);
                    $data = $stmt->fetch(PDO::FETCH_ASSOC);
                    $tagsStmt = $db->prepare("SELECT t.name FROM ejercicio_tags et JOIN tags t ON et.tag_id = t.id WHERE et.ejercicio_id = ?");
                    $tagsStmt->execute([$id]);
                    $data['tags'] = $tagsStmt->fetchAll(PDO::FETCH_COLUMN);
                } else if ($type === 'protocol' || $type === 'treatment') {
                    $is_protocol = $type === 'protocol' ? 1 : 0;
                     $query = "
                        SELECT
                            t.title, t.anamnesis, t.diagnostico, t.status, t.start_date, t.end_date,
                            p.nombre as paciente_nombre, p.apellido as paciente_apellido,
                            c.nombre as creator_name, c.apellido as creator_surname
                        FROM tratamientos t
                        LEFT JOIN cuentas p ON t.paciente_id = p.id
                        JOIN cuentas c ON t.creator_fisio_id = c.id
                        WHERE t.id = ? AND t.is_protocol = ?
                    ";
                    $stmt = $db->prepare($query);
                    $stmt->execute([$id, $is_protocol]);
                    $data = $stmt->fetch(PDO::FETCH_ASSOC);

                    $exStmt = $db->prepare("SELECT e.title, te.frecuencia, te.series, te.repetitions, te.rest_time, te.notes as pauta_notes, v.filename as video_filename, i.filename as image_filename 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.id");
                    $exStmt->execute([$id]);
                    $data['exercises'] = $exStmt->fetchAll(PDO::FETCH_ASSOC);
                }

                if (!$data) throw new Exception('Element no trobat.');
                echo json_encode(['status' => 'success', 'data' => $data]);
                break;

            case 'unarchive_personal_item':
                 if (!in_array($_POST['type'], ['video', 'image', 'ejercicio', 'protocol', 'treatment'])) { throw new Exception('Tipus d\'element no vàlid per a desarxivar.'); }

                // --- MODIFICACIÓ: Lògica de redirecció eliminada ---
                $stmt = $db->prepare("DELETE FROM archivado_personal WHERE fisio_id = :user_id AND item_id = :item_id AND item_type = :item_type");
                $stmt->execute([':user_id' => $user_id, ':item_id' => (int)$_POST['id'], ':item_type' => $_POST['type']]);
                echo json_encode([
                    'status' => 'success',
                    'message' => ucfirst($_POST['type']) . ' des-arxivat correctament.'
                ]);
                break;

            // --- NUEVA ACCIÓN ---
            case 'delete_personal_item_permanently':
                            if ($user_rol === 'paciente') { throw new Exception('Accés denegat.'); }

                            $id = (int)$_POST['id'];
                            $type = $_POST['type'];

                            $table = '';
                            $creator_col = '';
                            $folder = ''; // <-- NUEVO
                            $placeholder = ''; // <-- NUEVO

                            switch ($type) {
                                case 'video':
                                    $table = 'videos';
                                    $creator_col = 'id_uploader';
                                    $folder = 'videos/'; // <-- NUEVO
                                    $placeholder = 'placeholder.mp4'; // <-- NUEVO
                                    break;
                                case 'image':
                                    $table = 'images';
                                    $creator_col = 'id_uploader';
                                    $folder = 'images/'; // <-- NUEVO
                                    $placeholder = 'placeholder.jpg'; // <-- NUEVO
                                    break;
                                case 'ejercicio': $table = 'ejercicios'; $creator_col = 'id_creator'; break;
                                case 'protocol': $table = 'tratamientos'; $creator_col = 'creator_fisio_id'; break;
                                case 'treatment': $table = 'tratamientos'; $creator_col = 'creator_fisio_id'; break;
                                default: throw new Exception('Tipus d\'element no vàlid.');
                            }

                            // --- INICIO DE LA CORRECCIÓN ---
                            // Comprobación de permisos
                            // Añadimos 'filename' solo si es video o imagen
                            $filename_select_sql = ($type === 'video' || $type === 'image') ? ", filename" : "";

                            $stmtCheck = $db->prepare("SELECT $creator_col $filename_select_sql FROM $table WHERE id = ?");
                            $stmtCheck->execute([$id]);
                            $item_data = $stmtCheck->fetch(PDO::FETCH_ASSOC);
                            // --- FIN DE LA CORRECCIÓN ---

                            if (!$item_data) { throw new Exception("L'element no existeix."); }

                            $item_creator_id = $item_data[$creator_col];
                            $item_filename = $item_data['filename'] ?? null; // <-- Esto ahora es seguro

                            if ($user_rol !== 'superadmin' && $item_creator_id != $user_id) {
                                throw new Exception("No tens permís per a eliminar aquest element (només el creador o superadmin poden).");
                            }

                            // Si se tienen permisos, proceder a la eliminación
                            $db->beginTransaction();

                            // 1. Eliminar de la lista de archivados (para todos los que lo tengan)
                            $db->prepare("DELETE FROM archivado_personal WHERE item_id = ? AND item_type = ?")->execute([$id, $type]);

                            // 2. Limpiar dependencias y eliminar el item
                            if ($type === 'video') {
                                $db->prepare("UPDATE ejercicios SET id_video = NULL WHERE id_video = ?")->execute([$id]);
                                $db->prepare("DELETE FROM videos WHERE id = ?")->execute([$id]);
                            } elseif ($type === 'image') {
                                $db->prepare("UPDATE ejercicios SET id_image = NULL WHERE id_image = ?")->execute([$id]);
                                $db->prepare("DELETE FROM images WHERE id = ?")->execute([$id]);
                            } elseif ($type === 'ejercicio') {
                                // (Los ejercicios no tienen archivos físicos directos, esta lógica está bien)
                                $db->prepare("DELETE FROM ejercicio_tags WHERE ejercicio_id = ?")->execute([$id]);
                                $db->prepare("DELETE FROM tratamiento_ejercicios WHERE ejercicio_id = ?")->execute([$id]);
                                $db->prepare("DELETE FROM ejercicios WHERE id = ?")->execute([$id]);
                            } elseif ($type === 'protocol' || $type === 'treatment') {
                                if ($type === 'protocol') {
                                     $stmtUsageCheck = $db->prepare("SELECT COUNT(id) FROM tratamientos WHERE protocolo_origen_id = :id AND status IN ('En curs', 'Programat')");
                                     $stmtUsageCheck->execute([':id' => $id]);
                                     if ($stmtUsageCheck->fetchColumn() > 0) {
                                         $db->rollBack();
                                         throw new Exception("El protocol està en ús en un tractament actiu o programat i no es pot eliminar.");
                                     }
                                }
                                $db->prepare("DELETE FROM tratamiento_ejercicios WHERE tratamiento_id = ?")->execute([$id]);
                                $db->prepare("DELETE FROM tratamiento_fisios_asignados WHERE tratamiento_id = ?")->execute([$id]);
                                $db->prepare("DELETE FROM tratamientos WHERE id = ?")->execute([$id]);
                            }

                            // --- ¡¡¡AÑADIDO!!! ---
                            // 3. Eliminar el archivo físico si es un video o imagen
                            if (($type === 'video' || $type === 'image') && $item_filename) {
                                $filepath = $folder . $item_filename;
                                if (!filter_var($item_filename, FILTER_VALIDATE_URL) && file_exists($filepath) && $item_filename !== $placeholder) {
                                    @unlink($filepath); // Usar @ para suprimir errores si el archivo ya no existía
                                }
                            }
                            // --- FIN AÑADIDO ---

                            $db->commit();
                            echo json_encode(['status' => 'success', 'message' => 'Element eliminat permanentment.']);
                            break;
        }
    } catch (Exception $e) {
        if (isset($db) && $db->inTransaction()) $db->rollBack();
        http_response_code(400);
        echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
    }
    exit;
}

$page_title = "Arxiu";
include 'partials/header.php';
?>

<style>
/* Estilo para miniaturas en el modal de visualización */
.view-ex-thumb { width: 100px; height: 60px; object-fit: cover; border-radius: 0.25rem; background-color: #343a40; }

/* --- NOU ESTIL PER AL BOTÓ TORNAR --- */
.archive-back-btn-container {
    position: absolute;
    top: 10px;
    right: 15px;
    z-index: 10; /* Per sobre del contingut de la pestanya */
}
.tab-pane {
    position: relative; /* Necessari per al posicionament absolut del botó */
    padding-top: 50px; /* Deixar espai per al botó */
}

/* --- CORRECCIÓN Z-INDEX Y DROPDOWNS --- */
.dropdown-item i.bi { margin-right: 0.5rem; }
.dropdown .btn.dropdown-toggle:hover { color: #FFF !important; }

/* REGLA CLAVE: Permite que los menús salgan de la tabla/card */
td .dropdown, .card-footer .dropdown, .btn-group {
    position: static;
}
</style>

<main class="main-content container mt-4" style="max-width: 1420px;">
    <h1 class="h3 mb-4">Arxiu</h1>

    <div class="card shadow-sm">
        <div class="card-body">
            <ul class="nav nav-tabs mb-3" id="archiveTabs" role="tablist">
                <li class="nav-item" role="presentation"><button class="nav-link active" id="media-tab" data-bs-toggle="tab" data-bs-target="#media-panel" type="button">Els Meus Medis Arxivats</button></li>
                <li class="nav-item" role="presentation"><button class="nav-link" id="exercises-tab" data-bs-toggle="tab" data-bs-target="#exercises-panel" type="button">Els Meus Exercicis Arxivats</button></li>
                <li class="nav-item" role="presentation"><button class="nav-link" id="protocols-tab" data-bs-toggle="tab" data-bs-target="#protocols-panel" type="button">Els Meus Protocols Arxivats</button></li>
                <li class="nav-item" role="presentation"><button class="nav-link" id="treatments-tab" data-bs-toggle="tab" data-bs-target="#treatments-panel" type="button">Els Meus Tractaments Arxivats</button></li>

            </ul>

            <div class="tab-content" id="archiveTabsContent">
                <div class="tab-pane fade show active" id="media-panel" role="tabpanel">
                    <!-- BOTÓ TORNAR AFEGIT -->
                    <div class="archive-back-btn-container">
                        <a href="gallery.php" class="btn btn-outline-secondary btn-sm">
                            <i class="bi bi-arrow-left me-1"></i> Tornar a Galeria de Medis
                        </a>
                    </div>
                     <p class="text-muted small">Mostra els vídeos i imatges que has arxivat personalment. Estan ocults a la teua Galeria de Medis, però altres fisios els poden seguir veient.</p>
                    <div id="archived-media-container"></div>
                </div>
                <div class="tab-pane fade" id="exercises-panel" role="tabpanel">
                    <!-- BOTÓ TORNAR AFEGIT -->
                    <div class="archive-back-btn-container">
                        <a href="exercises.php" class="btn btn-outline-secondary btn-sm">
                            <i class="bi bi-arrow-left me-1"></i> Tornar al Catàleg d'Exercicis
                        </a>
                    </div>
                     <p class="text-muted small">Mostra els exercicis que has arxivat personalment. Estan ocults al teu Catàleg d'Exercicis, però altres fisios els poden seguir veient.</p>
                    <div id="archived-exercises-container"></div>
                </div>
                 <div class="tab-pane fade" id="protocols-panel" role="tabpanel">
                    <!-- BOTÓ TORNAR AFEGIT -->
                    <div class="archive-back-btn-container">
                        <a href="protocols.php" class="btn btn-outline-secondary btn-sm">
                            <i class="bi bi-arrow-left me-1"></i> Tornar a Biblioteca de Protocols
                        </a>
                    </div>
                     <p class="text-muted small">Mostra els protocols que has arxivat personalment. Estan ocults a la teua Biblioteca de Protocols, però altres fisios els poden seguir veient.</p>
                     <div id="archived-protocols-container"></div>
                </div>
                <div class="tab-pane fade" id="treatments-panel" role="tabpanel">
                    <!-- BOTÓ TORNAR DINÀMIC AFEGIT -->
                    <div class="archive-back-btn-container">
                        <a href="treatments.php" id="treatments-back-btn" class="btn btn-outline-secondary btn-sm">
                            <i class="bi bi-arrow-left me-1"></i> Tornar a Llistat General
                        </a>
                        <a href="#" id="treatments-patient-back-btn" class="btn btn-info btn-sm" style="display:none;">
                            <i class="bi bi-person-video me-1"></i> Tornar a Fitxa de <span id="back-btn-patient-name" class="fw-bold">...</span>
                        </a>
                    </div>
                     <p class="text-muted small">Mostra els tractaments que has arxivat personalment. Estan ocults a la teua llista de Tractaments.</p>
                     <div id="archived-treatments-container"></div>
                </div>
            </div>
        </div>
    </div>
</main>

<div class="modal fade" id="viewItemModal" tabindex="-1"><div class="modal-dialog modal-lg"><div class="modal-content"><div class="modal-header"><h5 class="modal-title" id="viewItemModalLabel"></h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div><div class="modal-body" id="viewItemModalBody"></div><div class="modal-footer"><button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Tancar</button></div></div></div></div>

<div class="modal fade" id="unarchivePersonalConfirmModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Confirmar Restauració</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <p>Vols restaurar <strong id="personalItemNameToUnarchive"></strong> a la teua llista principal?</p>
            </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-success" id="confirmUnarchivePersonalBtn">Sí, Restaurar</button>
            </div>
        </div>
    </div>
</div>

<!-- NUEVO MODAL DE ELIMINACIÓN -->
<div class="modal fade" id="deletePersonalConfirmModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-danger text-white">
                <h5 class="modal-title">Confirmar Eliminació Permanent</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <p class="text-danger"><i class="bi bi-exclamation-triangle-fill me-2"></i><strong>Acció Irreversible!</strong></p>
                <p>Estàs a punt d'eliminar permanentment <strong id="personalItemNameToDelete"></strong>.</p>
                <p>Aquesta acció l'esborrarà de la base de dades per a <strong>TOTS</strong> els usuaris, no només de la teua vista.</p>
                <p>Si l'element (vídeo, exercici...) està sent utilitzat en tractaments, pot causar errors.</p>
            </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-danger" id="confirmDeletePersonalBtn">Sí, Eliminar Permanentment</button>
            </div>
        </div>
    </div>
</div>


<?php include 'partials/footer.php'; ?>

<script>
$(document).ready(function() {
    const IS_SUPERADMIN = '<?= $user_rol ?>' === 'superadmin';
    const CURRENT_USER_ID = <?= $user_id ?>; // Necesitamos el ID del usuario actual
    const viewItemModal = new bootstrap.Modal('#viewItemModal');
    const unarchivePersonalConfirmModal = new bootstrap.Modal('#unarchivePersonalConfirmModal');
    const deletePersonalConfirmModal = new bootstrap.Modal('#deletePersonalConfirmModal'); // Nuevo modal
    
    function isMobileView() {
        return window.innerWidth < 767.98;
    }

    // --- MODIFICAT: 'personalItemToManage' ara guardarà les dades del pacient ---
    let personalItemToManage = { id: null, type: '', name: '', creatorId: null, pacienteId: null, pacienteName: null };
    // Variable per al botó dinàmic
    let lastUnarchivedPatient = { id: null, name: '' };
    // --- FI MODIFICACIÓ ---

    function getImagePath(filename) {
        if (!filename) return 'logos/img_defecte.jpg';
        const systemImages = ['logo.jpg', 'logo2.jpg', 'img_defecte.jpg'];
        return systemImages.includes(filename) ? `logos/${filename}` : `images/${filename}`;
    }

    function getStatusBadge(status) {
        switch(status) {
            case 'En curs': return `<span class="badge bg-warning text-dark">En curs</span>`;
            case 'Programat': return `<span class="badge bg-info">Programat</span>`;
            case 'Completat': return `<span class="badge bg-success">Completat</span>`;
            case 'Omés': return `<span class="badge bg-secondary">Omés</span>`;
            default: return `<span class="badge bg-light text-dark">${status}</span>`;
        }
    }

    // --- INICIO ELIMINACIÓN: Toda la lógica JS 'if (IS_SUPERADMIN) { ... }' para pacientes ha sido eliminada (fetchArchivedPacients, renderArchiveTable, renderPagination, y todos sus '.on(click)') ---

    // --- Lógica para Recursos Personales (Fisios y Superadmin) ---
    function fetchPersonalArchive(itemType) {
        const idSuffixMap = { 'media': 'media', 'ejercicio': 'exercises', 'protocol': 'protocols', 'treatment': 'treatments' };
        const idSuffix = idSuffixMap[itemType];
        const container = $(`#archived-${idSuffix}-container`);
        container.html('<div class="text-center p-5"><div class="spinner-border"></div></div>');
        $.getJSON('archive.php', { ajax: true, action: 'read_personal_archive', type: itemType })
        .done(res => renderPersonalArchive(res.items, itemType, container))
        .fail(() => container.html('<div class="alert alert-danger">Error en carregar.</div>'));
    }

 function renderPersonalArchive(items, itemType, container) {
        container.empty();
        container.removeClass('row g-3'); // Limpiar clases previas

        if (items.length === 0) {
            let message = 'elements';
            if (itemType === 'media') message = 'medis';
            if (itemType === 'ejercicio') message = 'exercicis';
            if (itemType === 'protocol') message = 'protocols';
            if (itemType === 'treatment') message = 'tractaments';
            container.html(`<div class="alert alert-secondary text-center">No tens cap ${message} arxivat.</div>`);
            return;
        }

        const isMobile = isMobileView();

        if (isMobile) {
            // --- VISTA MÓVIL (TARJETAS) ---
            container.addClass('row g-3'); // Grid layout
            
            items.forEach(item => {
                const finalType = item.type || itemType;
                const pacienteId = item.paciente_id || '';
                const pacienteName = (item.paciente_apellido && item.paciente_nombre) ? `${item.paciente_apellido}, ${item.paciente_nombre}` : '';
                const isCreator = item.creator_id == CURRENT_USER_ID;
                const canDelete = IS_SUPERADMIN || isCreator;

                // Botones
                let buttonsHtml = `
                    <button class="btn btn-sm btn-outline-info view-personal-item-btn" data-id="${item.id}" data-type="${finalType}" title="Veure"><i class="bi bi-eye"></i></button>
                    <button class="btn btn-sm btn-outline-success unarchive-personal-btn" data-id="${item.id}" data-type="${finalType}" data-name="${item.title}" data-paciente-id="${pacienteId}" data-paciente-name="${pacienteName}" title="Desarxivar"><i class="bi bi-arrow-counterclockwise"></i></button>
                `;
                if (canDelete) {
                    buttonsHtml += `<button class="btn btn-sm btn-outline-danger delete-personal-btn" data-id="${item.id}" data-type="${finalType}" data-name="${item.title}" data-creator-id="${item.creator_id}" title="Eliminar"><i class="bi bi-trash"></i></button>`;
                }

                // Contenido específico según tipo
                let extraInfo = '';
                if (itemType === 'media') extraInfo = `<span class="badge bg-light text-dark border mb-2">${item.type}</span>`;
                if (itemType === 'treatment') extraInfo = `<p class="card-text small mb-1 text-muted"><i class="bi bi-person"></i> ${pacienteName}</p>`;

                const cardHtml = `
                <div class="col-12">
                    <div class="card shadow-sm h-100">
                        <div class="card-body">
                            <div class="d-flex justify-content-between align-items-start">
                                <h6 class="card-title fw-bold text-truncate w-75">${item.title}</h6>
                                ${itemType === 'media' ? extraInfo : ''}
                            </div>
                            ${itemType !== 'media' ? extraInfo : ''}
                            <p class="card-text small text-muted mb-0">Creador: ${item.creator_name || 'N/A'}</p>
                        </div>
                        <div class="card-footer bg-white border-top-0 d-flex justify-content-end">
                            <div class="btn-group">${buttonsHtml}</div>
                        </div>
                    </div>
                </div>`;
                container.append(cardHtml);
            });

        } else {
            // --- VISTA ESCRITORIO (TABLA - Lógica Original) ---
            let tableHtml = '<table class="table table-hover align-middle"><thead><tr><th>Títol</th>';

            if (itemType === 'media') tableHtml += '<th>Tipus</th>';
            if (itemType === 'treatment') tableHtml += '<th>Pacient</th>';

            tableHtml += '<th>Creador</th><th class="text-end">Accions</th></tr></thead><tbody>';
            items.forEach(item => {
                const finalType = item.type || itemType;
                const pacienteId = item.paciente_id || '';
                const pacienteName = (item.paciente_apellido && item.paciente_nombre) ? `${item.paciente_apellido}, ${item.paciente_nombre}` : '';

                const isCreator = item.creator_id == CURRENT_USER_ID;
                const canDelete = IS_SUPERADMIN || isCreator;
                let deleteButtonHtml = '';
                if (canDelete) {
                    deleteButtonHtml = `<button class="btn btn-sm btn-outline-danger delete-personal-btn" data-id="${item.id}" data-type="${finalType}" data-name="${item.title}" data-creator-id="${item.creator_id}" title="Eliminar Permanentment"><i class="bi bi-trash"></i></button>`;
                }

                tableHtml += `
                <tr>
                    <td>${item.title}</td>
                    ${itemType === 'media' ? `<td><span class="badge bg-light text-dark border">${item.type}</span></td>` : ''}
                    ${itemType === 'treatment' ? `<td>${pacienteName}</td>` : ''}
                    <td>${item.creator_name || 'N/A'}</td>
                    <td class="text-end">
                        <div class="btn-group">
                            <button class="btn btn-sm btn-outline-info view-personal-item-btn" data-id="${item.id}" data-type="${finalType}" title="Veure"><i class="bi bi-eye"></i></button>
                            <button class="btn btn-sm btn-outline-success unarchive-personal-btn"
                                    data-id="${item.id}"
                                    data-type="${finalType}"
                                    data-name="${item.title}"
                                    data-paciente-id="${pacienteId}"
                                    data-paciente-name="${pacienteName}"
                                    title="Desarxivar">
                                <i class="bi bi-arrow-counterclockwise"></i>
                            </button>
                            ${deleteButtonHtml}
                        </div>
                    </td>
                </tr>`;
            });
            container.html(tableHtml + '</tbody></table>');
        }
    }

    $(document).on('click', '.view-personal-item-btn', function() {
        const id = $(this).data('id');
        const type = $(this).data('type');

        $('#viewItemModalLabel').text('Carregant...');
        $('#viewItemModalBody').html('<div class="text-center p-5"><div class="spinner-border"></div></div>');
        viewItemModal.show();

        $.getJSON('archive.php', { ajax: true, action: 'get_archived_item_details', id: id, type: type })
        .done(res => {
            const data = res.data;
            $('#viewItemModalLabel').text(data.title);
            let contentHtml = '';
            let playerHtml = '';
            const video_filename = data.video_filename || (type === 'video' ? data.filename : null);
            const image_filename = data.image_filename || (type === 'image' ? data.filename : null);

            if (video_filename) {
                const isEmbed = video_filename.startsWith('http');
                const videoSrc = isEmbed ? video_filename : `videos/${video_filename}`;
                playerHtml = isEmbed ? `<iframe src="${videoSrc}" class="w-100 mb-3" style="aspect-ratio: 16/9;" frameborder="0" allowfullscreen></iframe>` : `<video controls controlsList="nodownload" preload="metadata" src="${videoSrc}" class="w-100 mb-3"></video>`;
            } else if (image_filename) {
                playerHtml = `<div class="ratio ratio-16x9 bg-dark rounded mb-3"><img src="images/${image_filename}" style="object-fit: contain; width: 100%; height: 100%;" alt="${data.title}"></div>`;
            }

            if (type === 'video' || type === 'image') {
                contentHtml = playerHtml;
                if (data.description) {
                    contentHtml += `<p class="mt-3 text-muted">${data.description}</p>`;
                }
            } else if (type === 'ejercicio') {
                contentHtml = playerHtml;
                contentHtml += `<ul class="list-group list-group-flush mt-3">
                    <li class="list-group-item"><strong>Pauta:</strong> ${data.series} series de ${data.repetitions} reps, amb ${data.rest_time} de descans.</li>
                    <li class="list-group-item"><strong>Categoria:</strong> ${data.category_name || 'No especificada'}</li>
                    <li class="list-group-item"><strong>Etiquetes:</strong> ${data.tags.map(t => `<span class="badge bg-secondary me-1">${t}</span>`).join(' ')}</li>`;
                if(data.notes) {
                    contentHtml += `<li class="list-group-item"><strong>Notes:</strong><br><p class="text-muted mb-0">${data.notes}</p></li>`;
                }
                contentHtml += `</ul>`;
            } else if (type === 'protocol' || type === 'treatment') {
                let headerHtml = `<div class="row mb-4 small">`;
                if (data.paciente_nombre) {
                    headerHtml += `<div class="col-md-6">
                        <h6 class="text-dark mb-1"><i class="bi bi-person-badge me-2"></i>Pacient</h6>
                        <p class="ps-3 mb-0">${data.paciente_apellido}, ${data.paciente_nombre}</p>
                    </div>`;
                }
                if (data.creator_name) {
                    headerHtml += `<div class="col-md-6">
                        <h6 class="text-dark mb-1"><i class="bi bi-person-circle me-2"></i>Creat per</h6>
                        <p class="ps-3 mb-0">${data.creator_name} ${data.creator_surname}</p>
                    </div>`;
                }
                headerHtml += `</div>`;
                 if (data.status && data.start_date) {
                    headerHtml += `<div class="row mb-4 small">
                        <div class="col-md-6">
                            <h6 class="text-dark mb-1"><i class="bi bi-check-circle me-2"></i>Estat</h6>
                            <p class="ps-3 mb-0">${getStatusBadge(data.status)}</p>
                        </div>
                        <div class="col-md-6">
                            <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(data.start_date).toLocaleDateString('ca-ES')} - ${data.end_date ? new Date(data.end_date).toLocaleDateString('ca-ES') : 'N/A'}</p>
                        </div>
                    </div>`;
                }
                headerHtml += '<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">${data.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">${data.diagnostico || 'No especificat'}</p>
                        </div>
                    </div>
                    <hr>`;

                let exercisesHtml = '';
                if (data.exercises && data.exercises.length > 0) {
                    exercisesHtml += `<h5 class="mb-3"><i class="bi bi-list-ol me-2"></i>Pauta d'Exercicis (${data.exercises.length})</h5><div class="list-group list-group-flush">`;
                    data.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">` : `<video src="videos/${ex.video_filename}#t=0.5" class="view-ex-thumb"></video>`;
                        } else if (ex.image_filename) {
                             thumbnailHtml = `<img src="${getImagePath(ex.image_filename)}" class="view-ex-thumb">`;
                        } 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">${thumbnailHtml}</div><div class="flex-grow-1"><h6 class="mb-1">${ex.title}</h6><p class="mb-1 small"><strong>Pauta:</strong> ${ex.frecuencia} | ${ex.series} series | ${ex.repetitions} reps | ${ex.rest_time} descans</p>${ex.pauta_notes ? `<p class="mb-0 small text-muted fst-italic"><strong>Notes:</strong> ${ex.pauta_notes}</p>` : ''}</div></div></div>`;
                    });
                    exercisesHtml += `</div>`;
                }
                contentHtml = headerHtml + evaluationHtml + exercisesHtml;
            }

            $('#viewItemModalBody').html(contentHtml);
        })
        .fail(xhr => $('#viewItemModalBody').html(`<div class="alert alert-danger">${xhr.responseJSON?.message || 'Error desconegut'}</div>`));
    });

    // --- MODIFICACIÓ: Guardem les dades del pacient en clicar ---
    $(document).on('click', '.unarchive-personal-btn', function() {
        personalItemToManage = {
            id: $(this).data('id'),
            type: $(this).data('type'),
            name: $(this).data('name'),
            pacienteId: $(this).data('paciente-id'), // NOU
            pacienteName: $(this).data('paciente-name') // NOU
        };
        $('#personalItemNameToUnarchive').text(`"${personalItemToManage.name}"`);
        unarchivePersonalConfirmModal.show();
    });

    // --- NOVA FUNCIÓ per actualitzar el botó TORNAR ---
    function updateTreatmentsBackButton() {
        if (lastUnarchivedPatient.id) {
            $('#treatments-back-btn').hide();
            $('#back-btn-patient-name').text(lastUnarchivedPatient.name);
            $('#treatments-patient-back-btn')
                .attr('href', `fitxa_pacient.php?id=${lastUnarchivedPatient.id}&tab=history`)
                .show();
        } else {
            $('#treatments-back-btn').show();
            $('#treatments-patient-back-btn').hide();
        }
    }

    // --- MODIFICACIÓ: Lògica de redirecció eliminada. Ara actualitza el botó. ---
    $('#confirmUnarchivePersonalBtn').on('click', function() {
        if (!personalItemToManage.id) return;

        const { id, type } = personalItemToManage;
        $.post('archive.php', { ajax: true, action: 'unarchive_personal_item', id, type }, 'json')
            .done(res => {
                if (res.status === 'success') {
                    showToast(res.message, 'success');

                    // Comprovar si era un tractament per actualitzar el botó TORNAR
                    if (personalItemToManage.type === 'treatment' && personalItemToManage.pacienteId) {
                        lastUnarchivedPatient.id = personalItemToManage.pacienteId;
                        lastUnarchivedPatient.name = personalItemToManage.pacienteName;
                        updateTreatmentsBackButton();
                    }

                    // Refrescar la llista de la pestanya actual
                    const currentTabId = $('#archiveTabs .nav-link.active').attr('id');
                    handleTabLoad(currentTabId);

                } else {
                     showToast(res.message, 'danger');
                }
            }).fail(xhr => {
                showToast(xhr.responseJSON.message, 'danger');
            }).always(() => {
                unarchivePersonalConfirmModal.hide();
            });
    });

    // --- NUEVOS HANDLERS PARA ELIMINAR ---
    $(document).on('click', '.delete-personal-btn', function() {
        personalItemToManage = {
            id: $(this).data('id'),
            type: $(this).data('type'),
            name: $(this).data('name'),
            creatorId: $(this).data('creator-id')
            // No necessitem les dades del pacient per eliminar
        };
        $('#personalItemNameToDelete').text(`"${personalItemToManage.name}"`);
        deletePersonalConfirmModal.show();
    });

    $('#confirmDeletePersonalBtn').on('click', function() {
        if (!personalItemToManage.id) return;

        const { id, type, name } = personalItemToManage;
        const confirmation = prompt(`Per a confirmar l'eliminació permanent de "${name}", escriu ELIMINAR ací baix:`);

        if (confirmation === 'ELIMINAR') {
            $.post('archive.php', {
                ajax: true,
                action: 'delete_personal_item_permanently',
                id: id,
                type: type
            }, 'json')
            .done(res => {
                if (res.status === 'success') {
                    showToast(res.message, 'success');
                    const currentTabId = $('#archiveTabs .nav-link.active').attr('id');
                    handleTabLoad(currentTabId);
                } else {
                    showToast(res.message, 'danger');
                }
            }).fail(xhr => {
                showToast(xhr.responseJSON?.message || 'Error de connexió', 'danger');
            }).always(() => {
                deletePersonalConfirmModal.hide();
            });
        } else {
            showToast("Acció cancel·lada.", "info");
        }
    });


    // --- Carga Inicial y Eventos de Pestañas ---
    const handleTabLoad = (tabId) => {
        if (!tabId) return;
        // --- ELIMINADO: La comprobación de 'pacients-tab' ---
        if (tabId === 'media-tab') fetchPersonalArchive('media');
        if (tabId === 'exercises-tab') fetchPersonalArchive('ejercicio');
        if (tabId === 'protocols-tab') fetchPersonalArchive('protocol');
        if (tabId === 'treatments-tab') {
            fetchPersonalArchive('treatment');
            // Actualitzem l'estat del botó TORNAR
            updateTreatmentsBackButton();
        }
    };

    $('button[data-bs-toggle="tab"]').on('shown.bs.tab', function(e) {
        const targetId = $(e.target).attr('id');

        // --- MODIFICACIÓ: Resetejar el botó si sortim de la pestanya de tractaments ---
        if (targetId !== 'treatments-tab') {
            lastUnarchivedPatient = { id: null, name: '' };
            // No cal cridar a updateTreatmentsBackButton() aquí,
            // es cridarà quan es carregui la pestanya de tractaments
        }

        handleTabLoad(targetId);
        if(history.pushState) { history.pushState(null, null, '#' + targetId); }
    });

    const urlHash = window.location.hash;
    if (urlHash) {
        const tabToActivate = document.querySelector(`.nav-tabs button[id="${urlHash.substring(1)}"]`);
        if (tabToActivate) {
            new bootstrap.Tab(tabToActivate).show();
        }
    } else {
        const activeTabId = $('#archiveTabs .nav-link.active').attr('id');
        handleTabLoad(activeTabId);
    }
});
</script>

</body>
</html>
