<?php
// /partials/fisio_summary.php
// VERSIÓN RESPONSIVE MEJORADA

// Este archivo se incluye dentro de reports_ajax.php, por lo que ya tiene acceso a $db, $user_id, y $user_rol.

// Asegurarse de que el script solo se ejecute si se ha accedido desde reports_ajax.php
if (!isset($db) || !isset($user_id)) {
    die("Acceso directo denegado.");
}

// --- Determinación del ID a consultar (Lógica original mantenida) ---
$fisio_id_a_consultar = $user_id;
if (isset($_REQUEST['target_id']) && !empty($_REQUEST['target_id']) && $user_rol === 'superadmin') {
    $fisio_id_a_consultar = (int)$_REQUEST['target_id'];
}
$fisio_id = $fisio_id_a_consultar;

// Nombre del fisio
$stmt_name = $db->prepare("SELECT nombre, apellido FROM cuentas WHERE id = ?");
$stmt_name->execute([$fisio_id]);
$fisio_info = $stmt_name->fetch();
$fisio_name_a_mostrar = $fisio_info ? htmlspecialchars($fisio_info['nombre'] . ' ' . $fisio_info['apellido']) : 'Usuari Desconegut';

// --- Definición de "Mis pacientes" ---
$my_patients_join_condition = "
    LEFT JOIN tratamiento_fisios_asignados tfa ON t.id = tfa.tratamiento_id
    WHERE (t.creator_fisio_id = :fid OR tfa.fisio_id = :fid)
    AND t.is_protocol = 0
";
$params_fid = [':fid' => $fisio_id];

// --- 1. CONSULTAS DE CONTEO Y RECURSOS ---
$counts_stmt = $db->prepare("
    SELECT
        (SELECT COUNT(id) FROM cuentas WHERE id_fisio_registrador = :fid AND rol = 'paciente') as patients_registered,
        (SELECT COUNT(id) FROM videos WHERE id_uploader = :fid) as videos_uploaded,
        (SELECT COUNT(id) FROM images WHERE id_uploader = :fid) as images_uploaded,
        (SELECT COUNT(id) FROM ejercicios WHERE id_creator = :fid) as exercises_created_count,
        (SELECT COUNT(id) FROM tratamientos WHERE creator_fisio_id = :fid AND is_protocol = 1) as protocols_created_count
");
$counts_stmt->execute([':fid' => $fisio_id]);
$counts = $counts_stmt->fetch(PDO::FETCH_ASSOC);

// Listas de recursos
$exercises_created_list_stmt = $db->prepare("SELECT id, title FROM ejercicios WHERE id_creator = :fid ORDER BY title");
$exercises_created_list_stmt->execute([':fid' => $fisio_id]);
$exercises_created_list = $exercises_created_list_stmt->fetchAll(PDO::FETCH_ASSOC);

$protocols_created_list_stmt = $db->prepare("SELECT id, title FROM tratamientos WHERE creator_fisio_id = :fid AND is_protocol = 1 ORDER BY title");
$protocols_created_list_stmt->execute([':fid' => $fisio_id]);
$protocols_created_list = $protocols_created_list_stmt->fetchAll(PDO::FETCH_ASSOC);

$videos_uploaded_list_stmt = $db->prepare("SELECT id, title FROM videos WHERE id_uploader = :fid ORDER BY title");
$videos_uploaded_list_stmt->execute([':fid' => $fisio_id]);
$videos_uploaded_list = $videos_uploaded_list_stmt->fetchAll(PDO::FETCH_ASSOC);

$images_uploaded_list_stmt = $db->prepare("SELECT id, title FROM images WHERE id_uploader = :fid ORDER BY title");
$images_uploaded_list_stmt->execute([':fid' => $fisio_id]);
$images_uploaded_list = $images_uploaded_list_stmt->fetchAll(PDO::FETCH_ASSOC);


// --- 2. CONSULTAS DE TRATAMIENTOS ---
$treatments_authored_stmt = $db->prepare("
    SELECT t.id, t.title, t.status, t.start_date, t.end_date, c.nombre, c.apellido, c.id as patient_id
    FROM tratamientos t
    JOIN cuentas c ON t.paciente_id = c.id
    WHERE t.creator_fisio_id = :fid AND t.is_protocol = 0
    ORDER BY c.apellido, t.status, t.title
");
$treatments_authored_stmt->execute([':fid' => $fisio_id]);
$treatments_authored = $treatments_authored_stmt->fetchAll(PDO::FETCH_ASSOC);

$treatments_collaborated_stmt = $db->prepare("
    SELECT DISTINCT t.id, t.title, t.status, t.start_date, t.end_date, c.nombre, c.apellido, c.id as patient_id
    FROM tratamientos t
    JOIN tratamiento_fisios_asignados tfa ON t.id = tfa.tratamiento_id
    JOIN cuentas c ON t.paciente_id = c.id
    WHERE tfa.fisio_id = :fid AND t.is_protocol = 0 AND t.creator_fisio_id != :fid
    ORDER BY c.apellido, t.status, t.title
");
$treatments_collaborated_stmt->execute([':fid' => $fisio_id]);
$treatments_collaborated = $treatments_collaborated_stmt->fetchAll(PDO::FETCH_ASSOC);


// --- 3. CONSOLIDACIÓN ---
$all_responsible_treatments_raw = array_merge($treatments_authored, $treatments_collaborated);
$all_responsible_treatments = [];
foreach ($all_responsible_treatments_raw as $t) {
    $all_responsible_treatments[$t['id']] = $t;
}
$all_responsible_treatments = array_values($all_responsible_treatments);


// --- 4. FILTROS ---
$active_treatments = array_filter($all_responsible_treatments, fn($t) => $t['status'] === 'En curs');
$programmed_treatments = array_filter($all_responsible_treatments, fn($t) => $t['status'] === 'Programat');
$completed_treatments = array_filter($all_responsible_treatments, fn($t) => $t['status'] === 'Completat');
$omitted_treatments = array_filter($all_responsible_treatments, fn($t) => $t['status'] === 'Omés');

$ending_soon_treatments = array_filter($active_treatments, function($t) {
    if (empty($t['end_date'])) return false;
    try {
        $end_date = new DateTime($t['end_date']);
        $now = new DateTime();
        $interval = $now->diff($end_date);
        return !$interval->invert && $interval->days <= 3;
    } catch (Exception $e) { return false; }
});

$patients_treated_ids = [];
foreach ($active_treatments as $treatment) { $patients_treated_ids[$treatment['patient_id']] = true; }
$patients_treated_count = count($patients_treated_ids);


// --- 5. CONSULTAS ESPECÍFICAS ---
$stmt_activity = $db->prepare("
    SELECT tevol.fecha_realizacion, tevol.comentarios, c.nombre, c.apellido, c.id as patient_id, e.title as exercise_title, e.id as exercise_id, t.id as treatment_id
    FROM tratamiento_evolucion tevol
    JOIN tratamiento_ejercicios te ON tevol.tratamiento_ejercicio_id = te.id
    JOIN tratamientos t ON te.tratamiento_id = t.id
    JOIN cuentas c ON t.paciente_id = c.id
    JOIN ejercicios e ON te.ejercicio_id = e.id
    $my_patients_join_condition AND t.status IN ('En curs', 'Programat')
    ORDER BY tevol.fecha_realizacion DESC, COALESCE(tevol.hora_realizacion, '00:00:00') DESC
    LIMIT 10
");
$stmt_activity->execute($params_fid);
$detailed_recent_activity = $stmt_activity->fetchAll(PDO::FETCH_ASSOC);

$stmt_alerts_7d = $db->prepare("
    SELECT tevol.dolor_percibido, tevol.esfuerzo_percibido, tevol.fecha_realizacion, COALESCE(tevol.hora_realizacion, '00:00:00') as hora_realizacion,
           c.nombre, c.apellido, c.id as patient_id, e.title as exercise_title, e.id as exercise_id, t.id as treatment_id
    FROM tratamiento_evolucion tevol
    JOIN tratamiento_ejercicios te ON tevol.tratamiento_ejercicio_id = te.id
    JOIN tratamientos t ON te.tratamiento_id = t.id
    JOIN cuentas c ON t.paciente_id = c.id
    JOIN ejercicios e ON te.ejercicio_id = e.id
    $my_patients_join_condition AND t.status = 'En curs'
    AND (tevol.dolor_percibido >= 4 OR tevol.esfuerzo_percibido >= 4)
    AND tevol.fecha_realizacion >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)
    ORDER BY tevol.fecha_realizacion DESC, hora_realizacion DESC
    LIMIT 20
");
$stmt_alerts_7d->execute($params_fid);
$detailed_alerts_7d = $stmt_alerts_7d->fetchAll(PDO::FETCH_ASSOC);


// --- HELPER: Format Relative Time ---
if (!function_exists('formatRelativeTimeWidget')) {
    function formatRelativeTimeWidget($dateTimeString) {
        if (empty($dateTimeString)) return 'data desconeguda';
        try {
            $date = new DateTime($dateTimeString);
            $now = new DateTime();
            $interval = $now->diff($date);
            if ($interval->days > 1) return "fa " . $interval->days . " dies";
            if ($interval->days == 1) return ($now->format('H') < $date->format('H')) ? "hui" : "ahir";
            if ($interval->h > 1) return "fa " . $interval->h . " hores";
            if ($interval->h == 1) return "fa 1 hora";
            if ($interval->i > 1) return "fa " . $interval->i . " min";
            return "fa menys d'1 min";
        } catch (Exception $e) { return 'data invàlida'; }
    }
}
?>

<style>
    /* --- ESTILOS BASE --- */
    .summary-section h5 {
        color: #343a40;
        font-weight: bold;
        margin-top: 15px;
        border-bottom: 2px solid #eee;
        padding-bottom: 5px;
        font-size: 1.15rem;
    }

    .summary-stat-box { background-color: #f8f9fa; border-radius: .5rem; padding: 15px; margin-bottom: 15px; }
    .stat-number { font-size: 2.2rem; font-weight: bold; color: var(--custom-primary-teal); line-height: 1.2; }
    
    .list-scrollable { max-height: 250px; overflow-y: auto; }
    
    /* Badges de estado */
    .badge-status-green { color: #155724; }
    .badge-status-blue { color: #004085; }
    .badge-status-gray { background-color: #e2e3e5; color: #383d41; }
    .badge-status-red { color: #721c24; }

    .list-group-item strong { font-weight: 600; }
    .tab-content span, .list-scrollable span { font-weight: 500; }

    .activity-entry { font-size: 0.9rem; border-bottom: 1px solid #eee; padding: 8px 0; }
    .alert-level-low { background-color: #fff3cd; }
    .alert-level-high { background-color: #f8d7da; }
    .activity-text-secondary { font-size: 0.8rem; color: #6c757d; }

    .activity-list-container, .alerts-list-container { border: 1px solid #dee2e6; border-radius: .25rem; min-height: 100px; }
    .alerts-list-container { background-color: #fcfcfc; }

    /* Estilos de pestañas (Nav Tabs) */
    #treatmentTabs .nav-link {
        cursor: pointer; font-weight: 500; color: #495057;
        border-radius: .375rem .375rem 0 0;
        border-color: transparent transparent #dee2e6 transparent;
    }
    #treatmentTabs .nav-link.active {
        background-color: var(--custom-primary-teal) !important;
        color: white !important;
        border-color: var(--custom-primary-teal-dark) var(--custom-primary-teal-dark) white !important;
    }
    
    /* Estilos de pestañas verticales (Pills) */
    #v-pills-tab .nav-link.active { background-color: #E6F3FF !important; color: #333 !important; }
    #v-pills-tab .nav-link { color: #495057; border-radius: .25rem; margin-bottom: 2px; }
    #v-pills-tab .nav-link i { width: 1.2em; color: inherit !important; }

    #treatmentTabs + .tab-content { max-height: 400px; overflow-y: auto; border: 1px solid #dee2e6; border-top: none; padding: 1rem; }
    #v-pills-tabContent { max-height: 350px; overflow-y: auto; padding: 1rem; }

    /* Filtros interactivos */
    #active-summary-panel .filter-trigger { cursor: pointer; transition: background-color 0.2s, transform 0.2s; color: #000; font-weight: 500; font-size: 0.95rem; background-color: transparent; border: none; padding-top: 0.75rem; padding-bottom: 0.75rem; }
    #active-summary-panel .filter-trigger:hover { background-color: #E6F3FF; color: #000 !important; }
    #active-summary-panel .filter-trigger.active { color: #000; background-color: #E6F3FF; }
    #active-summary-panel .filter-trigger .badge { font-size: 0.7em; }
    
    /* --- RESPONSIVE TWEAKS --- */
    @media (max-width: 767.98px) {
        /* Ajustar tamaño de fuente en móvil */
        .stat-number { font-size: 1.8rem; }
        .summary-stat-box small { font-size: 0.75rem; display: block; line-height: 1.2; }
        
        /* En móvil, las pestañas "verticales" (Contenido) pasan a ser horizontales/bloque */
        #v-pills-tab { flex-direction: row !important; overflow-x: auto; white-space: nowrap; border-right: none !important; border-bottom: 1px solid #dee2e6; margin-right: 0 !important; margin-bottom: 1rem; }
        #v-pills-tab .nav-link { width: auto; margin-right: 5px; margin-bottom: 0; }
        
        /* Reajustar layout de la sección "Contingut" */
        .card .row.g-0 > .col-5 { width: 100%; border-right: none !important; }
        .card .row.g-0 > .col-7 { width: 100%; }
        
        /* Ajustar filtros de tratamientos */
        #active-summary-panel .col-md-5, #active-summary-panel .col-md-7 { width: 100%; }
        #active-summary-panel .col-md-5 { margin-bottom: 1rem; }
    }
</style>

<div class="row">
    <div class="col-md-12 text-center">
        <h4 class="text-secondary mb-3">Resum de la Càrrega de Treball de: <strong style="color: SteelBlue;"><?php echo $fisio_name_a_mostrar; ?></strong></h4>
        <?php if ($fisio_id == $user_id): ?>
            <p class="small text-muted">Aquesta informació mostra la teva activitat com a creador/gestor de contingut i tractaments.</p>
        <?php endif; ?>
    </div>
</div>

<div class="summary-stat-box row g-3">
    <div class="col-6 col-md-3 text-center">
        <div class="stat-number"><?= $counts['patients_registered'] ?></div>
        <small class="text-muted">Pacients Registrats</small>
    </div>

    <div class="col-6 col-md-3 text-center">
        <div class="stat-number"><?= $patients_treated_count ?></div>
        <small class="text-muted">Pacients Tractats</small>
    </div>

    <div class="col-6 col-md-3 text-center">
        <div class="stat-number"><?= $counts['exercises_created_count'] + $counts['protocols_created_count'] ?></div>
        <small class="text-muted">Contingut Creat</small>
    </div>
    <div class="col-6 col-md-3 text-center">
        <div class="stat-number"><?= count($active_treatments) ?></div>
        <small class="text-muted">Tractaments Actius</small>
    </div>
</div>

<div class="row summary-section mt-4">
    <div class="col-md-12">
        <h5><i class="bi bi-person-workspace me-2"></i> Gestió de Tractaments i Activitat</h5>
    </div>

    <div class="col-md-12">
        <ul class="nav nav-tabs" id="treatmentTabs" role="tablist">
            <li class="nav-item" role="presentation"><button class="nav-link active" id="active-summary-tab" data-bs-toggle="tab" data-bs-target="#active-summary-panel" type="button">Resum</button></li>
            <li class="nav-item" role="presentation"><button class="nav-link" id="activity-alerts-tab" data-bs-toggle="tab" data-bs-target="#activity-alerts-panel" type="button">Activitat</button></li>
            <li class="nav-item" role="presentation"><button class="nav-link" id="auth-col-tab" data-bs-toggle="tab" data-bs-target="#auth-col-panel" type="button">Autoria</button></li>
            <li class="nav-item" role="presentation"><button class="nav-link" id="history-tab" data-bs-toggle="tab" data-bs-target="#history-panel" type="button">Històric</button></li>
        </ul>

        <div class="tab-content">

            <div class="tab-pane fade show active" id="active-summary-panel" role="tabpanel">
                <div class="row g-3">
                    <div class="col-md-5"> <h6>Filtrar Tractaments:</h6>
                        <ul class="list-group list-group-flush small">
                             <li class="list-group-item d-flex justify-content-between align-items-center filter-trigger active" data-filter="active">
                                En Curs <span class="badge bg-primary rounded-pill"><?= count($active_treatments) ?></span>
                            </li>
                            <li class="list-group-item d-flex justify-content-between align-items-center filter-trigger" data-filter="programmed">
                                Programats <span class="badge bg-info rounded-pill"><?= count($programmed_treatments) ?></span>
                            </li>
                            <li class="list-group-item d-flex justify-content-between align-items-center filter-trigger" data-filter="ending_soon">
                                Finalitzen (3d) <span class="badge bg-warning text-dark rounded-pill"><?= count($ending_soon_treatments) ?></span>
                            </li>
                             </ul>
                         </div>

                    <div class="col-md-7"> <h6>Llista (<span id="treatment-list-title">En Curs</span>):</h6>
                        <div id="treatment-list-display" class="list-scrollable border rounded p-2" style="min-height: 150px;">
                            </div>
                        </div>
                </div>
            </div>

            <div class="tab-pane fade" id="activity-alerts-panel" role="tabpanel">
                <div class="row g-3">
                    <div class="col-md-6">
                        <h6><i class="bi bi-person-walking me-2"></i> Activitat Recent:</h6>
                        <div class="list-scrollable activity-list-container">
                            <?php if (empty($detailed_recent_activity)): ?>
                                <p class="text-muted small p-2">Sense activitat recent.</p>
                            <?php else: ?>
                                <ul class="list-group list-group-flush small">
                                    <?php foreach ($detailed_recent_activity as $act): ?>
                                        <li class="list-group-item">
                                            <div class="d-flex justify-content-between">
                                                <span class="text-truncate me-2"><?= htmlspecialchars($act['apellido'] . ', ' . $act['nombre']) ?></span>
                                                <small class="text-muted flex-shrink-0"><?= formatRelativeTimeWidget($act['fecha_realizacion']) ?></small>
                                            </div>
                                            <div class="activity-text-secondary text-truncate" title="<?= htmlspecialchars($act['exercise_title']) ?>">
                                                <span><?= htmlspecialchars($act['exercise_title']) ?></span>
                                                <?php if (!empty($act['comentarios'])): ?>
                                                    <span class="fst-italic text-primary ms-2">"<?= htmlspecialchars($act['comentarios']) ?>"</span>
                                                <?php endif; ?>
                                            </div>
                                        </li>
                                    <?php endforeach; ?>
                                </ul>
                            <?php endif; ?>
                        </div>
                    </div>

                    <div class="col-md-6">
                        <h6><i class="bi bi-exclamation-triangle me-2"></i> Alertes (7d):</h6>
                        <div class="list-scrollable alerts-list-container">
                            <?php if (empty($detailed_alerts_7d)): ?>
                                <p class="text-success small p-2">Sense alertes.</p>
                            <?php else: ?>
                                <ul class="list-group list-group-flush small">
                                    <?php foreach ($detailed_alerts_7d as $alert): ?>
                                        <?php $alert_class = (($alert['dolor_percibido'] ?? 0) >= 7 || ($alert['esfuerzo_percibido'] ?? 0) >= 7) ? 'alert-level-high' : 'alert-level-low'; ?>
                                        <li class="list-group-item <?= $alert_class ?>">
                                            <div class="d-flex justify-content-between">
                                                <span class="text-truncate me-2"><?= htmlspecialchars($alert['apellido'] . ', ' . $alert['nombre']) ?></span>
                                                 <small class="text-muted flex-shrink-0"><?= formatRelativeTimeWidget($alert['fecha_realizacion'] . ' ' . $alert['hora_realizacion']) ?></small>
                                            </div>
                                            <div class="d-flex justify-content-between activity-text-secondary">
                                                <span class="text-truncate me-2" title="<?= htmlspecialchars($alert['exercise_title']) ?>"><?= htmlspecialchars($alert['exercise_title']) ?></span>
                                                <div class="flex-shrink-0">
                                                    <?php if (($alert['dolor_percibido'] ?? 0) >= 4): ?>
                                                        <span class="badge bg-danger">D:<?= $alert['dolor_percibido'] ?></span>
                                                    <?php endif; ?>
                                                    <?php if (($alert['esfuerzo_percibido'] ?? 0) >= 4): ?>
                                                        <span class="badge bg-warning text-dark">E:<?= $alert['esfuerzo_percibido'] ?></span>
                                                    <?php endif; ?>
                                                </div>
                                            </div>
                                        </li>
                                    <?php endforeach; ?>
                                </ul>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>

            <div class="tab-pane fade" id="auth-col-panel" role="tabpanel">
                <div class="row g-3">
                    <div class="col-md-6">
                        <h6>Creats per mi (<?= count($treatments_authored) ?>):</h6>
                        <ul class="list-group list-group-flush small list-scrollable">
                            <?php if (empty($treatments_authored)): ?>
                                <li class="list-group-item text-muted">Cap tractament creat.</li>
                            <?php else:
                                foreach ($treatments_authored as $t): ?>
                                    <li class="list-group-item d-flex justify-content-between align-items-center">
                                        <span class="text-truncate me-1" title="<?= htmlspecialchars($t['title']) ?> (<?= htmlspecialchars($t['apellido'] . ', ' . $t['nombre']) ?>)">
                                            <strong><?= htmlspecialchars($t['title']) ?></strong> <small>(<?= htmlspecialchars($t['apellido'] . ', ' . $t['nombre']) ?>)</small>
                                        </span>
                                        <span class="badge bg-secondary flex-shrink-0"><?= $t['status'] ?></span>
                                    </li>
                                <?php endforeach;
                            endif; ?>
                        </ul>
                    </div>

                    <div class="col-md-6">
                        <h6>Col·laborador (<?= count($treatments_collaborated) ?>):</h6>
                        <ul class="list-group list-group-flush small list-scrollable">
                            <?php if (empty($treatments_collaborated)): ?>
                                <li class="list-group-item text-muted">Cap tractament com a col·laborador.</li>
                            <?php else:
                                foreach ($treatments_collaborated as $t): ?>
                                     <li class="list-group-item d-flex justify-content-between align-items-center">
                                        <span class="text-truncate me-1" title="<?= htmlspecialchars($t['title']) ?> (<?= htmlspecialchars($t['apellido'] . ', ' . $t['nombre']) ?>)">
                                            <strong><?= htmlspecialchars($t['title']) ?></strong> <small>(<?= htmlspecialchars($t['apellido'] . ', ' . $t['nombre']) ?>)</small>
                                        </span>
                                        <span class="badge bg-secondary flex-shrink-0"><?= $t['status'] ?></span>
                                    </li>
                                <?php endforeach;
                            endif; ?>
                        </ul>
                    </div>
                </div>
            </div>

            <div class="tab-pane fade" id="history-panel" role="tabpanel">
                <div class="row g-3">
                    <div class="col-md-6">
                        <h6>Completats (<?= count($completed_treatments) ?>):</h6>
                        <ul class="list-group list-group-flush small list-scrollable">
                            <?php if (empty($completed_treatments)): ?>
                                <li class="list-group-item text-muted">Cap tractament completat.</li>
                            <?php else:
                                foreach ($completed_treatments as $t): ?>
                                    <li class="list-group-item d-flex justify-content-between align-items-center">
                                        <span class="text-truncate me-1" title="<?= htmlspecialchars($t['title']) ?> (<?= htmlspecialchars($t['apellido'] . ', ' . $t['nombre']) ?>)">
                                            <?= htmlspecialchars($t['title']) ?> <small>(<?= htmlspecialchars($t['apellido'] . ', ' . $t['nombre']) ?>)</small>
                                        </span>
                                    </li>
                                <?php endforeach;
                            endif; ?>
                        </ul>
                    </div>
                    <div class="col-md-6">
                        <h6>Omessos (<?= count($omitted_treatments) ?>):</h6>
                        <ul class="list-group list-group-flush small list-scrollable">
                             <?php if (empty($omitted_treatments)): ?>
                                <li class="list-group-item text-muted">Cap tractament omès.</li>
                            <?php else:
                                foreach ($omitted_treatments as $t): ?>
                                    <li class="list-group-item d-flex justify-content-between align-items-center">
                                        <span class="text-truncate me-1" title="<?= htmlspecialchars($t['title']) ?> (<?= htmlspecialchars($t['apellido'] . ', ' . $t['nombre']) ?>)">
                                            <?= htmlspecialchars($t['title']) ?> <small>(<?= htmlspecialchars($t['apellido'] . ', ' . $t['nombre']) ?>)</small>
                                        </span>
                                    </li>
                                <?php endforeach;
                            endif; ?>
                        </ul>
                    </div>
                </div>
            </div>

        </div> </div> </div> <div class="row summary-section mt-4">
    <div class="col-md-12">
        <h5><i class="bi bi-folder-fill me-2"></i>Contingut (Propi i en Col·laboració)</h5>
    </div>

    <div class="col-md-12">
        <div class="card border">
            <div class="card-body p-0">
                <div class="row g-0">
                    <div class="col-5 border-end">
                    <div class="nav flex-column nav-pills me-3 p-2" id="v-pills-tab" role="tablist" aria-orientation="vertical">
                            <button class="nav-link text-start active" id="v-pills-ex-tab" data-bs-toggle="pill" data-bs-target="#v-pills-ex" type="button" role="tab">
                                <i class="bi bi-person-arms-up me-2"></i> Exercicis (<?= $counts['exercises_created_count'] ?>)
                            </button>
                            <button class="nav-link text-start" id="v-pills-prot-tab" data-bs-toggle="pill" data-bs-target="#v-pills-prot" type="button" role="tab">
                                <i class="bi bi-clipboard2-pulse me-2"></i> Protocols (<?= $counts['protocols_created_count'] ?>)
                            </button>
                            <button class="nav-link text-start" id="v-pills-treat-auth-tab" data-bs-toggle="pill" data-bs-target="#v-pills-treat-auth" type="button" role="tab">
                                <i class="bi bi-clipboard-check me-2"></i> Tract. Creats (<?= count($treatments_authored) ?>)
                            </button>
                             <button class="nav-link text-start" id="v-pills-treat-collab-tab" data-bs-toggle="pill" data-bs-target="#v-pills-treat-collab" type="button" role="tab">
                                <i class="bi bi-people me-2"></i> Tract. Col·lab. (<?= count($treatments_collaborated) ?>)
                            </button>
                            <button class="nav-link text-start" id="v-pills-vid-tab" data-bs-toggle="pill" data-bs-target="#v-pills-vid" type="button" role="tab">
                                <i class="bi bi-film me-2"></i> Vídeos (<?= $counts['videos_uploaded'] ?>)
                            </button>
                            <button class="nav-link text-start" id="v-pills-img-tab" data-bs-toggle="pill" data-bs-target="#v-pills-img" type="button" role="tab">
                                <i class="bi bi-image me-2"></i> Imatges (<?= $counts['images_uploaded'] ?>)
                            </button>
                        </div>
                    </div>

                    <div class="col-7">
                        <div class="tab-content" id="v-pills-tabContent">

                            <div class="tab-pane fade show active" id="v-pills-ex" role="tabpanel">
                                <ul class="list-group list-group-flush small">
                                    <?php if (empty($exercises_created_list)): ?>
                                        <li class="list-group-item text-muted">Cap exercici propi.</li>
                                    <?php else:
                                        foreach ($exercises_created_list as $e): ?>
                                            <li class="list-group-item text-truncate" title="<?= htmlspecialchars($e['title']) ?>">
                                                <span><?= htmlspecialchars($e['title']) ?></span>
                                            </li>
                                        <?php endforeach;
                                    endif; ?>
                                </ul>
                            </div>

                            <div class="tab-pane fade" id="v-pills-prot" role="tabpanel">
                                <ul class="list-group list-group-flush small">
                                    <?php if (empty($protocols_created_list)): ?>
                                        <li class="list-group-item text-muted">Cap protocol propi.</li>
                                    <?php else:
                                        foreach ($protocols_created_list as $p): ?>
                                            <li class="list-group-item text-truncate" title="<?= htmlspecialchars($p['title']) ?>">
                                                <span><?= htmlspecialchars($p['title']) ?></span>
                                            </li>
                                        <?php endforeach;
                                    endif; ?>
                                </ul>
                            </div>

                            <div class="tab-pane fade" id="v-pills-treat-auth" role="tabpanel">
                                <ul class="list-group list-group-flush small">
                                    <?php if (empty($treatments_authored)): ?>
                                        <li class="list-group-item text-muted">Cap tractament propi.</li>
                                    <?php else:
                                        foreach ($treatments_authored as $t): ?>
                                            <li class="list-group-item text-truncate" title="<?= htmlspecialchars($t['title']) ?> (<?= htmlspecialchars($t['apellido'] . ', ' . $t['nombre']) ?>)">
                                                <span><?= htmlspecialchars($t['title']) ?></span>
                                                <small>(<?= htmlspecialchars($t['apellido'] . ', ' . $t['nombre']) ?>)</small>
                                                <span class="badge bg-secondary ms-2"><?= $t['status'] ?></span>
                                            </li>
                                        <?php endforeach;
                                    endif; ?>
                                </ul>
                            </div>

                             <div class="tab-pane fade" id="v-pills-treat-collab" role="tabpanel">
                                <ul class="list-group list-group-flush small">
                                    <?php if (empty($treatments_collaborated)): ?>
                                        <li class="list-group-item text-muted">Cap tractament com a col·laborador.</li>
                                    <?php else:
                                        foreach ($treatments_collaborated as $t): ?>
                                            <li class="list-group-item text-truncate" title="<?= htmlspecialchars($t['title']) ?> (<?= htmlspecialchars($t['apellido'] . ', ' . $t['nombre']) ?>)">
                                                <span><?= htmlspecialchars($t['title']) ?></span>
                                                <small>(<?= htmlspecialchars($t['apellido'] . ', ' . $t['nombre']) ?>)</small>
                                                <span class="badge bg-secondary ms-2"><?= $t['status'] ?></span>
                                            </li>
                                        <?php endforeach;
                                    endif; ?>
                                </ul>
                            </div>
                            <div class="tab-pane fade" id="v-pills-vid" role="tabpanel">
                                <ul class="list-group list-group-flush small">
                                    <?php if (empty($videos_uploaded_list)): ?>
                                        <li class="list-group-item text-muted">Cap vídeo propi.</li>
                                    <?php else:
                                        foreach ($videos_uploaded_list as $v): ?>
                                            <li class="list-group-item text-truncate" title="<?= htmlspecialchars($v['title']) ?>">
                                                <span><?= htmlspecialchars($v['title']) ?></span>
                                            </li>
                                        <?php endforeach;
                                    endif; ?>
                                </ul>
                            </div>

                            <div class="tab-pane fade" id="v-pills-img" role="tabpanel">
                                <ul class="list-group list-group-flush small">
                                    <?php if (empty($images_uploaded_list)): ?>
                                        <li class="list-group-item text-muted">Cap imatge pròpia.</li>
                                    <?php else:
                                        foreach ($images_uploaded_list as $i): ?>
                                            <li class="list-group-item text-truncate" title="<?= htmlspecialchars($i['title']) ?>">
                                                <span><?= htmlspecialchars($i['title']) ?></span>
                                            </li>
                                        <?php endforeach;
                                    endif; ?>
                                </ul>
                            </div>

                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
$(document).ready(function() {
    // Solo ejecutar si estamos dentro del modal (para evitar conflictos)
    if ($('#active-summary-panel').length) {

        // 1. Obtener los datos de los tratamientos desde PHP
        const treatmentData = {
            active: <?= json_encode(array_values($active_treatments), JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT); ?>,
            programmed: <?= json_encode(array_values($programmed_treatments), JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT); ?>,
            ending_soon: <?= json_encode(array_values($ending_soon_treatments), JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT); ?>
        };

        const listDisplay = $('#treatment-list-display');
        const listTitle = $('#treatment-list-title');
        const filterTriggers = $('#active-summary-panel .filter-trigger');

        // 2. Función para renderizar la lista de tratamientos
        function renderTreatmentList(treatments, title) {
            listTitle.text(title);
            listDisplay.empty();

            if (!treatments || treatments.length === 0) {
                listDisplay.html('<p class="text-muted text-center p-3">No hi ha tractaments en aquesta categoria.</p>');
                return;
            }

            let listHtml = '<ul class="list-group list-group-flush small">';
            treatments.forEach(t => {
                // Asegurarse de que tenemos nombre y apellido
                const patientName = (t.apellido || '') + (t.apellido && t.nombre ? ', ' : '') + (t.nombre || '');
                const titleText = `${t.title || 'Sense títol'} ${patientName ? '(' + patientName + ')' : ''}`;

                listHtml += `<li class="list-group-item text-truncate" title="${titleText}">
                                <span>${t.title || 'Sense títol'}</span>
                                ${patientName ? `<small class="text-muted d-block">${patientName}</small>` : ''}
                             </li>`;
            });
            listHtml += '</ul>';
            listDisplay.html(listHtml);
        }

        // 3. Manejador de clics para los filtros
        filterTriggers.on('click', function() {
            const filterType = $(this).data('filter');
            let treatmentsToShow = [];
            let titleToShow = '';

            filterTriggers.removeClass('active');
            $(this).addClass('active');

            switch(filterType) {
                case 'active':
                    treatmentsToShow = treatmentData.active;
                    titleToShow = 'En Curs';
                    break;
                case 'programmed':
                    treatmentsToShow = treatmentData.programmed;
                    titleToShow = 'Programats';
                    break;
                case 'ending_soon':
                    treatmentsToShow = treatmentData.ending_soon;
                    titleToShow = 'Finalitzen (3d)';
                    break;
            }
            renderTreatmentList(treatmentsToShow, titleToShow);
        });

        // 4. Carga inicial
        const initialActiveFilter = filterTriggers.filter('.active').first();
        if (initialActiveFilter.length) {
            initialActiveFilter.trigger('click');
        } else if (filterTriggers.length > 0) {
            filterTriggers.first().trigger('click');
        } else {
             renderTreatmentList([], 'Cap Filtre');
        }
    }
});
</script>