<?php
// /announcements.php

// --- 1. GESTIÓN DE SESIÓN Y DEPENDENCIAS ---
session_start();
require_once 'db.php';

// PERMISO: Esta página es para Superadmin y Fisio
if (!isset($_SESSION['user_id']) || !in_array($_SESSION['user_rol'], ['superadmin', 'fisio'])) {
    // Si es una petición AJAX, denegar
    if (isset($_REQUEST['ajax'])) {
        http_response_code(403);
        echo json_encode(['status' => 'error', 'message' => 'Accés denegat.']);
        exit;
    }
    // Si es una carga de página, redirigir
    header('Location: dashboard.php');
    exit;
}

$user_id = $_SESSION['user_id'];
$is_ajax = isset($_REQUEST['ajax']);

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

    try {
        switch ($action) {

            // Carga la lista inicial de fisios y pacientes para los TomSelect
            case 'get_form_dependencies':
                $user_rol_ajax = $_SESSION['user_rol'];
                $user_id_ajax = $_SESSION['user_id'];
                $fisios = [];
                $pacientes = [];

                if ($user_rol_ajax === 'superadmin') {
                    $fisiosStmt = $db->query("SELECT id, nombre, apellido FROM cuentas WHERE rol = 'fisio' AND is_archived = 0 ORDER BY apellido, nombre");
                    $fisios = $fisiosStmt->fetchAll(PDO::FETCH_ASSOC);
                }

                if ($user_rol_ajax === 'superadmin') {
                    $pacientesStmt = $db->query("SELECT id, nombre, apellido FROM cuentas WHERE rol = 'paciente' AND is_archived = 0 ORDER BY apellido, nombre");
                    $pacientes = $pacientesStmt->fetchAll(PDO::FETCH_ASSOC);
                } else {
                    $pacientesStmt = $db->prepare("
                        SELECT DISTINCT c.id, c.nombre, c.apellido
                        FROM cuentas c
                        JOIN tratamientos t ON c.id = t.paciente_id
                        LEFT JOIN tratamiento_fisios_asignados tfa ON t.id = tfa.tratamiento_id
                        WHERE c.rol = 'paciente'
                          AND c.is_archived = 0
                          AND t.status = 'En curs'
                          AND (t.creator_fisio_id = :fisio_id OR tfa.fisio_id = :fisio_id)
                        ORDER BY c.apellido, c.nombre
                    ");
                    $pacientesStmt->execute([':fisio_id' => $user_id_ajax]);
                    $pacientes = $pacientesStmt->fetchAll(PDO::FETCH_ASSOC);
                }

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

            // Carga la tabla principal de anuncios
            case 'get_announcements_list':
                $user_rol_list = $_SESSION['user_rol'];
                $user_id_list = $_SESSION['user_id'];
                $filter_scope = $_GET['filter_scope'] ?? 'mine';

                // --- INICIO MODIFICACIÓN (Sort 2b) ---
                $sort_by_input = $_GET['sort_by'] ?? 'created_at';
                $sort_dir_input = $_GET['sort_dir'] ?? 'DESC';

                // Whitelist de columnas seguras para ordenar
                // AÑADIDO 'is_blocking' A LA LISTA
                $allowed_sort_columns = ['id', 'title', 'message_type', 'target_audience', 'start_date', 'end_date', 'is_active', 'created_at', 'is_blocking'];
                $sort_by = in_array($sort_by_input, $allowed_sort_columns) ? $sort_by_input : 'created_at';

                // Whitelist de direcciones
                $sort_dir = (strtoupper($sort_dir_input) === 'ASC') ? 'ASC' : 'DESC';

                // Casos especiales: Poner los NULLs al final si es ASC, al principio si es DESC
                if ($sort_by === 'start_date') {
                    $order_by_sql = ($sort_dir === 'ASC')
                        ? "CASE WHEN a.start_date IS NULL THEN 1 ELSE 0 END, a.start_date ASC"
                        : "CASE WHEN a.start_date IS NULL THEN 0 ELSE 1 END, a.start_date DESC";
                } else {
                    $order_by_sql = "a.$sort_by $sort_dir";
                }
                // --- FIN MODIFICACIÓN (Sort 2b) ---

                // Añadir c.rol para distinción visual
                $sql = "
                    SELECT a.*, c.nombre as creator_nombre, c.apellido as creator_apellido, c.rol as creator_rol
                    FROM anuncios a
                    LEFT JOIN cuentas c ON a.creator_id = c.id
                ";
                $params = [];

                if ($user_rol_list === 'fisio') {
                    $sql .= " WHERE a.creator_id = ?";
                    $params[] = $user_id_list;
                }
                else if ($user_rol_list === 'superadmin' && $filter_scope === 'mine') {
                    $sql .= " WHERE a.creator_id = ?";
                    $params[] = $user_id_list;
                }

                $sql .= " ORDER BY $order_by_sql"; // <-- LÍNEA MODIFICADA

                $stmt = $db->prepare($sql);
                $stmt->execute($params);
                echo json_encode(['status' => 'success', 'announcements' => $stmt->fetchAll(PDO::FETCH_ASSOC)]);
                break;

            // Carga los detalles de un anuncio para editarlo
            case 'get_announcement_details':
                $id = (int)($_GET['id'] ?? 0);
                if ($id === 0) throw new Exception('ID no vàlid.');

                $user_rol_details = $_SESSION['user_rol'];
                $user_id_details = $_SESSION['user_id'];

                $sql = "SELECT * FROM anuncios WHERE id = ?";
                $params = [$id];

                if ($user_rol_details === 'fisio') {
                    $sql .= " AND creator_id = ?";
                    $params[] = $user_id_details;
                }

                $stmt = $db->prepare($sql);
                $stmt->execute($params);
                $details = $stmt->fetch(PDO::FETCH_ASSOC);
                if (!$details) throw new Exception('Anunci no trobat o accés denegat.');

                $stmt_recipients = $db->prepare("SELECT user_id FROM anuncio_recipients WHERE anuncio_id = ?");
                $stmt_recipients->execute([$id]);
                $recipients = $stmt_recipients->fetchAll(PDO::FETCH_COLUMN);

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

            // Guarda un anuncio (Crea o Actualiza)
            case 'save_announcement':
                $db->beginTransaction();
                $user_rol_save = $_SESSION['user_rol'];
                $user_id_save = $_SESSION['user_id'];

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

                $title = $_POST['title'] ?? '';
                $content = $_POST['content'] ?? '';
                $message_type = $_POST['message_type'] ?? 'info';
                $target_audience_input = $_POST['target_audience'] ?? 'all_users';
                $target_audience_db = $target_audience_input;
                $is_active = (int)($_POST['is_active'] ?? 0);
                $start_date = !empty($_POST['start_date']) ? $_POST['start_date'] : null;
                $end_date = !empty($_POST['end_date']) ? $_POST['end_date'] : null;

                // --- INICIO MODIFICACIÓN BLOQUEO ---
                $is_blocking = 0;
                // Solo un superadmin puede crear un anuncio de bloqueo
                if ($user_rol_save === 'superadmin') {
                    $is_blocking = (int)($_POST['is_blocking'] ?? 0);
                }
                // --- FIN MODIFICACIÓN BLOQUEO ---


                if ($user_rol_save === 'fisio') {
                    $allowed_audiences = ['specific_pacientes', 'all_my_patients'];
                    if (!in_array($target_audience_input, $allowed_audiences)) {
                        throw new Exception('Accés denegat. Els fisios només poden enviar anuncis als seus pacients.');
                    }
                }


                if (empty($title) || empty($content)) {
                    throw new Exception('El títol i el contingut són obligatoris.');
                }

                if ($id > 0) { // Actualizar
                    $sql_update = "
                        UPDATE anuncios SET
                        title = ?, content = ?, message_type = ?, start_date = ?, end_date = ?,
                        target_audience = ?, is_active = ?, is_blocking = ?
                        WHERE id = ?
                    ";
                    // Añadido is_blocking al final
                    $params_update = [$title, $content, $message_type, $start_date, $end_date, $target_audience_db, $is_active, $is_blocking, $id];

                    if ($user_rol_save === 'fisio') {
                        $sql_update .= " AND creator_id = ?";
                        $params_update[] = $user_id_save;
                    }

                    $stmt = $db->prepare($sql_update);
                    $stmt->execute($params_update);

                    if ($user_rol_save === 'fisio' && $stmt->rowCount() === 0) {
                         throw new Exception('No s\'ha pogut actualitzar l\'anunci. O no existeix o no et pertany.');
                    }

                } else { // Crear
                    // [MYSQL CORREGIDO] datetime('now') -> NOW()
                    $stmt = $db->prepare("
                        INSERT INTO anuncios (title, content, message_type, start_date, end_date, target_audience, is_active, creator_id, created_at, is_blocking)
                        VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW(), ?)
                    ");
                    // Añadido is_blocking al final
                    $stmt->execute([$title, $content, $message_type, $start_date, $end_date, $target_audience_db, $is_active, $user_id_save, $is_blocking]);
                    $id = $db->lastInsertId();
                }

                // Gestionar destinatarios específicos (SIN CAMBIOS)
                $db->prepare("DELETE FROM anuncio_recipients WHERE anuncio_id = ?")->execute([$id]);
                $recipients_to_insert = [];

                // Determinar la lista de destinatarios A PARTIR DE CERO, incluso en edición
                $recipients_source = [];
                if ($target_audience_input === 'specific_fisios' && $user_rol_save === 'superadmin') {
                    $recipients_source = $_POST['specific_fisios'] ?? [];
                } else if ($target_audience_input === 'specific_pacientes') {
                    $recipients_source = $_POST['specific_pacientes'] ?? [];
                } else if ($target_audience_input === 'all_my_patients' && $user_rol_save === 'fisio') {
                    // SIEMPRE recalcular la lista completa de pacientes permitidos
                    $stmt_all_patients = $db->prepare("
                        SELECT DISTINCT c.id
                        FROM cuentas c
                        JOIN tratamientos t ON c.id = t.paciente_id
                        LEFT JOIN tratamiento_fisios_asignados tfa ON t.id = tfa.tratamiento_id
                        WHERE c.rol = 'paciente' AND c.is_archived = 0 AND t.status = 'En curs'
                          AND (t.creator_fisio_id = :fisio_id OR tfa.fisio_id = :fisio_id)
                    ");
                    $stmt_all_patients->execute([':fisio_id' => $user_id_save]);
                    $recipients_source = $stmt_all_patients->fetchAll(PDO::FETCH_COLUMN);
                }

                // Validar y filtrar destinatarios antes de insertar
                if (!empty($recipients_source)) {
                    if ($user_rol_save === 'superadmin') {
                        foreach ($recipients_source as $recipient_id) {
                            if (!empty($recipient_id) && is_numeric($recipient_id)) {
                                 $recipients_to_insert[] = (int)$recipient_id;
                            }
                        }
                    } else { // $user_rol_save === 'fisio'
                        // Re-obtener la lista de pacientes permitidos (por seguridad, aunque redundante si era all_my_patients)
                        $stmt_check = $db->prepare("
                            SELECT DISTINCT c.id FROM cuentas c
                            JOIN tratamientos t ON c.id = t.paciente_id
                            LEFT JOIN tratamiento_fisios_asignados tfa ON t.id = tfa.tratamiento_id
                            WHERE c.rol = 'paciente' AND c.is_archived = 0 AND t.status = 'En curs'
                              AND (t.creator_fisio_id = :fisio_id OR tfa.fisio_id = :fisio_id)
                        ");
                        $stmt_check->execute([':fisio_id' => $user_id_save]);
                        $allowed_patient_ids = $stmt_check->fetchAll(PDO::FETCH_COLUMN);
                        $allowed_set = array_flip($allowed_patient_ids);

                        foreach ($recipients_source as $recipient_id) {
                            if (!empty($recipient_id) && is_numeric($recipient_id) && isset($allowed_set[$recipient_id])) {
                                $recipients_to_insert[] = (int)$recipient_id;
                            } else {
                                if ($target_audience_input === 'specific_pacientes') { // Log solo si la selección fue manual e incorrecta
                                    error_log("ALERTA: Fisio $user_id_save ha intentat enviar un anunci al pacient no autoritzat $recipient_id. S'ha omès.");
                                }
                            }
                        }
                    }
                }

                // Insertar los destinatarios validados
                if (!empty($recipients_to_insert)) {
                    // [MYSQL CORREGIDO] Añadido IGNORE a la sintaxis de INSERT
                    $stmt_recipient = $db->prepare("INSERT IGNORE INTO anuncio_recipients (anuncio_id, user_id) VALUES (?, ?)");
                    foreach (array_unique($recipients_to_insert) as $valid_recipient_id) {
                         $stmt_recipient->execute([$id, $valid_recipient_id]);
                    }
                }


                $db->commit();
                echo json_encode(['status' => 'success', 'message' => 'Anunci guardat correctament.']);
                break;

             // Activa o desactiva un anuncio
            case 'toggle_active':
                $user_rol_toggle = $_SESSION['user_rol'];
                $user_id_toggle = $_SESSION['user_id'];
                $id = (int)$_POST['id'];

                $sql_toggle = "UPDATE anuncios SET is_active = 1 - is_active WHERE id = ?";
                $params_toggle = [$id];

                if ($user_rol_toggle === 'fisio') {
                    $sql_toggle .= " AND creator_id = ?";
                    $params_toggle[] = $user_id_toggle;
                }

                $stmt = $db->prepare($sql_toggle);
                $stmt->execute($params_toggle);

                if ($user_rol_toggle === 'fisio' && $stmt->rowCount() === 0) {
                     throw new Exception('No s\'ha pogut actualitzar l\'estat. O no existeix o no et pertany.');
                }

                echo json_encode(['status' => 'success', 'message' => 'Estat actualitzat.']);
                break;

            // Reenvía un anuncio (borrando los "vistos")
            case 'resend_announcement':
                $user_rol_resend = $_SESSION['user_rol'];
                $user_id_resend = $_SESSION['user_id'];
                $id = (int)$_POST['id'];

                if ($user_rol_resend === 'fisio') {
                    $stmt_check = $db->prepare("SELECT 1 FROM anuncios WHERE id = ? AND creator_id = ?");
                    $stmt_check->execute([$id, $user_id_resend]);
                    if (!$stmt_check->fetch()) {
                        throw new Exception('Accés denegat. Aquest anunci no et pertany.');
                    }
                }

                $stmt = $db->prepare("DELETE FROM anuncio_vistos WHERE anuncio_id = ?");
                $stmt->execute([$id]);
                $count = $stmt->rowCount();
                echo json_encode(['status' => 'success', 'message' => "Anunci reenviat. Es mostrarà de nou a $count usuaris."]);
                break;

            // Elimina un anuncio
            case 'delete_announcement':
                $user_rol_delete = $_SESSION['user_rol'];
                $user_id_delete = $_SESSION['user_id'];
                $id = (int)$_POST['id'];

                $sql_delete = "DELETE FROM anuncios WHERE id = ?";
                $params_delete = [$id];

                if ($user_rol_delete === 'fisio') {
                    $sql_delete .= " AND creator_id = ?";
                    $params_delete[] = $user_id_delete;
                }

                $stmt = $db->prepare($sql_delete);
                $stmt->execute($params_delete);

                if ($user_rol_delete === 'fisio' && $stmt->rowCount() === 0) {
                     throw new Exception('No s\'ha pogut eliminar. O no existeix o no et pertany.');
                }

                echo json_encode(['status' => 'success', 'message' => 'Anunci eliminat permanentment.']);
                break;


            default:
                throw new Exception('Acció AJAX no vàlida.');
        }
    } catch (Exception $e) {
        if ($db->inTransaction()) $db->rollBack();
        http_response_code(400); // Usar 400 para errores de lógica/datos
        error_log("Error AJAX en announcements.php: " . $e->getMessage());
        echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
    }
    exit;
}

// --- 3. CARGA DE PÁGINA HTML ---
$page_title = "Gestió d'Anuncis";
$user_rol_html = $_SESSION['user_rol'];

// [MYSQL CORREGIDO] INICIO: LÓGICA DE URL BASE DINÁMICA
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
$domain_root = $protocol . $_SERVER['HTTP_HOST'];
$app_base_url = rtrim($domain_root . dirname($_SERVER['SCRIPT_NAME']), '/') . '/';
// --- FIN: LÓGICA DE URL BASE DINÁMICA ---

include 'partials/header.php';
?>

<link href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/tom-select@2.3.1/dist/css/tom-select.bootstrap5.css" rel="stylesheet">
<style>
    .audience-tag {
        font-size: 0.75rem;
        font-weight: 600;
        padding: 0.25em 0.6em;
        border-radius: 1em;
        letter-spacing: 0.5px;
    }
    .ts-control .remove-button {
        color: #fff !important;
        background-color: var(--bs-primary) !important;
    }
    #specific-recipients-container {
        display: none; /* Oculto por defecto */
    }
    .table-actions {
        white-space: nowrap;
    }
    /* Estilo para el icono del creador */
    .creator-icon {
        font-size: 0.9em;
        margin-right: 4px;
        vertical-align: baseline;
    }
    /* INICIO MODIFICACIÓN: Estilos para ordenación */
    .sortable-header {
        cursor: pointer;
        user-select: none;
        white-space: nowrap; /* <-- ★★★ AQUÍ ESTÁ LA CORRECCIÓN ★★★ */
    }
    .sortable-header:hover {
        background-color: #f8f9fa;
    }
    .sortable-header .sort-icon {
        font-size: 0.8em;
        color: #999;
        vertical-align: middle;
        margin-left: 4px;
    }
    .sortable-header.sort-asc .sort-icon,
    .sortable-header.sort-desc .sort-icon {
        color: var(--bs-primary);
    }
    /* FIN MODIFICACIÓN */
</style>

<main class="main-content container mt-4" style="max-width: 1420px;">

    <div class="d-flex justify-content-between align-items-center mb-4">
        <h4><i class="bi bi-megaphone me-2"></i> <?= $page_title ?></h4>
        <div class="d-flex align-items-center">
            <?php if ($user_rol_html === 'superadmin'): ?>
            <div class="me-3">
                <label for="announcement-scope-filter" class="form-label mb-0 me-1 small">Veure:</label>
                <select class="form-select form-select-sm d-inline-block" id="announcement-scope-filter" style="width: auto;">
                    <option value="mine" selected>Només els meus</option>
                    <option value="all">Tots (Inclosos Fisios)</option>
                </select>
            </div>
            <?php endif; ?>

            <button class="btn btn-primary" id="new-announcement-btn">
                <i class="bi bi-plus-circle me-2"></i> Nou Anunci
            </button>
        </div>
    </div>


    <div class="card shadow-sm">
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-hover align-middle">
                    <thead class="table-light">
                        <tr>
                            <th style="width: 5%;" class="sortable-header" data-sort="is_active">Estat <i class="bi bi-arrow-down-up sort-icon"></i></th>
                            <th style="width: 25%;" class="sortable-header" data-sort="title">Títol <i class="bi bi-arrow-down-up sort-icon"></i></th>
                            <th style="width: 10%;" class="sortable-header" data-sort="message_type">Tipus <i class="bi bi-arrow-down-up sort-icon"></i></th>
                            <th style="width: 5%;" class="sortable-header" data-sort="is_blocking">Bloq. <i class="bi bi-arrow-down-up sort-icon"></i></th>
                            <th style="width: 15%;" class="sortable-header" data-sort="target_audience">Audiència <i class="bi bi-arrow-down-up sort-icon"></i></th>
                            <th style="width: 15%;" class="sortable-header" data-sort="start_date">Visibilitat <i class="bi bi-arrow-down-up sort-icon"></i></th>
                            <th style="width: 15%;" class="sortable-header" data-sort="created_at">Creació <i class="bi bi-arrow-down-up sort-icon"></i></th>
                            <th class="text-end" style="width: 10%;">Accions</th>
                        </tr>
                    </thead>
                    <tbody id="announcements-list-container">
                        </tbody>
                </table>
            </div>
        </div>
    </div>
</main>

<div class="modal fade" id="announcementModal" tabindex="-1">
    <div class="modal-dialog modal-lg modal-dialog-scrollable">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="announcementModalLabel">Nou Anunci</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="announcementForm">
                    <input type="hidden" name="id" id="announcementId">
                    <input type="hidden" name="is_active" id="isActiveInput" value="0">
                    <input type="hidden" name="is_blocking" id="isBlockingInput" value="0">
                    <div class="mb-3">
                        <label for="announcementTitle" class="form-label">Títol <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="announcementTitle" name="title" required>
                    </div>

                    <div class="mb-3">
                        <label for="announcementContent" class="form-label">Contingut del Missatge <span class="text-danger">*</span></label>
                        <textarea class="form-control" id="announcementContent" name="content" rows="5" required></textarea>
                    </div>

                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label for="messageTypeSelect" class="form-label">Tipus d'Avís</label>
                            <select class="form-select" id="messageTypeSelect" name="message_type">
                                <option value="info">Informació (Blau)</option>
                                <option value="warning">Avís (Groc)</option>
                                <option value="danger">Important (Roig)</option>
                            </select>
                        </div>

                        <div class="col-md-6 mb-3">
                            <label for="targetAudienceSelect" class="form-label">Audiència</label>
                            <select class="form-select" id="targetAudienceSelect" name="target_audience">
                                <?php if ($user_rol_html === 'superadmin'): ?>
                                    <option value="all_users">Tots els Usuaris</option>
                                    <option value="all_fisios">Tots els Fisios</option>
                                    <option value="all_pacientes">Tots els Pacients</option>
                                    <option value="specific_fisios">Fisios Específics</option>
                                <?php endif; ?>
                                <?php if ($user_rol_html === 'fisio'): ?>
                                    <option value="all_my_patients">Tots els meus pacients</option>
                                <?php endif; ?>
                                <option value="specific_pacientes">Pacients Específics</option>
                            </select>
                        </div>
                    </div>

                    <div id="specific-recipients-container" class="mb-3">
                        <?php if ($user_rol_html === 'superadmin'): ?>
                        <div id="fisios-select-wrapper">
                            <label class="form-label">Selecciona Fisios</label>
                            <select id="specificFisiosSelect" name="specific_fisios[]" multiple></select>
                        </div>
                        <?php endif; ?>

                        <div id="pacientes-select-wrapper">
                            <label class="form-label">Selecciona Pacients</label>
                            <select id="specificPacientesSelect" name="specific_pacientes[]" multiple></select>
                        </div>
                    </div>


                    <div class="mb-3">
                        <label for="dateRangePicker" class="form-label">Rang de Visibilitat (Inici - Fi)</label>
                        <div class="input-group">
                             <span class="input-group-text"><i class="bi bi-calendar-range"></i></span>
                            <input type="text" id="dateRangePicker" class="form-control" placeholder="Opcional: Selecciona un rang de dates...">
                            <input type="hidden" name="start_date" id="startDateHidden">
                            <input type="hidden" name="end_date" id="endDateHidden">
                        </div>
                        <div class="form-check mt-2">
                            <input class="form-check-input" type="checkbox" name="end_date_na" id="endDateNA">
                            <label class="form-check-label" for="endDateNA">
                                Sense data de caducitat
                            </label>
                        </div>
                    </div>

                    <?php if ($user_rol_html === 'superadmin'): ?>
                    <div class="mb-3 border-top pt-3 mt-4">
                         <div class="form-check form-switch form-check-danger">
                           <input class="form-check-input" type="checkbox" role="switch" id="announcementIsBlocking">
                           <label class="form-check-label fw-bold text-danger" for="announcementIsBlocking">
                               <i class="bi bi-lock-fill me-1 text-dark"></i> Requerir lectura (Bloquejar pantalla)
                           </label>
                           <div class="form-text text-danger mt-1">
                               Si s'activa, aquest anunci apareixerà en un modal que bloqueja l'aplicació fins que l'usuari el llegeixi.
                           </div>
                         </div>
                    </div>
                    <?php endif; ?>
                    </form>
            </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-outline-primary" id="saveAsDraftBtn">Guardar Esborrany</button>
                <button type="button" class="btn btn-primary" id="saveAsPublicBtn">Publicar Anunci</button>
            </div>
        </div>
    </div>
</div>

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

<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
<script src="https://cdn.jsdelivr.net/npm/flatpickr/dist/l10n/es.js"></script>
<script src="https://cdn.jsdelivr.net/npm/tom-select@2.3.1/dist/js/tom-select.complete.min.js"></script>

<script>
$(document).ready(function() {

    // --- Variables Globales ---
    const announcementModal = new bootstrap.Modal('#announcementModal');
    let tsFisios, tsPacientes, datePicker;
    const userRoleJS = '<?php echo $user_rol_html; ?>';
    const userIdJS = <?php echo $user_id; ?>;
    // [MYSQL CORREGIDO] Nueva URL base dinámica
    const APP_BASE_URL = "<?php echo $app_base_url; ?>";

    // INICIO MODIFICACIÓN: Variables de estado de ordenación
    let currentSortColumn = 'created_at';
    let currentSortDirection = 'DESC';
    // FIN MODIFICACIÓN


    // --- Inicializadores ---

    function initializeTomSelects() {
        if (tsFisios) tsFisios.destroy();
        if (tsPacientes) tsPacientes.destroy();

        if ($('#specificFisiosSelect').length > 0) {
            tsFisios = new TomSelect('#specificFisiosSelect', {
                plugins: ['remove_button'], placeholder: 'Cerca fisios...',
                valueField: 'id', labelField: 'text', searchField: 'text'
            });
        } else { tsFisios = null; }

        if ($('#specificPacientesSelect').length > 0) { // Check if element exists
             tsPacientes = new TomSelect('#specificPacientesSelect', {
                plugins: ['remove_button'], placeholder: 'Cerca pacients...',
                valueField: 'id', labelField: 'text', searchField: 'text'
            });
        } else { tsPacientes = null; } // Assign null if not found
    }

    function initializeDatePicker() {
        datePicker = flatpickr("#dateRangePicker", {
            mode: 'range', dateFormat: "Y-m-d", locale: "es",
            altInput: true, altFormat: "d F, Y",
            onChange: function(selectedDates, dateStr, instance) {
                if (selectedDates.length === 2) {
                    $('#startDateHidden').val(instance.formatDate(selectedDates[0], "Y-m-d"));
                    $('#endDateHidden').val(instance.formatDate(selectedDates[1], "Y-m-d"));
                    $('#endDateNA').prop('checked', false);
                } else if (selectedDates.length === 1) {
                     $('#startDateHidden').val(instance.formatDate(selectedDates[0], "Y-m-d"));
                     if(!$('#endDateNA').is(':checked')) { $('#endDateHidden').val(''); }
                } else {
                    $('#startDateHidden').val(''); $('#endDateHidden').val('');
                }
            }
        });
    }


    function loadFormDependencies() {
        // [MYSQL CORREGIDO] Usar APP_BASE_URL
        $.getJSON(APP_BASE_URL + 'announcements.php', { ajax: true, action: 'get_form_dependencies' })
            .done(response => {
                if (response.status === 'success') {
                    if (tsFisios && response.fisios && response.fisios.length > 0) {
                        const fisioOptions = response.fisios.map(f => ({ id: f.id, text: `${f.apellido}, ${f.nombre}` }));
                        tsFisios.addOptions(fisioOptions);
                    }
                    if (tsPacientes && response.pacientes) {
                        const pacientOptions = response.pacientes.map(p => ({ id: p.id, text: `${p.apellido}, ${p.nombre}` }));
                        tsPacientes.clearOptions(); // Ensure clean slate
                        tsPacientes.addOptions(pacientOptions);
                    }
                }
            })
            .fail(() => showToast('Error carregant llistes de destinataris.', 'danger'));
    }

    // --- Lógica Principal ---

    // INICIO MODIFICACIÓN: Carga con ordenación
    function loadAnnouncements() {
        const container = $('#announcements-list-container');
        const scope = $('#announcement-scope-filter').val() || 'mine';

        // Colspan actualizado a 8 (por la nueva columna)
        container.html('<tr><td colspan="8" class="text-center p-5"><div class="spinner-border text-primary"></div></td></tr>');

        // [MYSQL CORREGIDO] Usar APP_BASE_URL
        $.getJSON(APP_BASE_URL + 'announcements.php', {
            ajax: true,
            action: 'get_announcements_list',
            filter_scope: scope,
            sort_by: currentSortColumn, // <-- AÑADIDO
            sort_dir: currentSortDirection // <-- AÑADIDO
        })
            .done(response => {
                container.empty();
                if (response.status === 'success' && response.announcements.length > 0) {
                    response.announcements.forEach(a => {
                        container.append(renderAnnouncementRow(a));
                    });
                } else {
                    // Colspan actualizado a 8
                    container.html('<tr><td colspan="8" class="text-center p-5 text-muted">No s\'han trobat anuncis.</td></tr>');
                }
                updateSortIcons(); // <-- AÑADIDO
                $('[data-bs-toggle="tooltip"]').tooltip('dispose').tooltip();
            })
            .fail(() => {
                // Colspan actualizado a 8
                container.html('<tr><td colspan="8" class="alert alert-danger">Error carregant els anuncis.</td></tr>');
            });
    }
    // FIN MODIFICACIÓN

    // INICIO MODIFICACIÓN: Renderizado de fila con fecha de creación
    function renderAnnouncementRow(a) {
        const isActive = a.is_active == 1;
        const statusBadge = isActive ? `<span class="badge bg-success">Actiu</span>` : `<span class="badge bg-secondary">Esborrany</span>`;

        let typeBadge;
        switch(a.message_type) {
            case 'danger': typeBadge = `<span class="badge bg-danger">Important</span>`; break;
            case 'warning': typeBadge = `<span class="badge bg-warning text-dark">Avís</span>`; break;
            default: typeBadge = `<span class="badge bg-info">Informació</span>`; break;
        }

        // --- **** INICIO MODIFICACIÓN ESTÉTICA 3 **** ---
        // Se reemplaza el badge rojo por un icono simple
        const blockingIcon = a.is_blocking == 1
            ? `<span data-bs-toggle="tooltip" title="Bloquejant"><i class="bi bi-lock-fill text-dark"></i></span>`
            : `<span data-bs-toggle="tooltip" title="Normal"><i class="bi bi-unlock-fill text-muted"></i></span>`;
        // --- **** FIN MODIFICACIÓN ESTÉTICA 3 **** ---

        let audienceHtml;
        switch(a.target_audience) {
            case 'all_users': audienceHtml = `<span class="audience-tag bg-primary text-white">Tots Usuaris</span>`; break;
            case 'all_fisios': audienceHtml = `<span class="audience-tag bg-success text-white">Tots Fisios</span>`; break;
            case 'all_pacientes': audienceHtml = `<span class="audience-tag bg-info text-dark">Tots Pacients</span>`; break;
            case 'all_my_patients': audienceHtml = `<span class="audience-tag bg-primary-subtle text-primary-emphasis">Tots els meus pacients</span>`; break;
            case 'specific_fisios': audienceHtml = `<span class="audience-tag bg-success-subtle text-success-emphasis">Fisios Espec.</span>`; break;
            case 'specific_pacientes': audienceHtml = `<span class="audience-tag bg-info-subtle text-info-emphasis">Pacients Espec.</span>`; break;
            default: audienceHtml = a.target_audience;
        }

        let visibility = '';
        let startDateFormatted = a.start_date ? new Date(a.start_date+'T12:00:00').toLocaleDateString('ca-ES') : null;
        let endDateFormatted = a.end_date ? new Date(a.end_date+'T12:00:00').toLocaleDateString('ca-ES') : null;
        if (startDateFormatted && endDateFormatted) visibility = `Del ${startDateFormatted} al ${endDateFormatted}`;
        else if (startDateFormatted) visibility = `Des del ${startDateFormatted}`;
        else if (endDateFormatted) visibility = `Fins al ${endDateFormatted}`;
        else visibility = 'Permanent';

        // --- INICIO MODIFICACIÓN (Req 2a) ---
        // Formatear fecha creación. Asume UTC (por 'datetime("now")' de SQLite)
        let createdDateFormatted = 'N/A';
        if (a.created_at) {
            try {
                // [MYSQL CORREGIDO] MySQL devuelve 'YYYY-MM-DD HH:MM:SS', que JS parsea correctamente (como local)
                // Ya no añadimos 'Z'
                const dateObj = new Date(a.created_at);
                if (!isNaN(dateObj)) {
                    createdDateFormatted = dateObj.toLocaleString('ca-ES', {
                        day: '2-digit',
                        month: '2-digit',
                        year: 'numeric',
                        hour: '2-digit',
                        minute: '2-digit'
                    }).replace(',', ''); // Quitar coma
                }
            } catch(e) { console.warn("Error parsing created_at date", a.created_at); }
        }
        // --- FIN MODIFICACIÓN (Req 2a) ---

        // Creador
        let creatorIcon = '';
        let creatorName = ((a.creator_nombre || '') + ' ' + (a.creator_apellido || 'Sistema')).trim();
        let isMine = (a.creator_id == userIdJS);

        if (a.creator_rol === 'superadmin') {
            creatorIcon = '<i class="bi bi-person-workspace text-primary creator-icon" title="Superadmin"></i>';
        } else if (a.creator_rol === 'fisio') {
            creatorIcon = '<i class="bi bi-person-fill text-secondary creator-icon" title="Fisio"></i>';
        } else {
             creatorIcon = '<i class="bi bi-person-slash text-muted creator-icon" title="Desconegut"></i>';
        }
        let creatorHtml = `<br><small class="text-muted">${creatorIcon}${escapeHtml(creatorName)}${isMine ? ' <em class="fst-italic">(Meu)</em>' : ''}</small>`;

        // Lógica Botones
        const editBtn = `<button class="btn btn-sm btn-outline-primary edit-btn" data-id="${a.id}" title="Editar"><i class="bi bi-pencil"></i></button>`;
        let actionButtonsHtml = '';
        if (isActive) {
            const detepBtn = `<button class="btn btn-sm btn-outline-secondary toggle-active-btn" data-id="${a.id}" title="Desactivar (Aturar)"><i class="bi bi-pause-fill"></i></button>`;
            const resendBtn = `<button class="btn btn-sm btn-outline-info resend-btn" data-id="${a.id}" title="Reenviar (Tornar a mostrar a tots)"><i class="bi bi-send-check"></i></button>`;
            actionButtonsHtml = `${detepBtn} ${resendBtn} ${editBtn}`;
        } else {
            const activarBtn = `<button class="btn btn-sm btn-outline-success toggle-active-btn" data-id="${a.id}" title="Activar (Publicar)"><i class="bi bi-play-fill"></i></button>`;
            const deleteBtn = `<button class="btn btn-sm btn-outline-danger delete-btn" data-id="${a.id}" data-title="${escapeHtml(a.title)}" title="Eliminar"><i class="bi bi-trash"></i></button>`;
            actionButtonsHtml = `${activarBtn} ${editBtn} ${deleteBtn}`;
        }

        return `
            <tr>
                <td>${statusBadge}</td>
                <td><strong>${escapeHtml(a.title)}</strong>${creatorHtml}</td>
                <td>${typeBadge}</td>
                <td>${blockingIcon}</td>
                <td>${audienceHtml}</td>
                <td class="small">${visibility}</td>
                <td class="small">${createdDateFormatted}</td> <td class="text-end table-actions">
                    <div class="btn-group">
                        ${actionButtonsHtml}
                    </div>
                </td>
            </tr>
        `;
    }
    // FIN MODIFICACIÓN

    // INICIO MODIFICACIÓN: Checkbox por defecto y leer 'is_blocking'
    function populateAndOpenModal(data = null) {
        const form = $('#announcementForm');
        form[0].reset();

        if (tsFisios) tsFisios.clear();
        if (tsPacientes) tsPacientes.clear();
        if (tsFisios) tsFisios.disable();
        if (tsPacientes) tsPacientes.disable();

        datePicker.clear();
        $('#startDateHidden').val('');
        $('#endDateHidden').val('');
        $('#endDateNA').prop('checked', false).trigger('change');
        $('#specific-recipients-container').hide();

        // --- INICIO MODIFICACIÓN: Resetear checkbox bloqueo ---
        $('#announcementIsBlocking').prop('checked', false);
        $('#isBlockingInput').val(0);
        // --- FIN MODIFICACIÓN ---

        if (data && data.details) { // Modo Editar
            $('#announcementModalLabel').text("Editar Anunci");
            $('#announcementId').val(data.details.id);
            $('#announcementTitle').val(data.details.title);
            $('#announcementContent').val(data.details.content);
            $('#messageTypeSelect').val(data.details.message_type);

            // --- INICIO MODIFICACIÓN: Setear checkbox bloqueo ---
            if (data.details.is_blocking && data.details.is_blocking == 1) {
                $('#announcementIsBlocking').prop('checked', true);
                $('#isBlockingInput').val(1);
            }
            // --- FIN MODIFICACIÓN ---

            let audienceToSet = data.details.target_audience;

            $('#targetAudienceSelect').val(audienceToSet);
            $('#targetAudienceSelect').trigger('change'); // Trigger AFTER setting value

            if (data.details.start_date || data.details.end_date) {
                const dates = [];
                if(data.details.start_date) dates.push(data.details.start_date);
                if(data.details.end_date) {
                    dates.push(data.details.end_date);
                    $('#endDateNA').prop('checked', false);
                } else if (data.details.start_date) {
                    $('#endDateNA').prop('checked', true);
                }
                datePicker.setDate(dates, true);
                $('#startDateHidden').val(data.details.start_date || '');
                $('#endDateHidden').val(data.details.end_date || '');
            } else {
                $('#endDateNA').prop('checked', true);
            }
             $('#endDateNA').trigger('change');

            const recipientsArray = Array.isArray(data.recipients) ? data.recipients.map(String) : [];
            if (audienceToSet === 'specific_fisios') {
                if (tsFisios) tsFisios.setValue(recipientsArray);
            } else if (audienceToSet === 'specific_pacientes') {
                 if (tsPacientes) tsPacientes.setValue(recipientsArray);
            }

        } else { // Modo Nuevo
            $('#announcementModalLabel').text("Nou Anunci");
            $('#announcementId').val('');
            if (userRoleJS === 'fisio') {
                $('#targetAudienceSelect').val('all_my_patients').trigger('change');
            } else {
                $('#targetAudienceSelect').val('all_users').trigger('change');
            }

            // --- INICIO MODIFICACIÓN (Req 3b) ---
            $('#endDateNA').prop('checked', true).trigger('change'); // <-- LÍNEA MODIFICADA
            // --- FIN MODIFICACIÓN (Req 3b) ---
        }

        announcementModal.show();
    }
    // FIN MODIFICACIÓN


    // [MYSQL CORREGIDO] Función escapeHtml eliminada
    // function escapeHtml(str) { ... }


    // INICIO MODIFICACIÓN: Nuevas funciones y handlers para ordenación
    /**
     * Actualiza los iconos de las cabeceras de la tabla
     * para reflejar el estado de ordenación actual.
     */
    function updateSortIcons() {
        // Resetear todos los iconos
        $('.sortable-header').removeClass('sort-asc sort-desc');
        $('.sortable-header .sort-icon').attr('class', 'bi bi-arrow-down-up sort-icon');

        // Aplicar clase e icono activo
        const $currentHeader = $(`.sortable-header[data-sort="${currentSortColumn}"]`);
        if ($currentHeader.length > 0) {
            const directionClass = (currentSortDirection === 'ASC') ? 'sort-asc' : 'sort-desc';
            const iconClass = (currentSortDirection === 'ASC') ? 'bi bi-sort-up' : 'bi bi-sort-down';
            $currentHeader.addClass(directionClass);
            $currentHeader.find('.sort-icon').attr('class', `${iconClass} sort-icon`);
        }
    }

    // --- Handlers de Eventos ---

    /**
     * Handler para click en cabeceras de tabla ordenables
     */
    $(document).on('click', '.sortable-header', function() {
        const newSortColumn = $(this).data('sort');
        if (!newSortColumn) return;

        if (currentSortColumn === newSortColumn) {
            // Invertir dirección
            currentSortDirection = (currentSortDirection === 'ASC') ? 'DESC' : 'ASC';
        } else {
            // Nueva columna, dirección por defecto
            currentSortColumn = newSortColumn;
            // Fechas por defecto DESC, resto ASC
            currentSortDirection = (newSortColumn === 'created_at' || newSortColumn === 'start_date') ? 'DESC' : 'ASC';
        }

        loadAnnouncements(); // Recargar la tabla con la nueva ordenación
    });
    // FIN MODIFICACIÓN


    $('#new-announcement-btn').on('click', function() {
        populateAndOpenModal(null);
    });

    $(document).on('click', '.edit-btn', function() {
        const id = $(this).data('id');
        // [MYSQL CORREGIDO] Usar APP_BASE_URL
        $.getJSON(APP_BASE_URL + 'announcements.php', { ajax: true, action: 'get_announcement_details', id: id })
            .done(response => {
                if (response.status === 'success') {
                    populateAndOpenModal(response);
                } else { showToast(response.message, 'danger'); }
            })
            .fail(() => showToast('Error carregant dades.', 'danger'));
    });

    $('#saveAsDraftBtn').on('click', function() {
        $('#isActiveInput').val(0); $('#announcementForm').trigger('submit');
    });
    $('#saveAsPublicBtn').on('click', function() {
        $('#isActiveInput').val(1); $('#announcementForm').trigger('submit');
    });

    // INICIO MODIFICACIÓN: Handler de submit con validación HTML5
    $('#announcementForm').on('submit', function(e) {

        // --- INICIO MODIFICACIÓN (Req 3a) ---
        // Validar el formulario HTML5 ANTES de prevenir el default
        if (!this.checkValidity()) {
            // Si no es válido, mostrar los mensajes de error del navegador
            this.reportValidity();
            // Detener la ejecución, no enviar AJAX
            e.preventDefault(); // Prevenir recarga de página
            return;
        }
        // --- FIN MODIFICACIÓN (Req 3a) ---

        e.preventDefault(); // Prevenir envío normal
        const $btn = $('#isActiveInput').val() == 1 ? $('#saveAsPublicBtn') : $('#saveAsDraftBtn');
        const btnHtml = $btn.html();
        $btn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm"></span> Guardant...');

        const formData = new FormData(this);
        formData.append('ajax', 'true');
        formData.append('action', 'save_announcement');

        // --- INICIO MODIFICACIÓN: Añadir valor de is_blocking ---
        // El input oculto 'isBlockingInput' ya está en el form,
        // pero lo actualizamos desde el checkbox por si acaso
        const isBlockingVal = $('#announcementIsBlocking').is(':checked') ? 1 : 0;
        formData.set('is_blocking', isBlockingVal);
        // --- FIN MODIFICACIÓN ---

        const audience = $('#targetAudienceSelect').val();
        // Remove data from selects that shouldn't be sent based on audience
        if (audience !== 'specific_fisios') formData.delete('specific_fisios[]');
        if (audience !== 'specific_pacientes' && audience !== 'all_my_patients') formData.delete('specific_pacientes[]');
        // Ensure end_date is empty if NA is checked
         if ($('#endDateNA').is(':checked')) {
             if (formData.has('end_date')) formData.set('end_date', '');
         }

        // [MYSQL CORREGIDO] Usar APP_BASE_URL
        $.ajax({ url: APP_BASE_URL + 'announcements.php', type: 'POST', data: formData, processData: false, contentType: false, dataType: 'json' })
        .done(response => {
            if (response.status === 'success') {
                showToast(response.message, 'success');
                announcementModal.hide();
                loadAnnouncements(); // Reload the table
            } else { showToast(response.message || 'Error desconegut.', 'danger'); }
        })
        .fail(xhr => showToast(xhr.responseJSON?.message || 'Error de connexió.', 'danger'))
        .always(() => $btn.prop('disabled', false).html(btnHtml));
    });
    // FIN MODIFICACIÓN


    $('#targetAudienceSelect').on('change', function() {
        const selection = $(this).val();
        const container = $('#specific-recipients-container');
        const fisiosWrapper = $('#fisios-select-wrapper');
        const pacientesWrapper = $('#pacientes-select-wrapper');

        if (tsFisios) tsFisios.disable();
        if (tsPacientes) tsPacientes.disable();

        if (selection === 'specific_fisios') {
            container.slideDown(200);
            if (fisiosWrapper.length > 0) fisiosWrapper.show();
            if (tsFisios) tsFisios.enable();
            if (pacientesWrapper.length > 0) pacientesWrapper.hide();
        } else if (selection === 'specific_pacientes') {
            container.slideDown(200);
            if (fisiosWrapper.length > 0) fisiosWrapper.hide();
            if (pacientesWrapper.length > 0) pacientesWrapper.show();
            if (tsPacientes) tsPacientes.enable();
        } else if (selection === 'all_my_patients') {
            if (fisiosWrapper.length > 0) fisiosWrapper.hide();
            if (pacientesWrapper.length > 0) pacientesWrapper.hide(); // Hide selector, not needed
            container.slideUp(200); // Alternative: Hide the whole section
        } else {
            container.slideUp(200);
        }
    });


    $('#endDateNA').on('change', function() {
        if (!datePicker) return;
        if (this.checked) {
             $('#endDateHidden').val('');
             if (datePicker.selectedDates.length > 0) datePicker.setDate(datePicker.selectedDates[0], true);
             // Deshabilitar la parte 'end' del rango
             $(datePicker.calendarContainer).find('.flatpickr-day.endRange').removeClass('endRange');
             $(datePicker.calendarContainer).find('.flatpickr-day.startRange').addClass('selected');
        } else {
            // Habilitar modo rango normal
            if (datePicker.selectedDates.length === 1) {
                // Forzar a que se abra esperando el segundo click
                datePicker.open();
            }
        }
    });

    // --- INICIO MODIFICACIÓN: Settear valor del input oculto de bloqueo ---
    $('#announcementIsBlocking').on('change', function() {
        $('#isBlockingInput').val(this.checked ? 1 : 0);
    });
    // --- FIN MODIFICACIÓN ---


    // --- Acciones rápidas de la tabla ---
    $(document).on('click', '.toggle-active-btn', function() {
        const id = $(this).data('id');
        // [MYSQL CORREGIDO] Usar APP_BASE_URL
        $.post(APP_BASE_URL + 'announcements.php', { ajax: true, action: 'toggle_active', id: id }, 'json')
            .done(res => { showToast(res.message, 'success'); loadAnnouncements(); })
            .fail(xhr => showToast(xhr.responseJSON?.message || 'Error desconegut.', 'danger'));
    });
    $(document).on('click', '.resend-btn', function() {
        const id = $(this).data('id');
        if (confirm("Vas a reenviar l'anunci actual de nou a tots. Vols continuar?")) {
            // [MYSQL CORREGIDO] Usar APP_BASE_URL
            $.post(APP_BASE_URL + 'announcements.php', { ajax: true, action: 'resend_announcement', id: id }, 'json')
                .done(res => { showToast(res.message, 'success'); })
                .fail(xhr => showToast(xhr.responseJSON?.message || 'Error desconegut.', 'danger'));
        }
    });
    $(document).on('click', '.delete-btn', function() {
        const id = $(this).data('id');
        const title = $(this).data('title');
        if (confirm(`Vas a eliminar permanentment: "${title}". Vols continuar?`)) {
            // [MYSQL CORREGIDO] Usar APP_BASE_URL
            $.post(APP_BASE_URL + 'announcements.php', { ajax: true, action: 'delete_announcement', id: id }, 'json')
                .done(res => { showToast(res.message, 'success'); loadAnnouncements(); })
                .fail(xhr => showToast(xhr.responseJSON?.message || 'Error desconegut.', 'danger'));
        }
    });

    // Listener para el filtro del Superadmin
    $(document).on('change', '#announcement-scope-filter', function() {
        loadAnnouncements();
    });

    // --- Carga Inicial ---
    initializeTomSelects();
    initializeDatePicker();
    loadFormDependencies();
    loadAnnouncements(); // Carga inicial respetando el filtro 'mine' y orden 'created_at DESC'

});
</script>

</body>
</html>
