<?php
// /reports/smart_report.php

// --- 1. GESTIÓN DE SESIÓN Y DEPENDENCIAS ---
session_start();
// PERMISO: Permitir a fisios y superadmins ver esta herramienta
if (!isset($_SESSION['user_id']) || !in_array($_SESSION['user_rol'], ['fisio', 'superadmin'])) {
    header('Location: ../index.php'); // Salir de la carpeta /reports/
    exit;
}
require '../db.php';
$page_title = "Informe Intel·ligent"; // Título específico
$return_url = isset($_GET['return_to']) ? '../' . basename($_GET['return_to']) : '../dashboard.php'; // URL para "Tornar"

// NO incluimos el header, es una página independiente
?>
<!DOCTYPE html>
<html lang="ca">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= $page_title ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
    <link href="https://cdn.jsdelivr.net/npm/tom-select@2.3.1/dist/css/tom-select.bootstrap5.css" rel="stylesheet">

    <style>
            :root {
                --bs-body-font-family: "Segoe UI", "Helvetica Neue", Arial, sans-serif;
                --custom-brand-purple: #684A7A; /* Color corporativo */
            }
            body { background-color: #e9ecef; }
            .report-container { /* Contenedor principal */
                max-width: 1200px; /* Ancho aumentado */
                margin: 20px auto; padding: 40px;
                background-color: #ffffff; border: 1px solid #dee2e6;
                box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, .075);
                position: relative; /* Para posicionar botones */
            }
            /* NUEVA CABECERA */
            .report-brand-header { color: var(--custom-brand-purple); font-weight: bold; font-size: 1.5rem; margin-bottom: 0; }
            .report-title-header { font-size: 1.25rem; font-weight: 300; color: #495057; border-bottom: 1px solid #dee2e6; padding-bottom: 10px; margin-bottom: 30px; }
            /* NUEVOS BOTONES */
            .report-buttons { position: absolute; top: 35px; right: 40px; }
            /* Estilos específicos del Smart Report (existentes) */
            .report-builder-card { background-color: #f8f9fa; border: 1px solid #dee2e6; }
            .results-container { max-height: 600px; overflow-y: auto; border: 1px solid #dee2e6; border-radius: .25rem; background-color: #f8f9fa; }
            .results-container .list-group-item { border-bottom: 1px solid #eee !important; background-color: transparent; }
            .status-badge { font-size: 0.8em; font-weight: 600; padding: 0.25em 0.5em; border-radius: 0.25rem; }

            /* --- ESTILOS DE ESTADO MODIFICADOS --- */
            .status-en-curs { background-color: #fff3cd; color: #664d03; } /* Amarillo */
            .status-completat { background-color: #d1e7dd; color: #0f5132; } /* Verde */
            .status-programat { background-color: #cff4fc; color: #055160; } /* Azul */

            /* --- MODIFICADO: Gris más oscuro con texto oscuro --- */
.status-om\00E8s {
    background-color: #adb5bd; /* Gris fosc */
    color: #000; /* Texto negro */
}
/* --- FIN DE ESTILOS DE ESTADO --- */

            /* ESTILOS DE IMPRESIÓN */
            @media print {
                body { background-color: #ffffff; margin: 0; font-size: 10pt; }
                .no-print { display: none !important; }
                .report-container { width: 100%; max-width: 100%; margin: 0; padding: 10mm; border: none; box-shadow: none; position: static; }
                /* Mostrar ambos títulos y centrarlos */
                 .report-brand-header, .report-title-header { text-align: center; display: block !important; }
                 .report-brand-header { margin-bottom: 5px; font-size: 1.2rem; color: var(--custom-brand-purple) !important; }
                 .report-title-header { margin-bottom: 20px; border-bottom: 1px solid #ccc; padding-bottom: 10px; font-size: 1rem; color: #333 !important; }
                /* Ocultar formulario, mostrar solo resultados */
                #smartReportTabs, .tab-content > .tab-pane > p.text-muted, .tab-content > .tab-pane > .card, .tab-content > .tab-pane > hr:first-of-type { display: none; }
                .results-container { border: none; background-color: transparent !important; max-height: none; overflow: visible; padding: 0 !important; margin-top: 0 !important; }
                .tab-content { border: none !important; box-shadow: none !important; background-color: transparent !important; padding: 0 !important; } /* Resetear contenedor tabs */

                 /* MODIFICADO: Aplicar estilo de borde a TODOS los h5 (incluido el nuevo de resumen) */
                 h5 { border-bottom: 1px solid #ccc; padding-bottom: 5px; margin-top: 10px; font-size: 1.1rem; }

                 /* ===== CORRECCIÓN CSS (Añadido) ===== */
                 /* Estilo específico para el resumen de la consulta de impresión */
                 .query-summary-print {
                    font-weight: normal;
                    font-size: 1.1rem;
                    line-height: 1.6;
                    color: #333;
                 }
                 .query-summary-print b {
                    color: #000;
                 }
                 /* ==================================== */

                 .results-container ul { margin-bottom: 20px !important; }
                 .results-container .list-group-item { border: none !important; padding: 2px 0 !important; }
                 .status-badge { background-color: #eee !important; color: #333 !important; -webkit-print-color-adjust: exact; print-color-adjust: exact;}
                 a { text-decoration: none; color: #000 !important; }
            }
        </style>

</head>
<body>

    <div class="report-container" id="report-content">

        <header class="mb-4 no-print">
            <h4 class="report-brand-header">Avant Online</h4>
            <h1 class="report-title-header"><?= $page_title ?></h1>
        </header>

        <div class="report-buttons no-print">
            <a href="<?= htmlspecialchars($return_url) ?>" class="btn btn-secondary">
                <i class="bi bi-arrow-left me-1"></i>Tornar
            </a>
            <button id="print-btn" class="btn btn-primary">
                <i class="bi bi-printer me-1"></i>Imprimir
            </button>
        </div>

        <main> <header class="d-none d-print-block text-center">
                 <h4 class="report-brand-header">Avant Online</h4>
                 <h1 class="report-title-header"><?= $page_title ?></h1>
            </header>

            <ul class="nav nav-tabs no-print" id="smartReportTabs" role="tablist">
                <li class="nav-item" role="presentation">
                    <button class="nav-link active" id="usage-tab" data-bs-toggle="tab" data-bs-target="#usage-panel" type="button" role="tab">Anàlisi d'Ús</button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link" id="patient-tab" data-bs-toggle="tab" data-bs-target="#patient-panel" type="button" role="tab">Cerca de Pacients</button>
                </li>
            </ul>

            <div class="tab-content border border-top-0 p-4 mb-4 shadow-sm bg-white rounded-bottom"> <div class="tab-pane fade show active" id="usage-panel" role="tabpanel">
                    <p class="text-muted no-print">Aquesta eina t'ajuda a trobar on s'està utilitzant un recurs.</p>
                    <div class="card report-builder-card no-print">
                        <div class="card-body">
                            <form id="usage-form" class="row g-3 align-items-end">
                                <div class="col-md-4">
                                    <label for="usage-type-select" class="form-label fw-bold">1. Vull analitzar...</label>
                                    <select id="usage-type-select" class="form-select">
                                        <option value="" selected disabled>Selecciona un tipus de recurs...</option>
                                        <option value="exercici">Un Exercici</option>
                                        <option value="protocol">Un Protocol</option>
                                        <option value="tractament">Un Tractament</option>
                                        <option value="video">Un Vídeo</option>
                                        <option value="image">Una Imatge</option>
                                    </select>
                                </div>
                                <div class="col-md-6">
                                    <label for="usage-item-select" class="form-label fw-bold">2. Selecciona l'ítem</label>
                                    <select id="usage-item-select" disabled></select>
                                </div>
                                <div class="col-md-2">
                                    <button type="submit" class="btn btn-primary w-100" disabled>
                                        <i class="bi bi-search me-1"></i> Analitzar
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>
                    <hr class="no-print">
                    <h5>Resultats de l'Anàlisi:</h5>

                    <h5 class="d-none d-print-block query-summary-print" id="usage-query-summary"></h5>
                    <div id="usage-results-container" class="results-container p-3">
                         <p class="text-center text-muted no-print">Selecciona un tipus de recurs i un ítem per començar.</p>
                         </div>
                </div>

                <div class="tab-pane fade" id="patient-panel" role="tabpanel">
                    <p class="text-muted no-print">Aquesta eina t'ajuda a trobar pacients basant-te en el contingut dels seus tractaments.</p>
                    <div class="card report-builder-card no-print">
                         <div class="card-body">
                            <form id="patient-form" class="row g-3 align-items-end">
                                <div class="col-md-4">
                                    <label for="patient-condition-select" class="form-label fw-bold">1. Vull trobar pacients que...</label>
                                    <select id="patient-condition-select" class="form-select">
                                        <option value="" selected disabled>Selecciona una condició...</option>
                                        <option value="exercici">Tenen assignat un Exercici</option>
                                        <option value="protocol">El seu tractament prové d'un Protocol</option>
                                        <option value="video">Tenen un exercici que usa un Vídeo</option>
                                        <option value="image">Tenen un exercici que usa una Imatge</option>
                                    </select>
                                </div>
                                <div class="col-md-6">
                                    <label for="patient-item-select" class="form-label fw-bold">2. Selecciona l'ítem</label>
                                    <select id="patient-item-select" disabled></select>
                                </div>
                                <div class="col-md-2">
                                    <button type="submit" class="btn btn-primary w-100" disabled>
                                        <i class="bi bi-search me-1"></i> Cercar
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>
                    <hr class="no-print">
                    <h5>Resultats de la Cerca:</h5>

                    <h5 class="d-none d-print-block query-summary-print" id="patient-query-summary"></h5>
                    <div id="patient-results-container" class="results-container p-3">
                        <p class="text-center text-muted no-print">Selecciona una condició i un ítem per començar.</p>
                        </div>
                </div>
            </div> </main> </div> <script src="https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/tom-select@2.3.1/dist/js/tom-select.complete.min.js"></script>
    <div class="toast-container position-fixed bottom-0 end-0 p-3 no-print">
        <div id="liveToast" class="toast" role="alert" aria-live="assertive" aria-atomic="true">
            <div class="toast-header">
                <i class="bi bi-check-circle-fill rounded me-2"></i>
                <strong class="me-auto">Avant Online</strong>
                <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
            </div>
            <div class="toast-body"></div>
        </div>
    </div>
    <script>
        // Función de Toast
        function showToast(message, type = 'success') {
            const toastEl = $('#liveToast'); if (!toastEl.length) return;
            const toastBody = toastEl.find('.toast-body');
            const toastHeaderIcon = toastEl.find('.toast-header i');
            toastBody.text(message);
            if (type === 'danger') { toastHeaderIcon.attr('class', 'bi bi-exclamation-triangle-fill rounded me-2 text-danger'); }
            else if (type === 'warning') { toastHeaderIcon.attr('class', 'bi bi-exclamation-triangle-fill rounded me-2 text-warning'); }
            else { toastHeaderIcon.attr('class', 'bi bi-check-circle-fill rounded me-2 text-success'); }
            const toast = bootstrap.Toast.getOrCreateInstance(toastEl[0]); // Use getOrCreateInstance
            toast.show();
        }

        // JavaScript Específico
        $(document).ready(function() {
            let allData = { exercici: [], protocol: [], tractament: [], video: [], image: [] };
            let tsUsageItem = new TomSelect('#usage-item-select', { placeholder: 'Selecciona un ítem...' });
            let tsPatientItem = new TomSelect('#patient-item-select', { placeholder: 'Selecciona un ítem...' });

            function loadInitialData() {
                $.getJSON('../reports_ajax.php', { action: 'get_all_dependencies' })
                    .done(function(response) {
                        if (response.status === 'success') {
                            allData.exercici = response.exercises.map(item => ({ value: item.id, text: item.title }));
                            allData.protocol = response.protocols.map(item => ({ value: item.id, text: item.title }));
                            allData.tractament = response.treatments.map(item => ({ value: item.id, text: item.title }));
                            allData.video = response.videos.map(item => ({ value: item.id, text: item.title }));
                            allData.image = response.images.map(item => ({ value: item.id, text: item.title }));
                        } else { showToast('Error en carregar les dades inicials.', 'danger'); }
                    })
                    .fail(() => showToast('Error de connexió en carregar dades.', 'danger'));
            }

            function updateItemSelect(selectInstance, itemType, formButton) {
                selectInstance.clear(); selectInstance.clearOptions(); selectInstance.disable();
                formButton.prop('disabled', true);
                if (itemType && allData[itemType] && allData[itemType].length > 0) { // Check if data exists
                    selectInstance.addOptions(allData[itemType]);
                    selectInstance.enable(); formButton.prop('disabled', false);
                } else if (itemType) {
                    // Optionally show a message if the list is empty
                    selectInstance.addOption({value: '', text: `No hi ha ${itemType}s disponibles.`});
                    selectInstance.disable(); // Keep it disabled
                }
            }


            $('#usage-type-select').on('change', function() { updateItemSelect(tsUsageItem, $(this).val(), $('#usage-form button[type="submit"]')); });
            $('#patient-condition-select').on('change', function() { updateItemSelect(tsPatientItem, $(this).val(), $('#patient-form button[type="submit"]')); });

            // =================== HANDLER 1 (Usage Form) ===================
            $('#usage-form').on('submit', function(e) {
                 e.preventDefault();
                const type = $('#usage-type-select').val();
                const id = tsUsageItem.getValue();

                // Capturar los textos seleccionados
                const type_text = $('#usage-type-select').find('option:selected').text();

                // ===== INICIO DE LA CORRECCIÓN JS (1/2) =====
                // Lógica DEFINITIVA: Buscar el texto en el array 'allData'
                // en lugar de depender del método .getOption() de TomSelect.
                let item_text = '';
                if (id && type && allData[type]) {
                    // Usamos '==' por si 'id' es string y 'item.value' es número
                    const foundItem = allData[type].find(item => item.value == id);
                    if (foundItem) {
                        item_text = foundItem.text;
                    }
                }
                // =====  FIN DE LA CORRECCIÓN JS (1/2)  =====

                const $button = $(this).find('button[type="submit"]');
                const $resultsContainer = $('#usage-results-container');
                if (!type || !id) { showToast('Si us plau, selecciona un tipus i un ítem.', 'warning'); return; }
                $button.prop('disabled', true).html('<span class="spinner-border spinner-border-sm" role="status"></span>');

                // Limpiamos resultados anteriores Y el resumen de impresión
                $resultsContainer.html('<p class="text-center text-muted no-print">Cercant...</p>');
                $('#usage-query-summary').html(''); // Limpiar resumen

                $.getJSON('../reports_ajax.php', { action: 'run_smart_report', mode: 'usage_analysis', type: type, id: id })
                    .done(response => {
                        if(response.status === 'success') {
                            // Capturar el texto de las ETIQUETAS
                            const label1_text = $('label[for="usage-type-select"]').text().trim();
                            const label2_text = $('label[for="usage-item-select"]').text().trim();
                            // Crear el HTML del resumen exacto
                            const summary_html = `<b>${label1_text}</b> ${type_text}<br><b>${label2_text}:</b> ${item_text}`;
                            $('#usage-query-summary').html(summary_html); // Usamos .html() por el <br>

                            renderUsageResults(response.data, type);
                        } else {
                            throw new Error(response.message);
                        }
                    })
                    .fail((jqXHR, textStatus, errorThrown) => { console.error("AJAX Error (Usage):", textStatus, errorThrown, jqXHR.responseText); $resultsContainer.html('<div class="alert alert-danger">Error en executar l\'informe. Comprova la consola.</div>'); })
                    .always(() => $button.prop('disabled', false).html('<i class="bi bi-search me-1"></i> Analitzar'));
            });

            // =================== HANDLER 2 (Patient Form) ===================
            $('#patient-form').on('submit', function(e) {
                 e.preventDefault();
                const type = $('#patient-condition-select').val();
                const id = tsPatientItem.getValue();

                // Capturar los textos seleccionados
                const condition_text = $('#patient-condition-select').find('option:selected').text();

                // ===== INICIO DE LA CORRECCIÓN JS (2/2) =====
                // Lógica DEFINITIVA: Buscar el texto en el array 'allData'.
                let item_text = '';
                if (id && type && allData[type]) {
                    // Usamos '==' por si 'id' es string y 'item.value' es número
                    const foundItem = allData[type].find(item => item.value == id);
                    if (foundItem) {
                        item_text = foundItem.text;
                    }
                }
                // =====  FIN DE LA CORRECCIÓN JS (2/2)  =====

                const $button = $(this).find('button[type="submit"]');
                const $resultsContainer = $('#patient-results-container');
                if (!type || !id) { showToast('Si us plau, selecciona una condició i un ítem.', 'warning'); return; }
                $button.prop('disabled', true).html('<span class="spinner-border spinner-border-sm" role="status"></span>');

                // Limpiamos resultados anteriores Y el resumen de impresión
                $resultsContainer.html('<p class="text-center text-muted no-print">Cercant...</p>');
                $('#patient-query-summary').html(''); // Limpiar resumen

                $.getJSON('../reports_ajax.php', { action: 'run_smart_report', mode: 'patient_search', type: type, id: id })
                    .done(response => {
                        if(response.status === 'success') {
                            // Capturar el texto de las ETIQUETAS
                            const label1_text = $('label[for="patient-condition-select"]').text().trim();
                            const label2_text = $('label[for="patient-item-select"]').text().trim();
                            // Crear el HTML del resumen exacto
                            const summary_html = `<b>${label1_text}</b> ${condition_text}<br><b>${label2_text}:</b> ${item_text}`;
                            $('#patient-query-summary').html(summary_html); // Usamos .html() por el <br>

                            renderPatientResults(response.data);
                        } else {
                            throw new Error(response.message);
                        }
                    })
                    .fail((jqXR, textStatus, errorThrown) => { console.error("AJAX Error (Patient Search):", textStatus, errorThrown, jqXHR.responseText); $resultsContainer.html('<div class="alert alert-danger">Error en executar l\'informe. Comprova la consola.</div>'); })
                    .always(() => $button.prop('disabled', false).html('<i class="bi bi-search me-1"></i> Cercar'));
             });

            function renderUsageResults(data, type) {
                // Modificado: Seleccionar el 'p' específico para eliminarlo
                const $container = $('#usage-results-container');
                $container.find('p.no-print').remove(); // Quitamos el texto "Cercant..."
                let html = ''; // El H5 de impresión ya existe, no hace falta añadirlo aquí

                if (type === 'exercici') {
                    html += renderList('Protocols que l\'utilitzen:', data.protocols, 'bi-clipboard2-pulse');
                    html += renderList('Tractaments actius que l\'utilitzen:', data.active_treatments, 'bi-person');
                    html += renderList('Tractaments històrics que l\'utilitzen:', data.historic_treatments, 'bi-person-check');
                } else if (type === 'protocol') {
                    html += renderList('Tractaments creats a partir d\'aquest protocol:', data.treatments_from_protocol, 'bi-journal-medical');
                } else if (type === 'tractament') {
                    html += renderList('Pacient assignat:', data.patient, 'bi-person-fill');
                    html += renderList('Fisios assignats:', data.fisios, 'bi-file-medical');
                    html += renderList('Exercicis inclosos:', data.exercises, 'bi-person-arms-up');
                } else if (type === 'video' || type === 'image') {
                    html += renderList('Exercicis que utilitzen aquest medi:', data.exercises, 'bi-person-arms-up');
                }

                // Añadimos los resultados después del H5 de impresión
                $container.append(html || '<p class="text-center text-muted no-print">No s\'han trobat resultats.</p>');
            }

            function renderPatientResults(data) {
                // Modificado: Seleccionar el 'p' específico para eliminarlo
                const $container = $('#patient-results-container');
                $container.find('p.no-print').remove(); // Quitamos el texto "Cercant..."

                if (!data || !data.patients || data.patients.length === 0) {
                    $container.append('<p class="text-center text-muted no-print">No s\'han trobat pacients que compleixin la condició.</p>');
                    return;
                }

                let html = `<h6>S'han trobat ${data.patients.length} pacients:</h6>`;
                html += '<ul class="list-group list-group-flush">';
                data.patients.forEach(p => {

                  let statusClean = p.status ? p.status.toLowerCase().replace(' ', '-') : 'desconegut';
                  // Corrección del bug 'Omés' (aguda) vs 'Omès' (grave)
                  statusClean = statusClean.replace('é', 'è');
                  const statusClass = 'status-' + statusClean;

                    const statusText = p.status || 'Desconegut';
                    const treatmentTitle = p.treatment_title || 'Tractament sense títol';
                    const patientName = `${p.nombre || ''} ${p.apellido || ''}`.trim() || 'Pacient desconegut';
                    html += `
                        <li class="list-group-item d-flex justify-content-between align-items-center">
                            <div>
                                <i class="bi bi-person-fill me-2 text-muted"></i>
                                <strong>${patientName}</strong>
                                <small class="d-block text-muted ms-4">Tractament: "${treatmentTitle}"</small>
                            </div>
                            <span class="badge ${statusClass}">${statusText}</span>
                        </li>`;
                });
                html += '</ul>';

                // Añadimos los resultados después del H5 de impresión
                $container.append(html);
             }

            function renderList(title, items, icon) {
                 if (!items || items.length === 0) {
                    return `<h6>${title}</h6><p class="text-muted small mb-3">Cap resultat.</p>`; // Added mb-3
                }
                let html = `<h6>${title} (${items.length})</h6><ul class="list-group list-group-flush mb-3">`; // Added mb-3
                items.forEach(item => {
                    // Safely access properties with null checks
                    const itemName = item.title || `${item.nombre || ''} ${item.apellido || ''}`.trim();
                    let name = itemName || 'Sense Nom'; // Fallback if name is still empty
                    let subtitle = '';
                    if (item.nombre && item.apellido && item.title) { // Treatment item
                        subtitle = `<small class="text-muted ms-2">(Pacient: ${item.nombre} ${item.apellido})</small>`;
                    } else if (item.nombre && item.apellido && !item.title) { // User item
                         name = `${item.nombre} ${item.apellido}`;
                     }
                    html += `<li class="list-group-item"><i class="bi ${icon} me-2 text-muted"></i>${name} ${subtitle}</li>`;
                });
                html += '</ul>';
                return html;
            }


            // Añadir el listener para el nuevo botón de imprimir
            document.getElementById('print-btn').addEventListener('click', function() {
                window.print();
            });

            loadInitialData();
        });
    </script>
</body>
</html>
