<style>

    /* Para la página principal de Ejercicios (ej: exercises.php) */
    input[name="series"]::placeholder,
    input[name="repetitions"]::placeholder,
    input[name="rest_time"]::placeholder {
        color: #adb5bd !important;
        opacity: 1; /* Necesario para anular el 'opacity' por defecto */
    }

    /* Para los modales de Tratamientos y Protocolos (que usan data-field) */
    input[data-field="series"]::placeholder,
    input[data-field="repetitions"]::placeholder,
    input[data-field="rest_time"]::placeholder {
        color: #adb5bd !important;
        opacity: 1;
    }

    /* --- Prefijos para compatibilidad --- */
    input[name="series"]::-ms-input-placeholder,
    input[name="repetitions"]::-ms-input-placeholder,
    input[name="rest_time"]::-ms-input-placeholder,
    input[data-field="series"]::-ms-input-placeholder,
    input[data-field="repetitions"]::-ms-input-placeholder,
    input[data-field="rest_time"]::-ms-input-placeholder {
        color: #adb5bd !important;
    }
    input[name="series"]:-ms-input-placeholder,
    input[name="repetitions"]:-ms-input-placeholder,
    input[name="rest_time"]:-ms-input-placeholder,
    input[data-field="series"]:-ms-input-placeholder,
    input[data-field="repetitions"]:-ms-input-placeholder,
    input[data-field="rest_time"]:-ms-input-placeholder {
        color: #adb5bd !important;
    }
</style>

<footer class="footer mt-auto py-3">
    <div class="container text-center">
        <span class="text-muted">&copy; <?= date('Y') ?> AVANT ONLINE. Tots els drets reservats.</span>

        <?php // --- INICIO DE LA MODIFICACIÓN (Enlaces Legales) --- ?>
        <div class="mt-2">
            <a href="legal/politica-privacidad.php" class="small text-muted mx-2">Política de Privacitat</a>
            <span class="small text-muted">|</span>
            <a href="legal/terminos-de-uso.php" class="small text-muted mx-2">Termes d'Ús</a>
            <span class="small text-muted">|</span>
            <a href="legal/politica-cookies.php" class="small text-muted ms-2">Política de Cookies</a>
        </div>
        <?php // --- FIN DE LA MODIFICACIÓN --- ?>

    </div>
</footer>

<?php // --- ELIMINADO EL BLOQUE "CANVI RÀPID" Y LA VARIABLE $active_email --- ?>

<style>
    /* --- ELIMINADO: body { padding-bottom: 70px; } --- */

    /* --- FIX: Forçar color blau-verdós al modal de reactivació --- */
    #confirmationModal .modal-header.bg-primary {
       background-color: #77b9af !important; /* Color del botó 'Nou Tractament' */
       color: var(--bs-white) !important;
    }

    /* --- ★ INICIO: Estilos para el Avatar en Modal de Perfil ★ --- */
    .avatar-upload-col {
        border-left: 1px solid #dee2e6; /* Separador visual */
    }
    @media (max-width: 767.98px) {
        .avatar-upload-col {
            border-left: none;
            border-top: 1px solid #dee2e6;
            padding-top: 1rem;
            margin-top: 1rem;
        }
    }
    .avatar-preview-container {
        width: 150px;
        height: 150px;
        position: relative;
        margin: 0 auto 1rem auto;
        border-radius: 50%;
        background-color: #f8f9fa;
        border: 2px dashed #adb5bd;
        display: flex;
        align-items: center;
        justify-content: center;
        overflow: hidden; /* Para que la imagen se ajuste al círculo */
    }
    .avatar-preview-placeholder {
        color: #adb5bd;
        font-size: 5rem;
        line-height: 1;
    }
    .avatar-preview-img {
        width: 100%;
        height: 100%;
        object-fit: cover;
        display: none; /* Oculta por defecto */
    }
    /* --- ★ FIN: Estilos para el Avatar en Modal de Perfil ★ --- */

</style>
<div class="toast-container position-fixed bottom-0 end-0 p-3" style="z-index: 1100">
    <div id="appToast" class="toast align-items-center border-0" role="alert" aria-live="assertive" aria-atomic="true">
        <div class="d-flex"><div class="toast-body" id="toast-body-content"></div><button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast"></button></div>
    </div>
</div>

<div class="modal fade" id="logoutConfirmModal" tabindex="-1">
    <div class="modal-dialog"><div class="modal-content"><div class="modal-header"><h5 class="modal-title">Confirmar Tancament de Sessió</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div><div class="modal-body"><p>Estàs segur/a que vols tancar la sessió?</p></div><div class="modal-footer"><button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel·lar</button><a href="logout.php" class="btn btn-primary">Tancar Sessió</a></div></div></div>
</div>

<?php // ===== INICIO MODIFICACIÓN (Eliminado #preferencesModal) ===== ?>
<?php // El modal de Preferencias ha sido eliminado y su contenido movido a #adminModal ?>
<?php // ===== FIN MODIFICACIÓN ===== ?>

<?php if (isset($_SESSION['user_rol']) && $_SESSION['user_rol'] === 'superadmin'): ?>
<?php // ===== INICIO MODIFICACIÓN (Modal Admin ampliado a modal-xl) ===== ?>
<div class="modal fade" id="adminModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
<?php // ===== FIN MODIFICACIÓN ===== ?>
        <div class="modal-content">
            <div class="modal-header"><h5 class="modal-title">Administració de la Plataforma</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
            <div class="modal-body">

              <ul class="nav nav-tabs mb-3" id="adminTabs" role="tablist">
                  <li class="nav-item" role="presentation">
                      <button class="nav-link active" id="backup-admin-tab" data-bs-toggle="tab" data-bs-target="#backup-admin-panel" type="button" role="tab">
                          <i class="bi bi-database-down me-1"></i> Backups
                      </button>
                  </li>
                  <li class="nav-item" role="presentation">
                      <button class="nav-link" id="maintenance-admin-tab" data-bs-toggle="tab" data-bs-target="#maintenance-admin-panel" type="button" role="tab">
                          <i class="bi bi-shield-check me-1"></i> Manteniment
                      </button>
                  </li>
                  <li class="nav-item" role="presentation">
                      <button class="nav-link" id="audit-admin-tab" data-bs-toggle="tab" data-bs-target="#audit-admin-panel" type="button" role="tab">
                          <i class="bi bi-eye-fill me-1"></i> Auditoria
                      </button>
                  </li>
                  <li class="nav-item" role="presentation">
                      <button class="nav-link" id="ban-list-tab" data-bs-toggle="tab" data-bs-target="#ban-list-panel" type="button">
                          <i class="bi bi-shield-slash me-1"></i> Accés
                      </button>
                  </li>
                  <li class="nav-item" role="presentation">
                      <button class="nav-link" id="email-settings-tab" data-bs-toggle="tab" data-bs-target="#email-settings-panel" type="button">
                          <i class="bi bi-envelope-check me-1"></i> Emails
                      </button>
                  </li>
                  <?php // ===== INICIO MODIFICACIÓN (Añadida pestaña Preferències) ===== ?>
                  <li class="nav-item" role="presentation">
                      <button class="nav-link" id="general-prefs-tab" data-bs-toggle="tab" data-bs-target="#general-prefs-panel" type="button">
                          <i class="bi bi-sliders me-1"></i> Preferències
                      </button>
                  </li>
                  <?php // ===== FIN MODIFICACIÓN ===== ?>
              </ul>

                <div class="tab-content" id="adminTabsContent">
                    <div class="tab-pane fade show active" id="backup-admin-panel" role="tabpanel">
                        <p class="text-muted">Gestiona les còpies de seguretat de la base de dades (es conserven les últimes 5).</p>

                        <div class="mb-4 text-center">
                            <button type="button" class="btn btn-success" id="manualBackupBtn">
                                <span class="spinner-border spinner-border-sm d-none me-2" role="status" aria-hidden="true"></span>
                                <i class="bi bi-database-down me-2"></i> Crear Còpia Manual Ara
                            </button>
                            <div id="backupManualResult" class="mt-2 alert d-none small"></div>
                        </div>
                        <hr>

                        <h6 class="mb-3">Còpies de Seguretat Existents</h6>
                        <div id="backup-list-container" style="max-height: 250px; overflow-y: auto;" class="mb-4 border rounded p-2 bg-light">
                            <p class="text-center text-muted p-3">Carregant llista de còpies...</p>
                        </div>
                        <div id="backupRestoreResult" class="mt-2 alert d-none small"></div>
                        <hr>

                        <h6 class="mb-3">Restaurar des d'un Arxiu Local</h6>
                        <form id="uploadBackupForm" enctype="multipart/form-data">
                            <div class="input-group">
<input class="form-control" type="file" id="backupFileUpload" name="backupFile" accept=".sql" required>
                                <button class="btn btn-warning" type="submit" id="restoreUploadBtn">
                                    <span class="spinner-border spinner-border-sm d-none me-2" role="status" aria-hidden="true"></span>
                                    <i class="bi bi-upload me-1"></i> Restaurar des d'Arxiu
                                </button>
                            </div>
                            <div class="form-text">Selecciona un arxiu `.sql` del teu ordinador. <b>Atenció:</b> Això sobreescriurà la base de dades actual.</div>
                        </form>

                        <div class="progress mt-2" id="uploadProgressBarContainer" style="display: none; height: 25px;">
                            <div id="uploadProgressBar" class="progress-bar progress-bar-striped progress-bar-animated bg-warning text-dark fw-bold" role="progressbar" style="width: 0%;" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">0%</div>
                        </div>
                        <div id="backupUploadResult" class="mt-2 alert d-none small"></div>

                    </div>

                    <div class="tab-pane fade" id="maintenance-admin-panel" role="tabpanel">

                        <p class="text-muted">Aquestes eines realitzen comprovacions i neteja a la base de dades. Fes-les servir amb precaució.</p>
                        <hr>
                        <h6 class="mb-3">Comprovació d'Integritat de Dades</h6>
                        <p class="small text-muted">Busca registres "orfes" (per exemple, evolucions d'exercicis que ja no existeixen). Aquesta acció és **només de lectura** i no esborrarà res.</p>
                        <div class="mb-4 text-center">
                            <button type="button" class="btn btn-info" id="checkIntegrityBtn">
                                <span class="spinner-border spinner-border-sm d-none me-2" role="status" aria-hidden="true"></span>
                                <i class="bi bi-shield-check me-2"></i> Comprovar Integritat de Dades
                            </button>
                            <div id="integrityCheckResult" class="mt-3 alert d-none small"></div>
                        </div>
                    </div>

                    <div class="tab-pane fade" id="audit-admin-panel" role="tabpanel">
                        <h5 class="mb-3"><i class="bi bi-eye-fill text-info me-2"></i> Registre d'Auditoria del Sistema</h5>
                        <p class="text-muted small">Aquesta eina mostra un registre de totes les accions sensibles realitzades a la plataforma (inicis de sessió, suplantacions, eliminacions de tractaments, etc.).</p>
                        <p>Aquesta pàgina pot trigar a carregar si el registre és molt gran.</p>
                        <div class="text-center mt-4">
                            <a href="admin_logs.php" class="btn btn-info" target="_blank">
                                <i class="bi bi-box-arrow-up-right me-2"></i>Obrir el Registre d'Auditoria (en una nova pestanya)
                            </a>
                        </div>
                    </div>

                    <div class="tab-pane fade" id="ban-list-panel" role="tabpanel" aria-labelledby="ban-list-tab">

                        <h5 class="mt-3"><i class="bi bi-envelope-slash-fill me-2"></i> Emails Banejats</h5>
                        <p class="small text-muted">Aquests emails no podran crear un compte nou durant l'auto-registre.</p>

                        <form id="add-ban-email-form" class="row g-3 mb-3 align-items-center">
                            <div class="col-md-5">
                                <label for="ban-email-input" class="visually-hidden">Email</label>
                                <input type="email" name="email" id="ban-email-input" class="form-control" placeholder="correu@exemple.com" required>
                            </div>
                            <div class="col-md-5">
                                <label for="ban-reason-input" class="visually-hidden">Motiu</label>
                                <input type="text" name="reason" id="ban-reason-input" class="form-control" placeholder="Motiu (opcional, ex: Impagament)">
                            </div>
                            <div class="col-md-2">
                                <button type="submit" class="btn btn-warning w-100">Banejar</button>
                            </div>
                        </form>

                        <div id="banned-emails-list-container" class="border rounded p-2" style="max-height: 200px; overflow-y: auto;">
                            <p class="text-muted small p-3 text-center">Carregant llista...</p>
                        </div>

                        <hr class="my-4">

                        <h5><i class="bi bi-key-fill me-2"></i> Contrasenyes Prohibides</h5>
                        <p class="small text-muted">Aquestes contrasenyes no es podran utilitzar en el registre (ex: "123456", "password", "Avant123").</p>

                        <form id="add-prohibited-pass-form" class="row g-3 mb-3 align-items-center">
                            <div class="col-md-10">
                                <label for="prohibited-pass-input" class="visually-hidden">Contrasenya</label>
                                <input type="text" name="password_text" id="prohibited-pass-input" class="form-control" placeholder="Contrasenya perillosa" required>
                            </div>
                            <div class="col-md-2">
                                <button type="submit" class="btn btn-secondary w-100">Prohibir</button>
                            </div>
                        </form>

                        <div id="prohibited-pass-list-container" class="border rounded p-2" style="max-height: 200px; overflow-y: auto;">
                            <p class="text-muted small p-3 text-center">Carregant llista...</p>
                        </div>
                    </div>

                    <div class="tab-pane fade" id="email-settings-panel" role="tabpanel" aria-labelledby="email-settings-tab">
                                        <p class="text-muted small">Selecciona quines comunicacions automàtiques per email s'han d'enviar.</p>

                                        <form id="emailSettingsForm">
                                            <div id="email-settings-container">
                                                <p class="text-muted small p-3 text-center"><span class="spinner-border spinner-border-sm me-2"></span>Carregant configuracions...</p>
                                            </div>

                                            <div class="text-end mt-3 border-top pt-3">
                                                <button type="submit" class="btn btn-primary">
                                                    <span class="spinner-border spinner-border-sm d-none me-2" role="status" aria-hidden="true"></span>
                                                    Guardar Configuració d'Emails
                                                </button>
                                            </div>
                                        </form>
                                    </div>

                    <?php // ===== INICIO MODIFICACIÓN (Añadido panel Preferències) ===== ?>
                    <div class="tab-pane fade" id="general-prefs-panel" role="tabpanel" aria-labelledby="general-prefs-tab">
                        <form id="profilePrefsForm">
                            <p class="text-muted"><b>Ajusta el comportament per defecte de la interfície.</b></p>
                            <div class="form-check form-switch mb-3">
                                <input class="form-check-input" type="checkbox" role="switch" id="filterMineDefaultSwitch" name="filtro_personal_defecto">
                                <label class="form-check-label" for="filterMineDefaultSwitch">Activar el filtre "Només els meus" per defecte en totes les seccions.</label>
                            </div>

                            <div class="mt-3">
                                                            <label for="recordsPerPageSelect" class="form-label"><b>Elements per pàgina</b></label>
                                                            <select class="form-select" id="recordsPerPageSelect" name="records_per_page" style="max-width: 150px;">
                                                                <option value="4">4</option>
                                                                <option value="8">8</option>
                                                                <option value="12">12</option>
                                                                <option value="16">16</option>
                                                                <option value="20">20</option>
                                                                <option value="50">50</option>
                                                                <option value="100">100 (Màxim)</option>
                                                            </select>
                                                            <div class="form-text">Quants registres vols veure per defecte a les llistes (tractaments, exercicis, etc.)</div>
                                                        </div>

                            <div class="text-end mt-4 border-top pt-3">
                                 <button type="submit" form="profilePrefsForm" class="btn btn-primary ms-2">Guardar Preferències</button>
                            </div>
                        </form>
                    </div>
                    <?php // ===== FIN MODIFICACIÓN ===== ?>

                    </div>

                <div class="text-end mt-4 border-top pt-3">
                     <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Tancar</button>
                </div>

            </div>
        </div>
    </div>
</div>
<?php endif; ?>
<?php // ===== INICIO MODIFICACIÓN (Cambiado título del modal) ===== ?>
<div class="modal fade" id="profileModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header"><h5 class="modal-title">Les meves dades personals</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
<?php // ===== FIN MODIFICACIÓN ===== ?>
            <div class="modal-body">
                <ul class="nav nav-tabs" id="profileTabs" role="tablist">
                    <li class="nav-item" role="presentation"><button class="nav-link active" data-bs-toggle="tab" data-bs-target="#data-panel">Dades Personals</button></li>
                    <li class="nav-item" role="presentation"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#password-panel">Canviar Contrasenya</button></li>
                </ul>
                <div class="tab-content pt-3">
                    <div class="tab-pane fade show active" id="data-panel" role="tabpanel">
                        <form id="profileDataForm" novalidate>
                        <div class="row">
                                <div class="col-md-8">
                                    <div class="row">
                                        <div class="col-md-6 mb-3">
                                            <label class="form-label">Nom</label>
                                            <input type="text" name="nombre" class="form-control" required>
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label class="form-label">Cognoms</label>
                                            <input type="text" name="apellido" class="form-control" required>
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div class="col-md-6 mb-3">
                                            <label class="form-label">Email</label>
                                            <input type="email" name="email" class="form-control" required>
                                        </div>
                                        <div class="col-md-6 mb-3">
                                            <label class="form-label">Telèfon</label>
                                            <input type="tel" name="telefono" class="form-control">
                                        </div>
                                    </div>

                                    <?php if (isset($_SESSION['user_rol']) && in_array($_SESSION['user_rol'], ['superadmin', 'fisio'])): ?>

                                    <?php endif; ?>
                                    </div>
                                <div class="col-md-4 avatar-upload-col">
                                    <div class="text-center">
                                        <label class="form-label">Foto de Perfil</label>
                                        <div class="avatar-preview-container" title="Previsualització">
                                            <div class="avatar-preview-placeholder" id="avatar-preview-placeholder">
                                                <i class="bi bi-person-circle"></i>
                                            </div>
                                            <img src="#" alt="Previsualització" class="avatar-preview-img" id="avatar-preview-img">
                                        </div>

                                        <input type="file" id="avatar-upload-input" class="d-none" accept="image/jpeg, image/png, image/gif">

                                        <input type="hidden" name="delete_avatar" id="delete-avatar-input" value="0">

                                        <div class="btn-group btn-group-sm" role="group">
                                            <button type="button" class="btn btn-outline-primary" id="avatar-change-btn">
                                                <i class="bi bi-upload me-1"></i> Canviar...
                                            </button>
                                            <button type="button" class="btn btn-outline-danger" id="avatar-delete-btn" title="Eliminar foto actual">
                                                <i class="bi bi-trash"></i>
                                            </button>
                                        </div>
                                        <div class="form-text text-muted small mt-2">Max. 1MB (JPG, PNG, GIF)</div>
                                    </div>
                                </div>
                                </div>
                            <div class="text-end mt-3 border-top pt-3">
                                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel·lar</button>
                                <button type="submit" class="btn btn-primary ms-2">
                                    <span class="spinner-border spinner-border-sm d-none" role="status" aria-hidden="true"></span>
                                    Guardar Canvis
                                </button>
                            </div>
                        </form>
                    </div>
                    <div class="tab-pane fade" id="password-panel" role="tabpanel">
                        <form id="profilePasswordForm">
                            <?php // El formulario de fisio/admin pide la contraseña actual, el de paciente no ?>
                            <?php if (isset($_SESSION['user_rol']) && in_array($_SESSION['user_rol'], ['superadmin', 'fisio'])): ?>
                                <div class="mb-3"><label class="form-label">Contrasenya Actual</label><div class="password-group"><input type="password" name="current_password" class="form-control" required><button type="button" class="password-toggle-btn"><i class="bi bi-eye-slash"></i></button></div></div>
                                <div class="mb-3"><label class="form-label">Nova Contrasenya</label><div class="password-group"><input type="password" name="new_password" class="form-control" required><button type="button" class="password-toggle-btn"><i class="bi bi-eye-slash"></i></button></div></div>
                                <div class="mb-3"><label class="form-label">Confirmar Nova Contrasenya</label><div class="password-group"><input type="password" name="confirm_new_password" class="form-control" required><button type="button" class="password-toggle-btn"><i class="bi bi-eye-slash"></i></button></div></div>
                            <?php else: // Es paciente ?>
                                <div class="mb-3"><label class="form-label">Nova Contrasenya</label><div class="password-group"><input type="password" name="new_password" class="form-control" required minlength="6" maxlength="12"><button type="button" class="password-toggle-btn"><i class="bi bi-eye-slash"></i></button></div></div>
                                <div class="mb-3"><label class="form-label">Confirmar Nova Contrasenya</label><div class="password-group"><input type="password" name="confirm_new_password" class="form-control" required minlength="6" maxlength="12"><button type="button" class="password-toggle-btn"><i class="bi bi-eye-slash"></i></button></div></div>
                            <?php endif; ?>
                            <div class="text-end mt-3"><button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel·lar</button><button type="submit" class="btn btn-primary ms-2">Canviar Contrasenya</button></div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="deleteChatPatientModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered"><div class="modal-content"><div class="modal-header"><h5 class="modal-title">Eliminar Conversa</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div><div class="modal-body"><p>Estàs segur/a que vols eliminar aquesta conversa?</p><p class="text-muted small">Els missatges antics s'ocultaran. Si el fisioterapeuta et torna a escriure, la conversa començarà de nou només amb els missatges nous.</p><input type="hidden" id="deletePatientChatFisioId"></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="confirmDeletePatientChatBtn">Eliminar</button></div></div></div>
</div>
<div class="modal fade" id="deleteChatFisioModal" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered"><div class="modal-content"><div class="modal-header"><h5 class="modal-title">Eliminar Conversa</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div><div class="modal-body"><p>Com vols eliminar aquesta conversa?</p><div class="form-check"><input class="form-check-input" type="radio" name="deleteChatMode" id="deleteModeSelf" value="self" checked><label class="form-check-label" for="deleteModeSelf">Eliminar només per a mi</label><div class="text-muted small">La conversa s'esborrarà de la teva llista. El pacient conservarà l'historial.</div></div><div class="form-check mt-3"><input class="form-check-input" type="radio" name="deleteChatMode" id="deleteModeBoth" value="both"><label class="form-check-label" for="deleteModeBoth">Eliminar per a mi i per al pacient</label><div class="text-muted small">La conversa s'esborrarà per a tots dos.</div></div><input type="hidden" id="deleteFisioChatPatientId"></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="confirmDeleteFisioChatBtn">Eliminar</button></div></div></div>
</div>

<?php if (isset($_SESSION['user_rol']) && $_SESSION['user_rol'] === 'paciente'): ?>
    <div class="modal fade" id="feedbackModal" tabindex="-1" aria-labelledby="feedbackModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="feedbackModalLabel">...</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="feedbackForm">
                        <input type="hidden" id="tratamientoEjercicioId" name="tratamiento_ejercicio_id">
                        <div class="mb-4">
                            <label class="form-label">Nivell de Dolor (0 = gens, 5 = molt)</label>
                            <div id="rating-dolor" class="star-rating">
                                <i class="bi bi-star" data-value="1"></i><i class="bi bi-star" data-value="2"></i><i class="bi bi-star" data-value="3"></i><i class="bi bi-star" data-value="4"></i><i class="bi bi-star" data-value="5"></i>
                            </div>
                            <input type="hidden" name="dolor_percibido" id="dolor_percibido" value="0">
                        </div>
                        <div class="mb-4">
                            <label class="form-label">Esforç Percebut (0 = gens, 5 = màxim)</label>
                            <div id="rating-esfuerzo" class="star-rating">
                                <i class="bi bi-star" data-value="1"></i><i class="bi bi-star" data-value="2"></i><i class="bi bi-star" data-value="3"></i><i class="bi bi-star" data-value="4"></i><i class="bi bi-star" data-value="5"></i>
                            </div>
                            <input type="hidden" name="esfuerzo_percibido" id="esfuerzo_percibido" value="0">
                        </div>
                        <div>
                            <label for="comentarios" class="form-label">Comentaris (opcional)</label>
                            <textarea class="form-control" id="comentarios" name="comentarios" rows="3" placeholder="..."></textarea>
                        </div>
                    </form>
                </div>
                <div class="modal-footer justify-content-between">
                    <button type="button" class="btn btn-danger" id="deleteFeedbackBtn" style="display: none;">
                        <i class="bi bi-trash me-1"></i> Borrar Valoració
                    </button>
                    <div>
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel·lar</button>
                        <button type="submit" form="feedbackForm" class="btn btn-primary">Guardar Valoració</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="modal fade" id="exerciseModal" tabindex="-1" aria-labelledby="exerciseModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-xl modal-dialog-centered modal-dialog-scrollable">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="exerciseModalLabel">Realitzar Exercici</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div id="exercise-media-container" class="bg-dark rounded text-center mb-3 noselect" oncontextmenu="return false;">
                        </div>
                    <div class="accordion" id="exerciseDetailsAccordion">
                        <div class="accordion-item">
                            <h2 class="accordion-header" id="headingOne">
                                <button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
                                    <i class="bi bi-info-circle me-2"></i> Veure/Amagar Detalls i Pauta
                                </button>
                            </h2>
                            <div id="collapseOne" class="accordion-collapse collapse show" aria-labelledby="headingOne" data-bs-parent="#exerciseDetailsAccordion">
                                <div class="accordion-body">
                                    <h4 id="modal-exercise-title-details"></h4>
                                    <p id="modal-exercise-explanation"></p>
                                    <hr>
                                    <h5>Pauta Específica</h5>

                                    <div id="modal-pauta-container" class="row g-3 mt-2">
                                        <div class="col-12 col-md-6">
                                            <div class="d-flex align-items-center p-2 bg-light rounded">
                                                <i class="bi bi-calendar-check fs-4 text-primary me-3"></i>
                                                <div>
                                                    <strong class="d-block">Frecuencia</strong>
                                                    <span id="modal-pauta-frecuencia" class="text-muted">...</span>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-12 col-md-6">
                                            <div class="d-flex align-items-center p-2 bg-light rounded">
                                                <i class="bi bi-arrow-repeat fs-4 text-primary me-3"></i>
                                                <div>
                                                    <strong class="d-block">Series</strong>
                                                    <span id="modal-pauta-series" class="text-muted">...</span>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-12 col-md-6">
                                            <div class="d-flex align-items-center p-2 bg-light rounded">
                                                <i class="bi bi-stopwatch fs-4 text-primary me-3"></i>
                                                <div>
                                                    <strong class="d-block">Repeticiones</strong>
                                                    <span id="modal-pauta-repetitions" class="text-muted">...</span>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-12 col-md-6">
                                            <div class="d-flex align-items-center p-2 bg-light rounded">
                                                <i class="bi bi-clock-history fs-4 text-primary me-3"></i>
                                                <div>
                                                    <strong class="d-block">Descanso</strong>
                                                    <span id="modal-pauta-rest" class="text-muted">...</span>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <div id="modal-exercise-pauta-notes-container" class="d-none mt-3">
                                        <h6><i class="bi bi-chat-left-text-fill me-2 text-primary"></i>Notes del teu fisio:</h6>
                                        <blockquote class="blockquote bg-light p-3 rounded">
                                            <p class="mb-0" id="modal-exercise-pauta-notes"></p>
                                        </blockquote>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer justify-content-center">
                     <button type="button" class="btn btn-primary btn-lg" data-bs-dismiss="modal">
                        <i class="bi bi-check-circle-fill me-2"></i>He acabat, vull valorar
                    </button>
                </div>
            </div>
        </div>
    </div>
    <div class="modal fade" id="historyModal" tabindex="-1" aria-labelledby="historyModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg modal-dialog-scrollable">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="historyModalLabel">Historial de Tractaments</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body" id="historyModalBody">
                    <div class="text-center p-5">
                        <div class="spinner-border text-primary" role="status">
                            <span class="visually-hidden">Carregant historial...</span>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Tancar</button>
                </div>
            </div>
        </div>
    </div>
<?php endif; ?>

<?php if (isset($_SESSION['user_rol']) && in_array($_SESSION['user_rol'], ['superadmin', 'fisio'])): ?>

    <div class="modal fade" id="confirmationModal" tabindex="-1">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="confirmationModalLabel">Confirmar Acció</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body" id="confirmationModalBody">
                    <p>Estàs segur/a que vols realitzar aquesta acció?</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-primary" id="confirmActionButton">Confirmar</button>
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" id="cloneTreatmentModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header"><h5 class="modal-title">Clonar Tractament</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
                <div class="modal-body">
                    <form id="cloneTreatmentForm">
                        <input type="hidden" name="original_treatment_id">
                        <p>Es crearà una còpia d'aquest tractament. Si us plau, confirma el nou títol i assigna un pacient.</p>
                        <div class="mb-3">
                            <label class="form-label">Nou Títol del Tractament</label>
                            <input type="text" name="title" class="form-control" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Assignar al Pacient</label>
                            <select name="paciente_id" class="form-control" required></select>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel·lar</button>
                            <button type="submit" class="btn btn-primary"><i class="bi bi-copy"></i> Confirmar Clonació</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
    <div class="modal fade" id="selectProtocolModal" tabindex="-1"> <div class="modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">Selecciona un Protocol</h5> <button type="button" class="btn-close" data-bs-dismiss="modal"></button> </div> <div class="modal-body"> <div class="input-group mb-3"> <span class="input-group-text"><i class="bi bi-search"></i></span> <input type="text" id="protocolSearchInputModal" class="form-control" placeholder="Cercar protocols..."> </div> <div id="protocol-list-modal-container" style="max-height: 60vh; overflow-y: auto;"></div> </div> </div> </div> </div>

    <div class="modal fade" id="treatmentModal" tabindex="-1"> <div class="modal-dialog modal-xl"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="treatmentModalLabel">Nou Tractament</h5> <button type="button" class="btn-close" data-bs-dismiss="modal"></button> </div> <div class="modal-body"> <form id="treatmentForm"> <input type="hidden" name="id" id="treatmentId"> <input type="hidden" name="start_date" id="start_date_hidden"> <input type="hidden" name="end_date" id="end_date_hidden"> <input type="hidden" name="paciente_id" id="paciente_id_hidden_field"> <div class="card card-body shadow-sm mb-3">


      <div class="card card-body shadow-sm mb-3"> <div class="row">
          <div class="col-md-4 mb-3 mb-md-0"><label class="form-label">Objectiu / Títol del Tractament <span class="text-danger">*</span></label><input type="text" name="title" class="form-control" required></div>

          <div class="col-md-4 mb-3 mb-md-0">
              <label class="form-label">Pacient <span class="text-danger">*</span></label>
              <select name="paciente_id" id="paciente_id_select" class="form-control" required></select>
          </div>
          <div class="col-md-4 mb-3 mb-md-0"><label class="form-label">Fisios Col·laboradors</label><select name="assigned_fisios[]" id="assigned_fisios_select" multiple></select></div>
      </div> </div>


    </div> <div class="row mb-4"> <div class="col-md-5"> <div class="card card-body shadow-sm h-100"> <h6 class="border-bottom pb-2 mb-3"><i class="bi bi-calendar-check me-2"></i>Programació</h6> <div class="mb-3"> <label class="form-label">Entrega al Pacient</label>

        <div id="delivery-options-wrapper">
            <div class="form-check"><input class="form-check-input" type="radio" name="delivery_option" id="delivery_immediate" value="immediata" checked><label class="form-check-label" for="delivery_immediate">Immediata (visible des d'avui)</label></div>
            <div class="form-check"><input class="form-check-input" type="radio" name="delivery_option" id="delivery_programmed" value="programada"><label class="form-check-label" for="delivery_programmed">Programada (visible a la data d'inici)</label></div>
        </div>
        </div> <div> <label for="date_range_picker" class="form-label">Rang de Dates del Tractament (Inici - Fi) <span class="text-danger">*</span></label> <div class="input-group"> <span class="input-group-text"><i class="bi bi-calendar-range"></i></span> <input type="text" id="date_range_picker" class="form-control" placeholder="Selecciona un rang de dates..." required> </div> </div> </div> </div> <div class="col-md-7"> <div class="card card-body shadow-sm h-100"> <h6 class="border-bottom pb-2 mb-3"><i class="bi bi-file-text me-2"></i>Avaluació Inicial</h6> <div class="row"> <div class="col-md-6"><label class="form-label">Anamnesi</label><textarea name="anamnesis" class="form-control" rows="3"></textarea></div> <div class="col-md-6"><label class="form-label">Diagnòstic Fisioterapèutic</label><textarea name="diagnostico" class="form-control" rows="3"></textarea></div> </div> </div> </div> </div> <div class="row">

          <div class="col-lg-5">
              <div class="card h-100 shadow-sm">
                  <div class="card-header bg-light"><h6><i class="bi bi-person-arms-up me-2"></i>Biblioteca d'Exercicis</h6></div>
                  <div class="card-body p-2">
                      <div class="px-2">
                          <div class="form-check form-switch mb-2">
                              <input class="form-check-input" type="checkbox" role="switch" id="filterMyExercisesModalTreatment">
                              <label class="form-check-label" for="filterMyExercisesModalTreatment">Només els meus</label>
                          </div>
                      </div>
                      <div class="px-2 mb-2">
                          <div class="input-group input-group-sm" style="position: relative;">
                              <input type="text" id="exerciseSearchInput" class="form-control" placeholder="Cercar exercici...">
                              <button class="clear-search-btn" type="button" id="clearModalSearchBtn" style="display: none;"><i class="bi bi-x"></i></button>
                              </div>
                      </div>
                      <div id="exercise-library-container" class="list-group list-group-flush protocol-exercise-library border-top"></div>
                  </div>
              </div>
          </div>


          <div class="col-lg-7"> <div class="card h-100 shadow-sm d-flex flex-column"> <div class="card-header bg-primary text-white"><h6><i class="bi bi-clipboard2-check-fill me-2"></i>Exercicis del Tractament</h6></div> <div id="assigned-exercises-container" class="card-body p-2 flex-grow-1" style="overflow-y: auto; max-height: 400px;"></div> </div> </div> </div> <input type="hidden" name="assigned_exercises" id="assignedExercisesInput"> <div class="modal-footer mt-3"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel·lar</button> <button type="submit" class="btn btn-primary">Guardar Tractament</button> </div> </form> </div> </div> </div> </div>
    <div class="modal fade" id="viewTreatmentModal" tabindex="-1"> <div class="modal-dialog modal-lg modal-dialog-scrollable"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="viewTreatmentModalLabel"></h5> <button type="button" class="btn-close" data-bs-dismiss="modal"></button> </div> <div class="modal-body" id="viewTreatmentModalBody"></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="manageModal" tabindex="-1"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"><h5 class="modal-title" id="manageModalLabel"></h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div> <div class="modal-body" id="manageModalBody"></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-warning" id="archiveBtn">Arxivar</button> <button type="button" class="btn btn-danger" id="deleteBtn">Eliminar</button> </div> </div> </div> </div>
    <div class="modal fade" id="exercise-change-confirmation-modal" tabindex="-1"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header bg-danger text-white"> <h5 class="modal-title"><i class="bi bi-exclamation-triangle-fill me-2"></i>Confirmació d'Eliminació de Dades</h5> <button type="button" class="btn-close" data-bs-dismiss="modal"></button> </div> <div class="modal-body"> <p>Estàs a punt d'<strong>eliminar</strong> un exercici d'aquest tractament que ja té <strong>dades d'evolució</strong> registrades pel pacient.</p> <div class="alert alert-danger">Aquesta acció <strong>esborrarà permanentment</strong> tot el progrés i feedback associat a l'exercici:</div> <ul id="exercises-to-delete-list" class="list-group mb-3"></ul> <p>Estàs absolutament segur/a que vols continuar?</p> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">No, Cancel·lar</button> <button type="button" class="btn btn-danger" id="confirm-exercise-delete-btn">Sí, Eliminar i Continuar</button> </div> </div> </div> </div>

    <?php // Modal de Evolución (Solo para fitxa_pacient.php, aunque podría ser global) ?>
    <div class="modal fade" id="evolutionDetailModal" tabindex="-1"> <div class="modal-dialog modal-dialog-scrollable modal-lg modal-fullscreen-md-down"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="evolutionDetailModalLabel">Evolució del Tractament</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body" id="evolutionDetailModalBody" style="display: flex; flex-direction: column;"> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Tancar</button> </div> </div> </div> </div>
<?php endif; ?>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>

<script src="treatment_modal.js?v=2"></script> <?php // <-- HE AÑADIDO ?v=2 PARA FORZAR LA CACHÉ ?>
<script>



    // Función Global showToast
    function showToast(message, type = 'success') {
        const toastEl = document.getElementById('appToast');
        const toastBody = document.getElementById('toast-body-content');
        if (!toastEl || !toastBody) {
             console.error("Toast elements not found!");
             alert(`${type === 'success' ? 'Éxito' : 'Error'}: ${message}`); // Fallback
             return;
        }
        const toast = bootstrap.Toast.getOrCreateInstance(toastEl, { delay: 3000, autohide: true });
        toastBody.textContent = message;
        toastEl.className = 'toast align-items-center border-0 text-white'; // Reset classes

        // --- ★★★ INICIO DE LA CORRECCIÓN ★★★ ---
                if (type === 'success') {
                    toastEl.classList.add('bg-success', 'text-white');
                } else if (type === 'danger') {
                    toastEl.classList.add('bg-danger', 'text-white');
                } else if (type === 'warning') {
                    // El amarillo (warning) necesita texto oscuro para leerse bien
                    toastEl.classList.add('bg-warning', 'text-dark');
                } else {
                    // Asumimos 'info' (o cualquier otro)
                    toastEl.classList.add('bg-info', 'text-white'); // bg-info es azul claro
                }
                // --- ★★★ FIN DE LA CORRECCIÓN ★★★ ---

        toast.show();
    }

    // --- ======================================================= ---
    // --- INICIO: CORRECCIÓN DEFINITIVA checkUnreadMessages
    // --- ======================================================= ---
    // Función Global checkUnreadMessages
    function checkUnreadMessages(force = false) {

        // Comprobamos si estamos en una página de chat (fisio o paciente)
        const currentPath = window.location.pathname;
        const isOnChatPage = (currentPath.endsWith('/chat_inbox.php') || currentPath.endsWith('/chat_patient.php'));

        // *** LA CLAVE ESTÁ AQUÍ ***
        // Si estamos en una página de chat Y la función NO ha sido llamada explícitamente
        // con 'force = true' (es decir, es una llamada automática del setInterval o del document.ready),
        // entonces NO hacemos NADA.
        if (isOnChatPage && !force) {
             // console.log("checkUnreadMessages skipped: On chat page and not forced.");
            return;
        }

        // Si no estamos en página de chat, o si la llamada fue forzada (desde chat_patient.php),
        // continuamos con la lógica normal para obtener y mostrar el contador.
        const userRole = '<?php echo $_SESSION['user_rol'] ?? 'none'; ?>';
        let endpoint = '';
        if (userRole === 'paciente') {
            endpoint = 'patient_ajax.php';
        } else if (userRole === 'fisio' || userRole === 'superadmin') {
            endpoint = 'dashboard.php';
        } else {
            return; // Rol desconocido o no logueado
        }

        $.getJSON(`${endpoint}?ajax=true&action=get_unread_message_count`)
            .done(function(response) {
                const badge = $('#unread-messages-badge');
                const countSpan = $('#unread-messages-count');
                if (badge.length === 0 || countSpan.length === 0) return;

                if (response.status === 'success' && response.count > 0) {
                    // Aseguramos que count sea un número antes de comparar
                    const count = Number(response.count);
                    countSpan.text(count > 9 ? '9+' : count);
                    badge.show();
                } else {
                    badge.hide();
                    countSpan.text('');
                }
            }).fail(() => {
                // Ocultar badge en caso de error
                const badge = $('#unread-messages-badge');
                if (badge.length > 0) badge.hide();
                const countSpan = $('#unread-messages-count');
                if (countSpan.length > 0) countSpan.text('');
            });
    }
    // --- ======================================================= ---
    // --- FIN: CORRECCIÓN DEFINITIVA checkUnreadMessages
    // --- ======================================================= ---

    // ★★★ INICIO: FUNCIÓN escapeHtml MOVIDA (CORRECCIÓN BUG SINTAXIS) ★★★
    // **FUNCIÓN GLOBAL MOVILIZADA**
    function escapeHtml(text) {
        if (typeof text !== 'string') return '';
        var map = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#039;' };
        return text.replace(/[&<>"']/g, function(m) { return map[m]; });
    }
    // ★★★ FIN: FUNCIÓN escapeHtml MOVIDA ★★★
    /* Aplica un efecto "flash" a un elemento jQuery específico.
    * Asume que la clase CSS 'flash-attention' está cargada globalmente.
    *
    * @param {jQuery} $elementToFlash El objeto jQuery (fila, card, etc.) a flashear.
    */
   function flashElement($elementToFlash) {
       if (!$elementToFlash || $elementToFlash.length === 0) {
           console.warn("flashElement: No se encontró el elemento para flashear.");
           return;
       }

       // 1. Nos aseguramos de que sea visible (scroll)
       $('html, body').animate({
           scrollTop: $elementToFlash.offset().top - 150 // -150px para dar margen
       }, 500);

       // 2. Añadimos la clase CSS global
       $elementToFlash.addClass('flash-attention');

       // 3. La quitamos después de 3.5 segundos
       setTimeout(() => {
           $elementToFlash.removeClass('flash-attention');
       }, 3500);
   }


$(document).ready(function() {




    // Inicializar Tooltips
    new bootstrap.Tooltip(document.body, { selector: "[data-bs-toggle='tooltip']" });

    // Lógica Logout Confirm
    if ($('#logoutConfirmModal').length > 0) {
        const logoutModal = new bootstrap.Modal(document.getElementById('logoutConfirmModal'));
        $('a[href="logout.php"]').not('#confirmLogoutBtn').on('click', function(event) {
            if ($(this).closest('#logoutConfirmModal').length === 0) {
                event.preventDefault();
                logoutModal.show();
            }
        });
    }

    // ===== INICI: SOLUCIÓ PER AL 'PASSWORD TOGGLE' =====
        $(document).on('click', '.password-toggle-btn', function() {
            const $input = $(this).closest('.password-group').find('input');
            const $icon = $(this).find('i');

            if ($input.attr('type') === 'password') {
                $input.attr('type', 'text');
                $icon.removeClass('bi-eye-slash').addClass('bi-eye');
            } else {
                $input.attr('type', 'password');
                $icon.removeClass('bi-eye').addClass('bi-eye-slash');
            }
        });
        // ===== FI: SOLUCIÓ PER AL 'PASSWORD TOGGLE' =====

    // --- ======================================================= ---
    // --- INICIO: LÓGICA MODAL PERFIL UNIFICADA (MODIFICADA PARA AVATAR)
    // --- ======================================================= ---
    if ($('#profileModal').length > 0) {
        const profileModalEl = document.getElementById('profileModal');
        const profileModal = new bootstrap.Modal(profileModalEl);

        // Selectores de Avatar
        const avatarPreviewImg = $('#avatar-preview-img');
        const avatarPreviewPlaceholder = $('#avatar-preview-placeholder');
        const avatarUploadInput = $('#avatar-upload-input');
        const deleteAvatarInput = $('#delete-avatar-input');

        // Determinar el endpoint y la acción correctos según el rol
        const userRoleForProfile = '<?php echo $_SESSION['user_rol'] ?? 'none'; ?>';
        const isPaciente = userRoleForProfile === 'paciente';

        const profileEndpoint = isPaciente ? 'patient_ajax.php' : 'dashboard.php';
        const getAction = isPaciente ? 'get_patient_data' : 'get_profile_data';
        const updateDataAction = isPaciente ? 'update_personal_data' : 'update_profile';
        const updatePassAction = isPaciente ? 'update_password' : 'change_password';

        // (c) Botón para cambiar foto
        $('#avatar-change-btn').on('click', function() {
            avatarUploadInput.click();
        });

        // (d) Botón para eliminar foto
        $('#avatar-delete-btn').on('click', function() {
            avatarPreviewImg.attr('src', '#').hide();
            avatarPreviewPlaceholder.show();
            avatarUploadInput.val(''); // Limpiar selección de archivo
            deleteAvatarInput.val('1'); // Marcar para borrado
            showToast('Es guardarà sense foto de perfil.', 'success');
        });

        // (c) Previsualización al seleccionar archivo
        avatarUploadInput.on('change', function(e) {
            const file = e.target.files[0];
            if (!file) return;

            // Validación de tipo
            const allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
            if (!allowedTypes.includes(file.type)) {
                showToast('Format de fitxer no permès (només JPG, PNG, GIF).', 'danger');
                avatarUploadInput.val('');
                return;
            }

            // (c) Validación de tamaño 1MB
            const maxSize = 1048576; // 1MB
            if (file.size > maxSize) {
                showToast('El fitxer és massa gran (màx. 1 MB).', 'danger');
                avatarUploadInput.val('');
                return;
            }

            // Previsualización (c)
            const reader = new FileReader();
            reader.onload = function(event) {
                avatarPreviewImg.attr('src', event.target.result).show();
                avatarPreviewPlaceholder.hide();
                deleteAvatarInput.val('0'); // Asegurarse de que no está marcado para borrado
            }
            reader.readAsDataURL(file);
        });


        $(profileModalEl).on('show.bs.modal', function() {
            // Resetear formularios y traer datos
            $('#profilePasswordForm')[0].reset();
            const $submitBtn = $('#profileDataForm').find('button[type="submit"]');
            $submitBtn.prop('disabled', false).find('.spinner-border').addClass('d-none');

            // Resetear estado del avatar
            avatarPreviewImg.attr('src', '#').hide();
            avatarPreviewPlaceholder.show();
            avatarUploadInput.val('');
            deleteAvatarInput.val('0');

            $.getJSON(`${profileEndpoint}?ajax=true&action=${getAction}`, response => {
                if (response.status === 'success') {
                    // 'data.data' es para fisio, 'data' es para paciente (según lógica original)
                    const data = isPaciente ? (response.data.data || response.data) : response.data;

                    $('#profileDataForm [name="nombre"]').val(data.nombre);
                    $('#profileDataForm [name="apellido"]').val(data.apellido);
                    $('#profileDataForm [name="email"]').val(data.email);
                    $('#profileDataForm [name="telefono"]').val(data.telefono);

                    // Cargar filtro (solo fisio/admin)
                    if (!isPaciente) {
                        // Esta lógica se mueve al modal de admin
                        // $('#profileFilterMineDefaultSwitch').prop('checked', data.filtro_personal_defecto == 1);
                    }

                    // ★ INICIO MODIFICACIÓN: Cargar avatar actual ★
                    if (data.avatar && data.avatar.trim() !== '') {
                        // Añadir un "cache buster" (timestamp) para evitar que la imagen antigua se quede en caché
                        avatarPreviewImg.attr('src', data.avatar + '?t=' + new Date().getTime()).show();
                        avatarPreviewPlaceholder.hide();
                    } else {
                        avatarPreviewImg.hide();
                        avatarPreviewPlaceholder.show();
                    }
                    // ★ FIN MODIFICACIÓN ★
                }
            });
            // Mostrar siempre la primera pestaña (Datos Personales) al abrir
            const firstTab = new bootstrap.Tab($('#profileTabs button:first'));
            firstTab.show();
        });

        // Handler para guardar DATOS PERSONALES (MODIFICADO PARA FormData)
        $('#profileDataForm').on('submit', function(e) {
            e.preventDefault();
            const $form = $(this);
            const $submitBtn = $form.find('button[type="submit"]');

            $submitBtn.prop('disabled', true).find('.spinner-border').removeClass('d-none');

            const url = `${profileEndpoint}?ajax=true&action=${updateDataAction}`;

            // (c) Usar FormData para enviar el formulario y el archivo
            const formData = new FormData(this);

            // Adjuntar el archivo de avatar si se seleccionó uno nuevo
            const fileInput = avatarUploadInput[0];
            if (fileInput.files.length > 0) {
                formData.append('avatar', fileInput.files[0]);
            }

            $.ajax({
                url: url,
                type: 'POST',
                data: formData,
                processData: false, // Requerido para FormData
                contentType: false, // Requerido para FormData
                dataType: 'json',
                success: function(res) {
                    if (res.status === 'success') {
                        showToast(res.message, 'success');
                        profileModal.hide();

                        // --- ★★★ INICIO DE LA MODIFICACIÓN ★★★ ---
                        // Comprobar si estamos en la página de usuarios.php
                        if (window.location.pathname.endsWith('/users.php')) {
                            // Si es así, recargar la página para ver los cambios en la tabla
                            location.reload();
                        }
                        // --- ★★★ FIN DE LA MODIFICACIÓN ★★★ ---

                        // Determinar los datos de respuesta (lógica original)
                        const newName = isPaciente ? (res.data?.newName || res.newName) : res.newName;
                        const newAvatarUrl = isPaciente ? (res.data?.newAvatarUrl || res.newAvatarUrl) : (res.newAvatarUrl || '');

                        // Actualizar el saludo (f) (sigue mostrando solo el nombre, como en el JS original)
                        const greetingElement = $('.user-greeting');
                        if (greetingElement.length && newName) {
                            greetingElement.text(`Hola, ${newName}`);
                        }

                        // (f) Actualizar el icono del avatar en el header (ambos headers tienen id="header-avatar-icon")
                        const headerAvatar = $('#header-avatar-icon');
                        if (headerAvatar.length) {
                            if (newAvatarUrl) {
                                // Si hay una nueva URL, creamos/actualizamos la <img>
                                if (headerAvatar.is('div')) { // Si era un placeholder
                                    headerAvatar.replaceWith(`<img src="${newAvatarUrl}" class="user-avatar-icon me-2" alt="Avatar" id="header-avatar-icon">`);
                                } else { // Si ya era 'img'
                                    headerAvatar.attr('src', newAvatarUrl + '?t=' + new Date().getTime()); // Añadir cache-buster
                                }
                            } else {
                                // No hay avatar (se ha borrado)
                                // Reemplazar 'img' por 'div' placeholder
                                if (headerAvatar.is('img')) {
                                    headerAvatar.replaceWith(`<div class="user-avatar-placeholder me-2" id="header-avatar-icon"><i class="bi bi-person-circle"></i></div>`);
                                }
                            }
                        }

                    } else {
                        // Error de lógica devuelto por el servidor
                        showToast(res.message || 'Error desconegut.', 'danger');
                    }
                },
                error: function(xhr) {
                    // Error de red o servidor (500, 404, etc.)
                    showToast(xhr.responseJSON?.message || 'Error de connexió o del servidor.', 'danger');
                },
                complete: function() {
                    // Reactivar el botón en cualquier caso
                    $submitBtn.prop('disabled', false).find('.spinner-border').addClass('d-none');
                }
            });
        });

        // Handler para guardar CONTRASEÑA (Sin cambios)
        $('#profilePasswordForm').on('submit', function(e) { e.preventDefault();
            const url = `${profileEndpoint}?ajax=true&action=${updatePassAction}`;
            const data = $(this).serialize();
            $.post(url, data, 'json')
            .done(res => { showToast(res.message, 'success'); profileModal.hide(); })
            .fail(xhr => showToast(xhr.responseJSON?.message || 'Error desconegut.', 'danger'));
        });
    }
    // --- ======================================================= ---
    // --- FIN: LÓGICA MODAL PERFIL UNIFICADA (MODIFICADA PARA AVATAR)
    // --- ======================================================= ---
    // ★★★ INICIO: LÓGICA MODAL ADMINISTRACIÓN (MODIFICADA) ★★★
    if ($('#adminModal').length > 0 && '<?php echo $_SESSION['user_rol'] ?? 'none'; ?>' === 'superadmin') {
        const adminModal = new bootstrap.Modal(document.getElementById('adminModal'));

        // Evento para resetear y preparar el modal de admin CADA VEZ que se abre
        $('#adminModal').on('show.bs.modal', function() {
             // Asegurar que la primera pestaña (Backups) esté activa
             const firstTabAdmin = new bootstrap.Tab($('#adminTabs button:first'));
             firstTabAdmin.show();

             // Resetear todos los formularios y resultados
             $('#backupManualResult, #backupRestoreResult, #backupUploadResult, #integrityCheckResult').addClass('d-none').removeClass('alert-success alert-danger alert-warning').text('');
             $('#backupFileUpload').val('');
             const $manualButton = $('#manualBackupBtn'); $manualButton.prop('disabled', false); $manualButton.find('.spinner-border').addClass('d-none'); $manualButton.find('i').removeClass('d-none');
             const $uploadButton = $('#restoreUploadBtn'); $uploadButton.prop('disabled', false); $uploadButton.find('.spinner-border').addClass('d-none'); $uploadButton.find('i').removeClass('d-none');
             $('#backupFileUpload').prop('disabled', false);
             $('#backup-list-container').html('<p class="text-center text-muted p-3">Carregant llista de còpies...</p>');

             // ★★★ INICIO MODIFICACIÓN: Resetear barra de progreso ★★★
             $('#uploadProgressBarContainer').hide();
             $('#uploadProgressBar').css('width', '0%').attr('aria-valuenow', 0).text('0%').removeClass('bg-success bg-danger').addClass('bg-warning text-dark');
             // ★★★ FIN MODIFICACIÓN ★★★

             // Resetear la nueva pestaña de "Control d'Accés"
             $('#banned-emails-list-container').html('<p class="text-muted small p-3 text-center">Carregant llista...</p>');
             $('#prohibited-pass-list-container').html('<p class="text-muted small p-3 text-center">Carregant llista...</p>');
             $('#add-ban-email-form')[0].reset();
             $('#add-prohibited-pass-form')[0].reset();
        });

        // Evento para limpiar al cerrar
         $('#adminModal').on('hidden.bs.modal', function () {
             $('#backupManualResult, #backupRestoreResult, #backupUploadResult, #integrityCheckResult').addClass('d-none').text('');
             $('#backupFileUpload').val('');
             $('#backup-list-container').empty();
             // Limpiar también las nuevas listas
             $('#banned-emails-list-container').empty();
             $('#prohibited-pass-list-container').empty();
         });

        // --- ★★★ INICI: CORRECCIÓ BUG (Càrrega inicial de backups) ★★★ ---
        // S'executa QUAN el modal s'ha mostrat completament
        $('#adminModal').on('shown.bs.modal', function() {
            // Comprova si la pestanya activa actual és la de backups
            if ($('#backup-admin-tab').hasClass('active')) {
                // Si ho és, força la càrrega de la llista,
                // ja que l'event 'shown.bs.tab' no s'haurà disparat.
                loadBackupList();
            }
        });
        // --- ★★★ FI: CORRECCIÓ BUG ★★★ ---

        // ===== INICIO MODIFICACIÓN (Lógica movida de #preferencesModal) =====
        // Cargar datos de preferencias cuando se muestra la pestaña de preferencias
        const prefsTabEl = document.getElementById('general-prefs-tab');
        if (prefsTabEl) {
            prefsTabEl.addEventListener('shown.bs.tab', function (event) {
                // Cargar datos solo para la pestaña General (que ahora está aquí)
                $.getJSON('dashboard.php', { ajax: true, action: 'get_profile_data' }, response => {
                    if (response.status === 'success') {
                        $('#filterMineDefaultSwitch').prop('checked', response.data.filtro_personal_defecto == 1);
                        $('#recordsPerPageSelect').val(response.data.records_per_page || 8);
                    }
                });
            });
        }

        // Handler para el formulario de preferencias (que ahora está en adminModal)
        $('#profilePrefsForm').on('submit', function(e) { e.preventDefault();
            const isChecked = $('#filterMineDefaultSwitch').is(':checked') ? 1 : 0;
            const recordsPerPage = $('#recordsPerPageSelect').val();

            $.post('dashboard.php', {
              ajax: true,
              action: 'update_preferences',
              filtro_personal_defecto: isChecked,
              records_per_page: recordsPerPage
            }, 'json')
            .done(res => { showToast(res.message, 'success'); adminModal.hide(); location.reload(); }).fail(xhr => showToast(xhr.responseJSON?.message || 'Error desconegut.', 'danger'));
        });
        // ===== FIN MODIFICACIÓN =====

        // Lógica Backup (movida desde el if(superadmin) anterior)
        $('#manualBackupBtn').on('click', function() {
            const $button = $(this);
            const $spinner = $button.find('.spinner-border');
            const $icon = $button.find('i');
            const $resultDiv = $('#backupManualResult');

            $button.prop('disabled', true); $spinner.removeClass('d-none'); $icon.addClass('d-none');
            $resultDiv.addClass('d-none').removeClass('alert-success alert-danger').text('');

            $.post('dashboard.php', { ajax: true, action: 'manual_backup' }, 'json')
                .done(function(response) {
                    if (response.status === 'success') {
                        $resultDiv.text(response.message).removeClass('d-none').addClass('alert-success');
                        loadBackupList();
                    } else {
                        $resultDiv.text('Error: ' + (response.message || 'Desconegut')).removeClass('d-none').addClass('alert-danger');
                    }
                })
                .fail(function(xhr) {
                    const errorMsg = xhr.responseJSON?.message || xhr.responseText || 'Error de connexió.';
                    $resultDiv.text('Error Greu: ' + errorMsg).removeClass('d-none').addClass('alert-danger');
                })
                .always(function() {
                    $button.prop('disabled', false); $spinner.addClass('d-none'); $icon.removeClass('d-none');
                });
        });

        function loadBackupList() {
            const $listContainer = $('#backup-list-container');
            $listContainer.html('<p class="text-center text-muted p-3"><span class="spinner-border spinner-border-sm me-2"></span>Carregant llista...</p>');
             $('#backupRestoreResult').addClass('d-none').text('');
             $('#backupUploadResult').addClass('d-none').text('');

            $.getJSON('dashboard.php', { ajax: true, action: 'list_backups' })
                .done(function(response) {
                    $listContainer.empty();
                    if (response.status === 'success' && response.backups && response.backups.length > 0) {
                        const listGroup = $('<ul class="list-group"></ul>');
                        response.backups.forEach(backup => {
                            const date = new Date(backup.timestamp * 1000);
                            const formattedDate = date.toLocaleString('ca-ES', { dateStyle: 'short', timeStyle: 'medium' });
                            // --- **** INICIO MODIFICACIÓN: Añadido botón Eliminar **** ---
                            const listItem = $(`
                                <li class="list-group-item d-flex justify-content-between align-items-center flex-wrap">
                                    <div>
                                        <span class="fw-bold text-break">${backup.filename}</span><br>
                                        <small class="text-muted">${formattedDate}</small>
                                    </div>
                                    <div class="btn-group btn-group-sm mt-2 mt-sm-0">
                                        <button class="btn btn-warning restore-backup-btn" data-filename="${backup.filename}" title="Restaurar aquesta còpia">
                                            <i class="bi bi-arrow-counterclockwise"></i> Restaurar
                                        </button>
                                        <a href="download_backup.php?file=${encodeURIComponent(backup.filename)}" class="btn btn-secondary" title="Descarregar còpia" download>
                                            <i class="bi bi-download"></i> Descargar
                                        </a>
                                        <button class="btn btn-danger delete-backup-btn" data-filename="${backup.filename}" title="Eliminar aquesta còpia permanentment">
                                            <i class="bi bi-trash"></i>
                                        </button>
                                    </div>
                                </li>
                            `);
                            // --- **** FIN MODIFICACIÓN **** ---
                            listGroup.append(listItem);
                        });
                        $listContainer.append(listGroup);
                    } else if (response.status === 'success') {
                        $listContainer.html('<p class="text-center text-muted p-3">No hi ha còpies de seguretat disponibles.</p>');
                    } else {
                         $listContainer.html('<p class="text-center text-danger p-3">Error al carregar la llista: ' + (response.message || 'Desconegut') + '</p>');
                    }
                })
                .fail(function(xhr) {
                    const errorMsg = xhr.responseJSON?.message || 'Error de connexió.';
                    $listContainer.html('<p class="text-center text-danger p-3">Error greu al carregar la llista: ' + errorMsg + '</p>');
                });
        }

        // Cargar lista de backups CADA VEZ que se muestra la pestaña de admin de backups
        // ID de la pestaña de backup actualizado a 'backup-admin-tab'
        const backupTabEl = document.getElementById('backup-admin-tab');
        if (backupTabEl) {
            backupTabEl.addEventListener('shown.bs.tab', function (event) {
                loadBackupList();
            });
        }

        $('#backup-list-container').on('click', '.restore-backup-btn', function() {
            const filename = $(this).data('filename');
            const $button = $(this);
            const $resultDiv = $('#backupRestoreResult');

            if (!filename) return;
            if (!confirm(`ATENCIÓ!\n\nEstàs segur que vols RESTAURAR la base de dades utilitzant la còpia "${filename}"?\n\nAixò sobreescriurà TOTES les dades actuals amb les de la còpia de seguretat seleccionada. Aquesta acción NO es pot desfer.`)) return;

            $button.prop('disabled', true).html('<span class="spinner-border spinner-border-sm"></span>');
            $('.restore-backup-btn, .delete-backup-btn, #manualBackupBtn, #restoreUploadBtn').prop('disabled', true);
            $resultDiv.addClass('d-none').removeClass('alert-success alert-danger').text('');

            $.post('dashboard.php', { ajax: true, action: 'restore_backup', filename: filename }, 'json')
                .done(function(response) {
                    if (response.status === 'success') {
                        $resultDiv.text(response.message).removeClass('d-none').addClass('alert-success');
                        alert("Restauració completada. Es recomana recarregar la pàgina (Ctrl+R o Cmd+R) per veure els canvis.");
                    } else {
                        $resultDiv.text('Error: ' + response.message).removeClass('d-none').addClass('alert-danger');
                    }
                })
                .fail(function(xhr) {
                    const errorMsg = xhr.responseJSON?.message || 'Error de connexió.';
                    $resultDiv.text('Error Greu: ' + errorMsg).removeClass('d-none').addClass('alert-danger');
                })
                .always(function() {
                     $button.prop('disabled', false).html('<i class="bi bi-arrow-counterclockwise"></i> Restaurar');
                     $('.restore-backup-btn, .delete-backup-btn, #manualBackupBtn, #restoreUploadBtn').prop('disabled', false);
                });
        });

        $('#backup-list-container').on('click', '.delete-backup-btn', function() {
            const filename = $(this).data('filename');
            const $button = $(this);
            const $resultDiv = $('#backupRestoreResult'); // Reutilizar el div de resultados

            if (!filename) return;
            if (!confirm(`ATENCIÓ!\n\nEstàs segur que vols ELIMINAR PERMANENTMENT la còpia de seguretat "${filename}"?\n\nAquesta acció NO es pot desfer.`)) return;

            $button.prop('disabled', true).html('<span class="spinner-border spinner-border-sm"></span>');
            $('.restore-backup-btn, .delete-backup-btn, #manualBackupBtn, #restoreUploadBtn').prop('disabled', true);
            $resultDiv.addClass('d-none').removeClass('alert-success alert-danger').text('');

            $.post('dashboard.php', { ajax: true, action: 'delete_backup', filename: filename }, 'json')
                .done(function(response) {
                    if (response.status === 'success') {
                        $resultDiv.text(response.message).removeClass('d-none').addClass('alert-success');
                        loadBackupList();
                    } else {
                        $resultDiv.text('Error: ' + response.message).removeClass('d-none').addClass('alert-danger');
                    }
                })
                .fail(function(xhr) {
                    const errorMsg = xhr.responseJSON?.message || 'Error de connexió.';
                    $resultDiv.text('Error Greu: ' + errorMsg).removeClass('d-none').addClass('alert-danger');
                })
                .always(function() {
                     $('.restore-backup-btn, .delete-backup-btn, #manualBackupBtn, #restoreUploadBtn').prop('disabled', false);
                });
        });

        // --- ★★★ INICIO DE LA MODIFICACIÓN: Lógica de subida de backups por Chunks ★★★ ---
        // Se reemplaza el manejador $('#uploadBackupForm').on('submit', ...) anterior

        $('#uploadBackupForm').on('submit', function(e) {
            e.preventDefault();

            const $form = $(this);
            const $button = $('#restoreUploadBtn');
            const $spinner = $button.find('.spinner-border');
            const $icon = $button.find('i');
            const $fileInput = $('#backupFileUpload');
            const $resultDiv = $('#backupUploadResult');
            const $progressContainer = $('#uploadProgressBarContainer');
            const $progressBar = $('#uploadProgressBar');

            const file = $fileInput.prop('files')[0];

            if (!file) {
                $resultDiv.text('Error: Has de seleccionar un arxiu.').removeClass('d-none').addClass('alert-danger');
                return;
            }
            if (!file.name.endsWith('.sql')) {
                $resultDiv.text('Error: El arxiu ha de ser de tipus .sql.').removeClass('d-none').addClass('alert-danger');
                return;
            }

            if (!confirm(`ATENCIÓ!\n\nEstàs segur que vols RESTAURAR la base de dades utilitzant l'arxiu local "${file.name}"?\n\nAixò sobreescriurà TOTES les dades actuals amb les de l'arxiu pujat. Aquesta acción NO es pot desfer.`)) {
                return;
            }

            // Deshabilitar botones y resetear UI
            $button.prop('disabled', true);
            $spinner.removeClass('d-none');
            $icon.addClass('d-none');
            $fileInput.prop('disabled', true);
            $('.restore-backup-btn, .delete-backup-btn, #manualBackupBtn').prop('disabled', true);
            $resultDiv.addClass('d-none').removeClass('alert-success alert-danger').text('');

            // Mostrar y resetear barra de progreso
            $progressContainer.show();
            $progressBar.css('width', '0%').attr('aria-valuenow', 0).text('0%').removeClass('bg-success bg-danger').addClass('bg-warning text-dark');

            // --- Lógica de Chunks ---
            const CHUNK_SIZE = 2 * 1024 * 1024; // 2 MB por chunk
            const totalChunks = Math.ceil(file.size / CHUNK_SIZE);
            let chunkIndex = 0;

            // Nombre de archivo temporal único para ensamblar en el servidor
            const tempFilename = Date.now() + '_' + file.name + '.part';

            // Función recursiva para subir chunks
            function uploadChunk(start) {
                const end = Math.min(start + CHUNK_SIZE, file.size);
                const chunk = file.slice(start, end);
                const chunkFormData = new FormData();

                chunkFormData.append('backupFileChunk', chunk, file.name);
                chunkFormData.append('chunkIndex', chunkIndex);
                chunkFormData.append('totalChunks', totalChunks);
                chunkFormData.append('originalFilename', file.name);
                chunkFormData.append('tempFilename', tempFilename);

                const xhr = new XMLHttpRequest();
                xhr.open('POST', 'upload_backup_chunk.php', true); // Apunta al nuevo script PHP

                // Progreso de la subida DEL CHUNK ACTUAL
                xhr.upload.onprogress = function(e) {
                    if (e.lengthComputable) {
                        const chunkPercent = (e.loaded / e.total) * 100;
                        // Calcular progreso total
                        const totalPercent = ((chunkIndex / totalChunks) + (chunkPercent / 100 / totalChunks)) * 100;
                        const percentFixed = totalPercent.toFixed(0);
                        $progressBar.css('width', percentFixed + '%').attr('aria-valuenow', percentFixed).text(percentFixed + '%');
                    }
                };

                // Cuando la petición XHR finaliza (chunk subido o error)
                xhr.onload = function() {
                    if (xhr.status === 200) {
                        let response;
                        try {
                            response = JSON.parse(xhr.responseText);
                        } catch (err) {
                            handleUploadError('Error: Resposta invàlida del servidor.');
                            return;
                        }

                        if (response.status === 'chunk_success') {
                            // Chunk subido, vamos por el siguiente
                            chunkIndex++;
                            if (chunkIndex < totalChunks) {
                                uploadChunk(end); // Llamada recursiva
                            }
                            // Si era el último, el PHP habrá devuelto 'success' o 'error'

                        } else if (response.status === 'success') {
                            // --- ¡RESTAURACIÓN COMPLETADA! ---
                            // El PHP ya ha procesado el último chunk y restaurado la DB
                            $resultDiv.text(response.message).removeClass('d-none').addClass('alert-success');
                            $progressBar.css('width', '100%').attr('aria-valuenow', 100).text('Completat!');
                            $progressBar.removeClass('bg-warning text-dark').addClass('bg-success');
                            alert("Restauració des d'arxiu local completada. Es recomana recarregar la pàgina (Ctrl+R o Cmd+R) per veure els canvis.");
                            $fileInput.val('');
                            resetUploadUI();
                            loadBackupList(); // Recargar la lista de backups por si acaso

                        } else {
                            // Error devuelto por el servidor (PHP)
                            handleUploadError(response.message || 'Error desconegut al processar el fitxer.');
                        }

                    } else {
                        // Error de HTTP (404, 500, 403)
                        let errorMsg = 'Error Greu: ' + xhr.statusText;
                         try {
                            let response = JSON.parse(xhr.responseText);
                            errorMsg = response.message || errorMsg;
                        } catch (err) {}
                        handleUploadError(errorMsg);
                    }
                };

                // Error de red
                xhr.onerror = function() {
                    handleUploadError('Error de xarxa. Comprova la teva connexió.');
                };

                xhr.send(chunkFormData);
            }

            // Función para manejar errores y limpiar la UI
            function handleUploadError(message) {
                $resultDiv.text('Error: ' + message).removeClass('d-none').addClass('alert-danger');
                $progressBar.css('width', '100%').text('Error');
                $progressBar.removeClass('bg-warning text-dark').addClass('bg-danger');
                resetUploadUI();
            }

            // Función para reactivar la UI
            function resetUploadUI() {
                $button.prop('disabled', false);
                $spinner.addClass('d-none');
                $icon.removeClass('d-none');
                $fileInput.prop('disabled', false);
                $('.restore-backup-btn, .delete-backup-btn, #manualBackupBtn').prop('disabled', false);
                // Ocultar la barra de progreso después de 3 segundos
                setTimeout(() => {
                     $progressContainer.hide();
                     $progressBar.removeClass('bg-success bg-danger').addClass('bg-warning text-dark');
                }, 3000);
            }

            // Iniciar la subida del primer chunk
            uploadChunk(0);
        });
        // --- ★★★ FIN DE LA MODIFICACIÓN ★★★ ---


        // Lógica Mantenimiento (movida)
        $('#checkIntegrityBtn').on('click', function() {
            const $button = $(this);
            const $spinner = $button.find('.spinner-border');
            const $icon = $button.find('i');
            const $resultDiv = $('#integrityCheckResult');

            $button.prop('disabled', true);
            $spinner.removeClass('d-none');
            $icon.addClass('d-none');
            $resultDiv.addClass('d-none').removeClass('alert-success alert-warning alert-danger').html('');

            $.getJSON('dashboard.php', { ajax: true, action: 'check_data_integrity' })
                .done(function(response) {
                    if (response.status === 'success' && response.report) {

                        const labels = {
                            orphan_evolutions: 'Evoluciones huérfanas (sin ejercicio vinculado)',
                            orphan_exercises: 'Ejercicios de tratamiento huérfanos (sin tratamiento vinculado)',
                            orphan_treatment_to_exercise_links: 'Ejercicios de tratamiento huérfanos (sin ejercicio en la biblioteca)',
                            orphan_chat_sender: 'Mensajes de chat (emisor huérfano)',
                            orphan_chat_receiver: 'Mensajes de chat (receptor huérfano)',
                            orphan_treatment_fisios: 'Asignaciones de fisio huérfanas (sin tratamiento vinculado)',
                            orphan_fisio_accounts: 'Asignaciones de fisio huérfanas (sin cuenta de fisio vinculada)',
                            orphan_notifications: 'Notificaciones huérfanas (sin cuenta de fisio vinculada)',
                            orphan_treatments_patient: 'Tratamientos huérfanos (sin paciente vinculado)',
                            orphan_treatments_creator: 'Tratamientos huérfanos (sin fisio creador vinculado)'
                        };

                        let issuesFound = 0;
                        let reportHtml = '<strong>Informe d\'Integritat:</strong><ul class="mb-0 mt-2" style="font-size: 0.85rem;">';
                        let actionsHtml = '<hr><h6 class="text-danger mb-3">Acciones de Limpieza (Destructivas)</h6>';
                        let actionsAvailable = false;

                        for (const key in response.report) {
                            const count = parseInt(response.report[key]) || 0;
                            const label = labels[key] || key;

                            if (count > 0) {
                                issuesFound += count;
                                reportHtml += `<li class="text-danger">${label}: <strong>${count}</strong></li>`;
                                actionsHtml += `
                                    <div class="d-flex justify-content-between align-items-center mb-2 pb-2 border-bottom">
                                        <span class="small">Purgar <strong>${count}</strong> "${label}"</span>
                                        <button class="btn btn-sm btn-outline-danger purge-btn" data-action="purge_${key}" data-label="${label}">
                                            <i class="bi bi-trash3 me-1"></i> Purgar
                                        </button>
                                    </div>`;
                                actionsAvailable = true;
                            } else {
                                reportHtml += `<li class="text-success">${label}: <strong>0</strong></li>`;
                            }
                        }
                        reportHtml += '</ul>';

                        if (issuesFound > 0) {
                            $resultDiv.html(reportHtml + (actionsAvailable ? actionsHtml : ''))
                                     .removeClass('d-none').addClass('alert-warning');
                        } else {
                            $resultDiv.html('<strong><i class="bi bi-check-circle-fill me-2"></i>Informe d\'Integritat:</strong> No s\'han trobat problemes d\'integritat en les dades.').removeClass('d-none').addClass('alert-success');
                        }

                    } else {
                        $resultDiv.text('Error: ' + (response.message || 'Respuesta inesperada.')).removeClass('d-none').addClass('alert-danger');
                    }
                })
                .fail(function(xhr) {
                    const errorMsg = xhr.responseJSON?.message || 'Error de connexió.';
                    $resultDiv.text('Error Greu: ' + errorMsg).removeClass('d-none').addClass('alert-danger');
                })
                .always(function() {
                    $button.prop('disabled', false);
                    $spinner.addClass('d-none');
                    $icon.removeClass('d-none');
                });
        });

        $('#integrityCheckResult').on('click', '.purge-btn', function() {
            const $button = $(this);
            const action = $button.data('action');
            const label = $button.data('label');
            if (!action) return;
            const confirmMsg = `ATENCIÓ:\n\n¿Estás SEGURO de que quieres purgar permanentemente todos los registros de "${label}"?\n\nEsta acción NO se puede deshacer.`;

            if (confirm(confirmMsg)) {
                $button.prop('disabled', true).html('<span class="spinner-border spinner-border-sm me-2"></span> Purgando...');
                $('.purge-btn').not($button).prop('disabled', true);
                $.post('dashboard.php', { ajax: true, action: action }, 'json')
                    .done(function(response) {
                        if (response.status === 'success') {
                            showToast(response.message || 'Purga completada.', 'success');
                            $('#checkIntegrityBtn').click();
                        } else {
                            showToast(response.message || 'Error al purgar.', 'danger');
                            $button.prop('disabled', false).html('<i class="bi bi-trash3 me-1"></i> Purgar');
                            $('.purge-btn').prop('disabled', false);
                        }
                    })
                    .fail(function(xhr) {
                        showToast(xhr.responseJSON?.message || 'Error de connexió.', 'danger');
                        $button.prop('disabled', false).html('<i class="bi bi-trash3 me-1"></i> Purgar');
                        $('.purge-btn').prop('disabled', false);
                    });
            }
        });

        // --- ★★★ INICIO PASO 4: AÑADIR LÓGICA JS "CONTROL D'ACCÉS" ★★★ ---
        // ======================================================= -->
        // ============ INICIO: LÓGICA DE CONTROL D'ACCÉS ======== -->
        // ======================================================= -->

        // Función para (re)cargar las dos listas (emails y contraseñas)
        function loadBanLists() {
            const $emailListContainer = $('#banned-emails-list-container');
            const $passListContainer = $('#prohibited-pass-list-container');

            // --- Cargar Emails Baneados ---
            $emailListContainer.html('<p class="text-muted small p-3 text-center"><span class="spinner-border spinner-border-sm me-2"></span>Carregant llista d\'emails...</p>');
            $.getJSON('dashboard.php', { ajax: true, action: 'get_banned_list' })
                .done(function(response) {
                    if (response.status === 'success' && response.data) {
                        $emailListContainer.empty();
                        if (response.data.length === 0) {
                            $emailListContainer.html('<p class="text-muted small p-3 text-center">No hi ha emails banejats.</p>');
                            return;
                        }

                        const $list = $('<ul class="list-group list-group-flush"></ul>');
                        response.data.forEach(item => {
                            const adminName = (item.nombre && item.apellido) ? `${escapeHtml(item.nombre)} ${escapeHtml(item.apellido)}` : 'Admin desconegut';
                            const banDate = new Date(item.banned_at).toLocaleString('ca-ES', { day: '2-digit', month: '2-digit', year: 'numeric' });

                            $list.append(`
                                <li class="list-group-item d-flex justify-content-between align-items-center flex-wrap">
                                    <div style="min-width: 0; flex-basis: 300px; flex-grow: 1;">
                                        <strong class="text-break">${escapeHtml(item.email)}</strong>
                                        <small class="d-block text-muted text-truncate" title="Motiu: ${escapeHtml(item.reason)}">Motiu: ${escapeHtml(item.reason)}</small>
                                        <small class="d-block text-muted" style="font-size: 0.75rem;">Banejat per: ${adminName} el ${banDate}</small>
                                    </div>
                                    <button class="btn btn-sm btn-outline-danger remove-ban-btn mt-2 mt-sm-0" data-id="${item.id}" data-type="email" title="Eliminar baneig">
                                        <i class="bi bi-trash"></i>
                                    </button>
                                </li>
                            `);
                        });
                        $emailListContainer.append($list);
                    } else {
                        $emailListContainer.html(`<p class="text-danger small p-3 text-center">${escapeHtml(response.message || 'Error al carregar emails.')}</p>`);
                    }
                })
                .fail(xhr => $emailListContainer.html(`<p class="text-danger small p-3 text-center">Error de connexió: ${escapeHtml(xhr.responseJSON?.message || 'Error')}</p>`));

            // --- Cargar Contraseñas Prohibidas ---
            $passListContainer.html('<p class="text-muted small p-3 text-center"><span class="spinner-border spinner-border-sm me-2"></span>Carregant llista de contrasenyes...</p>');
            $.getJSON('dashboard.php', { ajax: true, action: 'get_prohibited_passwords' })
                .done(function(response) {
                    if (response.status === 'success' && response.data) {
                        $passListContainer.empty();
                        if (response.data.length === 0) {
                            $passListContainer.html('<p class="text-muted small p-3 text-center">No hi ha contrasenyes prohibides.</p>');
                            return;
                        }

                        const $list = $('<ul class="list-group list-group-flush"></ul>');
                        response.data.forEach(item => {
                            $list.append(`
                                <li class="list-group-item d-flex justify-content-between align-items-center">
                                    <code>${escapeHtml(item.password_text)}</code>
                                    <button class="btn btn-sm btn-outline-danger remove-ban-btn" data-id="${item.id}" data-type="password" title="Eliminar prohibició">
                                        <i class="bi bi-trash"></i>
                                    </button>
                                </li>
                            `);
                        });
                        $passListContainer.append($list);
                    } else {
                        $passListContainer.html(`<p class="text-danger small p-3 text-center">${escapeHtml(response.message || 'Error al carregar contrasenyes.')}</p>`);
                    }
                })
                .fail(xhr => $passListContainer.html(`<p class="text-danger small p-3 text-center">Error de connexió: ${escapeHtml(xhr.responseJSON?.message || 'Error')}</p>`));
        }

        // Cargar las listas solo cuando se muestra la pestaña
        const banListTabEl = document.getElementById('ban-list-tab');
        if (banListTabEl) {
            banListTabEl.addEventListener('shown.bs.tab', function (event) {
                loadBanLists();
            });
        }

        // Enviar formulario de banear email
        $(document).on('submit', '#add-ban-email-form', function(e) {
            e.preventDefault();
            const $form = $(this);
            const $btn = $form.find('button[type="submit"]');
            $btn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm"></span>');

            $.post('dashboard.php', 'ajax=true&action=add_banned_email&' + $form.serialize(), 'json')
                .done(res => showToast(res.message, res.status))
                .fail(err => showToast(err.responseJSON?.message || 'Error', 'danger'))
                .always(() => {
                    $form[0].reset();
                    $btn.prop('disabled', false).text('Banejar');
                    loadBanLists(); // Recargar la lista
                });
        });

        // Enviar formulario de prohibir contraseña
        $(document).on('submit', '#add-prohibited-pass-form', function(e) {
            e.preventDefault();
            const $form = $(this);
            const $btn = $form.find('button[type="submit"]');
            $btn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm"></span>');

            $.post('dashboard.php', 'ajax=true&action=add_prohibited_password&' + $form.serialize(), 'json')
                .done(res => showToast(res.message, res.status))
                .fail(err => showToast(err.responseJSON?.message || 'Error', 'danger'))
                .always(() => {
                    $form[0].reset();
                    $btn.prop('disabled', false).text('Prohibir');
                    loadBanLists(); // Recargar la lista
                });
        });

        // Eliminar un ítem (email o contraseña)
        $(document).on('click', '.remove-ban-btn', function() {
            // --- CORRECCIÓN DE SINTAXIS (APÓSTROFO) ---
            if (!confirm("Estàs segur que vols eliminar aquesta restricció?")) return;
            // --- FIN CORRECCIÓN ---

            const $btn = $(this);
            const id = $btn.data('id');
            const type = $btn.data('type');
            const action = (type === 'email') ? 'remove_banned_email' : 'remove_prohibited_password';

            $btn.prop('disabled', true);

            $.post('dashboard.php', { ajax: true, action: action, id: id }, 'json')
                .done(res => showToast(res.message, res.status))
                .fail(err => showToast(err.responseJSON?.message || 'Error', 'danger'))
                .always(() => loadBanLists()); // Recargar listas
        });
        // ======================================================= -->
        // ============ FIN: LÓGICA DE CONTROL D'ACCÉS ========= -->
        // ======================================================= -->

        // ======================================================= -->
            // ============ INICIO: LÓGICA DE CONFIGURACIÓN DE EMAIL ==== -->
            // ======================================================= -->

            // Cargar las configuraciones solo cuando se muestra la pestaña
            const emailSettingsTabEl = document.getElementById('email-settings-tab');
            if (emailSettingsTabEl) {
                emailSettingsTabEl.addEventListener('shown.bs.tab', function (event) {
                    loadEmailSettings();
                });
            }

            function loadEmailSettings() {
                            const $container = $('#email-settings-container');
                            $container.html('<p class="text-muted small p-3 text-center"><span class="spinner-border spinner-border-sm me-2"></span>Carregant configuracions...</p>');

                            $.getJSON('dashboard.php', { ajax: true, action: 'get_email_settings' })
                                .done(function(response) {
                                    if (response.status === 'success' && response.data) {
                                        $container.empty();
                                        if (response.data.length === 0) {
                                            $container.html('<p class="text-danger small p-3 text-center">No s\'ha trobat cap configuració a la BBDD.</p>');
                                            return;
                                        }

                                        // --- ★ INICIO DE LA CORRECCIÓN ★ ---
                                        // 1. Cambiamos el título
                                        let html = '<h6 class="text-muted"><b>Correus Crítics (Es recomana no desactivar)</b></h6><ul class="list-group mb-4">';
                                        let optionalHtml = '<h6 class="text-muted"><b>Correus Opcionals</b></h6><ul class="list-group">';

                                        // 2. Listas para separar
                                        let criticalItems = '';
                                        let optionalItems = '';

                                        response.data.forEach(item => {
                                            const settingName = escapeHtml(item.setting_name);
                                            const description = escapeHtml(item.description);
                                            const isEnabled = item.is_enabled == 1;

                                            // 3. Construir el HTML del interruptor (AHORA TODOS SON IGUALES)
                                            const itemHtml = `
                                                <li class="list-group-item d-flex justify-content-between align-items-center">
                                                    ${description}
                                                    <div class="form-check form-switch">
                                                        <input class="form-check-input email-setting-toggle" type="checkbox" role="switch" id="switch_${settingName}" name="${settingName}" value="1" ${isEnabled ? 'checked' : ''}>
                                                    </div>
                                                </li>
                                            `;

                                            // 4. Separar en las listas según el nombre (como en tu captura)
                                            if (settingName === 'new_user_admin' || settingName === 'new_user_register' || settingName === 'password_reset') {
                                                criticalItems += itemHtml;
                                            } else {
                                                optionalItems += itemHtml;
                                            }
                                        });

                                        html += criticalItems + '</ul>'; // Añadir lista de "críticos"
                                        html += optionalHtml + optionalItems + '</ul>'; // Añadir lista de "opcionales"

                                        $container.html(html);
                                        // --- ★ FIN DE LA CORRECCIÓN ★ ---

                                    } else {
                                        $container.html(`<p class="text-danger small p-3 text-center">${escapeHtml(response.message || 'Error al carregar configuracions.')}</p>`);
                                    }
                                })
                                .fail(xhr => $container.html(`<p class="text-danger small p-3 text-center">Error de connexió: ${escapeHtml(xhr.responseJSON?.message || 'Error')}</p>`));
                        }

            // Guardar configuración de emails
            $(document).on('submit', '#emailSettingsForm', function(e) {
                e.preventDefault();
                const $form = $(this);
                const $btn = $form.find('button[type="submit"]');
                $btn.prop('disabled', true).find('.spinner-border').removeClass('d-none');

                // Serializar solo los interruptores opcionales (no deshabilitados)
                const settingsData = $form.find('.email-setting-toggle').map(function() {
                    return { name: $(this).attr('name'), value: $(this).is(':checked') ? '1' : '0' };
                }).get();

                $.post('dashboard.php', { ajax: true, action: 'save_email_settings', settings: settingsData }, 'json')
                    .done(res => {
                        if(res.status === 'success') {
                            showToast(res.message, 'success');
                            adminModal.hide();
                        } else {
                            showToast(res.message, 'danger');
                        }
                    })
                    .fail(err => showToast(err.responseJSON?.message || 'Error', 'danger'))
                    .always(() => {
                        $btn.prop('disabled', false).find('.spinner-border').addClass('d-none');
                    });
            });
            // ======================================================= -->
            // ============ FIN: LÓGICA DE CONFIGURACIÓN DE EMAIL ====== -->
            // ======================================================= -->

    } // Fin del if (superadmin)
    // ★★★ FIN: LÓGICA MODAL ADMINISTRACIÓN (MODIFICADA) ★★★


    // ======================================================= -->
    // ========= LLAMADA AL CRON CENTRALIZADO (Global) ======== -->
    // ======================================================= -->
    function runSimulatedCron() {
        $.post('cron_tasks.php', { ajax: true })
            .done(function(response) {
                if(response.status === 'success') { console.log('Cron tasks executed:', response); }
            })
            .fail(function(err) { console.error('Centralized cron task failed to ping:', err); });
    }
    setTimeout(runSimulatedCron, 5000);
    // ======================================================= -->
    // ========== FIN: LLAMADA AL CRON CENTRALIZADO ========== -->
    // ======================================================= -->

}); // Fin document ready

// --- ★★★ FUNCIÓN escapeHtml MOVIDA (YA NO ESTÁ) ★★★ ---

</script>

<?php // Cargar Flatpickr y SortableJS SOLO en las páginas que los necesitan ?>
<?php if (basename($_SERVER['PHP_SELF']) === 'treatments.php' || basename($_SERVER['PHP_SELF']) === 'protocols.php' || basename($_SERVER['PHP_SELF']) === 'fitxa_pacient.php'): ?>
<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
<script src="https://npmcdn.com/flatpickr/dist/l10n/es.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sortablejs@latest/Sortable.min.js"></script>
<?php endif; ?>

<?php // Cargar Chart.js SOLO en las páginas que los necesitan ?>
<?php if (basename($_SERVER['PHP_SELF']) === 'fitxa_pacient.php' || basename($_SERVER['PHP_SELF']) === 'patient_dashboard.php' || basename($_SERVER['PHP_SELF']) === 'reports/smart_report.php'): ?>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-date-fns/dist/chartjs-adapter-date-fns.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-annotation@3.0.1/dist/chartjs-plugin-annotation.min.js"></script>
<?php endif; ?>


<div class="modal fade" id="blockingAnnouncementModal" tabindex="-1" aria-labelledby="blockingAnnouncementModalLabel" aria-hidden="true" data-bs-backdrop="static" data-bs-keyboard="false">
    <div class="modal-dialog modal-dialog-centered modal-lg">
        <div class="modal-content border-danger border-3">
            <div class="modal-header bg-danger text-white">
                <h5 class="modal-title" id="blockingAnnouncementModalLabel">
                    </h5>
                </div>
            <div class="modal-body" style="max-height: 60vh; overflow-y: auto;">
                <p>Cargando anuncio importante...</p>
            </div>
            <div class="modal-footer justify-content-center">
                <button type="button" class="btn btn-danger btn-lg" id="confirmReadBlockingAnnouncementBtn" data-anuncio-id="">
                    He llegit i entès
                </button>
            </div>
        </div>
    </div>
</div>

</body>
</html>
