<?php
// /reports/treatment_report.php

// --- 1. GESTIÓN DE SESIÓN Y DEPENDENCIAS ---
session_start();
// PERMISO: Permitir a fisios y superadmins ver este informe
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';
$user_id = $_SESSION['user_id'];
$user_rol = $_SESSION['user_rol'];

// --- 2. OBTENER ID Y DATOS BÁSICOS ---
$treatment_id = (int)($_GET['id'] ?? 0);
if ($treatment_id === 0) {
    die("Error: No s'ha proporcionat un ID de tractament vàlid.");
}

$return_url = isset($_GET['return_to']) ? '../' . basename(urldecode($_GET['return_to'])) : '../dashboard.php';
$page_title = "Informe Complet de Tractament";

// --- 3. RECOPILACIÓN DE DATOS ---

// -- Query 1: Datos Principales del Tratamiento y Paciente --
$stmt_main = $db->prepare("
    SELECT
        t.title, t.status, t.start_date, t.end_date, t.anamnesis, t.diagnostico, t.realizacion_percent, t.creator_fisio_id,
        p.nombre as paciente_nombre, p.apellido as paciente_apellido, p.email as paciente_email, p.telefono as paciente_telefono
    FROM tratamientos t
    JOIN cuentas p ON t.paciente_id = p.id
    WHERE t.id = ? AND t.is_protocol = 0
");
$stmt_main->execute([$treatment_id]);
$treatment = $stmt_main->fetch(PDO::FETCH_ASSOC);

if (!$treatment) {
    die("Error: Tractament no trobat o no és un tractament vàlid.");
}

// --- 4. COMPROBACIÓN DE PERMISOS ---
if ($user_rol !== 'superadmin') {
    $stmt_perm = $db->prepare("
        SELECT 1 FROM tratamiento_fisios_asignados
        WHERE tratamiento_id = ? AND fisio_id = ?
    ");
    $stmt_perm->execute([$treatment_id, $user_id]);
    if ($treatment['creator_fisio_id'] != $user_id && !$stmt_perm->fetch()) {
        header('Location: ../dashboard.php?error=access_denied');
        exit;
    }
}

// -- Query 2: Fisios Asignados --
$stmt_fisios = $db->prepare("
    SELECT c.nombre, c.apellido
    FROM cuentas c
    JOIN tratamiento_fisios_asignados tfa ON c.id = tfa.fisio_id
    WHERE tfa.tratamiento_id = ?
    ORDER BY c.apellido, c.nombre
");
$stmt_fisios->execute([$treatment_id]);
$assigned_fisios = $stmt_fisios->fetchAll(PDO::FETCH_ASSOC);

// -- Query 3: Pauta de Ejercicios Prescrita --
$stmt_pauta = $db->prepare("
    SELECT e.title, te.frecuencia, te.series, te.repetitions, te.rest_time, te.notes
    FROM tratamiento_ejercicios te
    JOIN ejercicios e ON te.ejercicio_id = e.id
    WHERE te.tratamiento_id = ?
    ORDER BY te.id ASC
");
$stmt_pauta->execute([$treatment_id]);
$prescribed_exercises = $stmt_pauta->fetchAll(PDO::FETCH_ASSOC);

// -- Query 4: Registro de Evolución (Para la tabla/log) --
$stmt_log = $db->prepare("
    SELECT ev.fecha_realizacion, ev.dolor_percibido, ev.esfuerzo_percibido, ev.comentarios, e.title as exercise_title
    FROM tratamiento_evolucion ev
    JOIN tratamiento_ejercicios te ON ev.tratamiento_ejercicio_id = te.id
    JOIN ejercicios e ON te.ejercicio_id = e.id
    WHERE te.tratamiento_id = ?
    ORDER BY ev.fecha_realizacion DESC, e.title ASC
");
$stmt_log->execute([$treatment_id]);
$evolution_log = $stmt_log->fetchAll(PDO::FETCH_ASSOC);

// -- Query 5: Datos de Evolución (Para el gráfico, agrupados por día) --
$stmt_chart = $db->prepare("
    SELECT
        ev.fecha_realizacion,
        AVG(ev.dolor_percibido) as avg_dolor,
        AVG(ev.esfuerzo_percibido) as avg_esfuerzo
    FROM tratamiento_evolucion ev
    JOIN tratamiento_ejercicios te ON ev.tratamiento_ejercicio_id = te.id
    WHERE te.tratamiento_id = ?
    GROUP BY ev.fecha_realizacion
    ORDER BY ev.fecha_realizacion ASC
");
$stmt_chart->execute([$treatment_id]);
$chart_data = $stmt_chart->fetchAll(PDO::FETCH_ASSOC);

?>
<!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">
    <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 {
            max-width: 1200px; /* Más ancho para este informe */
            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;
        }
        .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; }
        .report-buttons { position: absolute; top: 35px; right: 40px; }

        .section-title {
            font-weight: 600;
            border-bottom: 2px solid var(--custom-brand-purple);
            padding-bottom: 8px;
            margin-top: 30px;
            margin-bottom: 20px;
            color: #333;
        }
        .info-card {
            background-color: #f8f9fa;
            border: 1px solid #dee2e6;
            border-radius: .375rem;
            padding: 1.25rem;
        }
        .info-card h6 {
            font-weight: 600;
            color: #495057;
        }

        /* Clases de estado copiadas de smart_report.php */
        .status-badge { font-size: 0.9em; font-weight: 600; padding: 0.35em 0.65em; }
        .status-en-curs { background-color: #fff3cd; color: #664d03; }
        .status-completat { background-color: #d1e7dd; color: #0f5132; }
        .status-programat { background-color: #cff4fc; color: #055160; }
        .status-omès { background-color: #adb5bd; color: #000; }

        /* 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; }
            .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; }

            h5, .section-title {
                border-bottom: 1px solid #ccc;
                padding-bottom: 5px;
                margin-top: 20px;
                font-size: 1.2rem;
                page-break-after: avoid;
            }
            .info-card {
                background-color: #f8f9fa !important;
                border: 1px solid #ced4da !important;
                page-break-inside: avoid;
                -webkit-print-color-adjust: exact;
                print-color-adjust: exact;
            }
            .chart-container {
                page-break-inside: avoid;
                height: 400px !important; /* Altura fija para impresión */
            }
            table {
                page-break-inside: auto; /* Permitir que las tablas se dividan si es necesario */
            }
            tr {
                page-break-inside: avoid;
            }
            .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>

            <section id="summary" class="mb-4">
                <div class="row">
                    <div class="col-lg-6 mb-3 mb-lg-0">
                        <div class="info-card h-100">
                            <h6><i class="bi bi-person-fill me-2"></i>Pacient</h6>
                            <h4 class="mb-1"><?= htmlspecialchars($treatment['paciente_nombre'] . ' ' . $treatment['paciente_apellido']) ?></h4>
                            <p class="mb-1"><i class="bi bi-envelope me-2"></i><?= htmlspecialchars($treatment['paciente_email']) ?></p>
                            <p class="mb-0"><i class="bi bi-phone me-2"></i><?= htmlspecialchars($treatment['paciente_telefono'] ?? 'N/A') ?></p>
                        </div>
                    </div>
                    <div class="col-lg-6">
                        <div class="info-card h-100">
                            <h6><i class="bi bi-journal-medical me-2"></i>Tractament</h6>
                            <h4 class="mb-2"><?= htmlspecialchars($treatment['title']) ?></h4>
                            <div class="d-flex justify-content-between">
                                <div>
                                    <p class="mb-1"><strong>Dates:</strong> <?= (new DateTime($treatment['start_date']))->format('d/m/Y') ?> - <?= (new DateTime($treatment['end_date']))->format('d/m/Y') ?></p>
                                    <p class="mb-0"><strong>Fisios:</strong>
                                        <?php
                                        $fisio_names = [];
                                        foreach ($assigned_fisios as $fisio) { $fisio_names[] = htmlspecialchars($fisio['nombre'] . ' ' . $fisio['apellido']); }
                                        echo implode(', ', $fisio_names);
                                        ?>
                                    </p>
                                </div>
                                <div class="text-end">
                                    <?php
                                    $status = $treatment['status'];
                                    $status_class = 'status-' . strtolower(str_replace(' ', '-', $status));
                                    echo "<span class=\"badge $status_class status-badge\">$status</span>";

                                    if ($treatment['realizacion_percent'] !== null) {
                                        echo "<p class='mb-0 mt-2 small'>Adherència: <strong>" . $treatment['realizacion_percent'] . "%</strong></p>";
                                    }
                                    ?>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </section>

            <section id="clinical-data">
                <h5 class="section-title">Dades Clíniques</h5>
                <div class="row">
                    <div class="col-md-6">
                        <h6>Anamnesi</h6>
                        <p class="text-muted"><?= nl2br(htmlspecialchars($treatment['anamnesis'] ?? 'No registrada.')) ?></p>
                    </div>
                    <div class="col-md-6">
                        <h6>Diagnòstic</h6>
                        <p class="text-muted"><?= nl2br(htmlspecialchars($treatment['diagnostico'] ?? 'No registrat.')) ?></p>
                    </div>
                </div>
            </section>

            <section id="evolution-chart">
                <h5 class="section-title">Gràfic d'Evolució (Mitjanes Diàries)</h5>
                <div class="chart-container" style="position: relative; height:350px;">
                    <?php if (empty($chart_data)): ?>
                        <div class="alert alert-warning text-center">No hi ha dades d'evolució registrades per a mostrar el gràfic.</div>
                    <?php else: ?>
                        <canvas id="evolutionChart"></canvas>
                    <?php endif; ?>
                </div>
            </section>

            <section id="prescribed-exercises">
                <h5 class="section-title">Pauta d'Exercicis Prescrita (<?= count($prescribed_exercises) ?>)</h5>
                <div class="table-responsive">
                    <table class="table table-sm table-striped table-bordered">
                        <thead class="table-light">
                            <tr>
                                <th>Exercici</th>
                                <th>Freqüència</th>
                                <th>Sèries</th>
                                <th>Repeticions</th>
                                <th>Descans</th>
                                <th>Notes</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($prescribed_exercises as $ex): ?>
                                <tr>
                                    <td><?= htmlspecialchars($ex['title']) ?></td>
                                    <td><?= htmlspecialchars($ex['frecuencia']) ?></td>
                                    <td><?= htmlspecialchars($ex['series']) ?></td>
                                    <td><?= htmlspecialchars($ex['repetitions']) ?></td>
                                    <td><?= htmlspecialchars($ex['rest_time']) ?></td>
                                    <td><?= htmlspecialchars($ex['notes']) ?></td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </section>

            <section id="evolution-log">
                <h5 class="section-title">Registre Detallat del Pacient (<?= count($evolution_log) ?> entrades)</h5>
                <?php if (empty($evolution_log)): ?>
                    <div class="alert alert-secondary text-center">El pacient no ha registrat cap evolució per a aquest tractament.</div>
                <?php else: ?>
                    <div class="table-responsive" style="max-height: 600px; overflow-y: auto;">
                        <table class="table table-sm table-striped table-hover">
                            <thead class="table-light" style="position: sticky; top: 0;">
                                <tr>
                                    <th>Data</th>
                                    <th>Exercici</th>
                                    <th>Dolor (0-5)</th>
                                    <th>Esforç (0-5)</th>
                                    <th>Comentaris del Pacient</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($evolution_log as $log): ?>
                                    <tr>
                                        <td class="text-nowrap"><?= (new DateTime($log['fecha_realizacion']))->format('d/m/Y') ?></td>
                                        <td><?= htmlspecialchars($log['exercise_title']) ?></td>
                                        <td class="text-center"><?= htmlspecialchars($log['dolor_percibido'] ?? 'N/A') ?></td>
                                        <td class="text-center"><?= htmlspecialchars($log['esfuerzo_percibido'] ?? 'N/A') ?></td>
                                        <td><?= htmlspecialchars($log['comentarios'] ?? '...') ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </section>

        </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/chart.js@4.4.1/dist/chart.umd.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-date-fns@3.0.0/dist/chartjs-adapter-date-fns.bundle.min.js"></script>

    <script>
        // Pasar datos de PHP a JS para el gráfico
        const chartData = <?= json_encode($chart_data); ?>;

        $(document).ready(function() {
            // 1. Botón de Imprimir
            $('#print-btn').on('click', function() {
                window.print();
            });

            // 2. Renderizar Gráfico (si hay datos)
            if (chartData && chartData.length > 0) {
                const ctx = document.getElementById('evolutionChart');

                const labels = chartData.map(d => d.fecha_realizacion);
                const painData = chartData.map(d => d.avg_dolor);
                const effortData = chartData.map(d => d.avg_esfuerzo);

                new Chart(ctx, {
                    type: 'line',
                    data: {
                        labels: labels,
                        datasets: [
                            {
                                label: 'Dolor Mitjà (0-5)',
                                data: painData,
                                borderColor: 'rgb(255, 99, 132)',
                                backgroundColor: 'rgba(255, 99, 132, 0.5)',
                                tension: 0.1,
                                spanGaps: true, // Conecta líneas aunque falten datos
                                yAxisID: 'y'
                            },
                            {
                                label: 'Esforç Mitjà (0-5)',
                                data: effortData,
                                borderColor: 'rgb(54, 162, 235)',
                                backgroundColor: 'rgba(54, 162, 235, 0.5)',
                                tension: 0.1,
                                spanGaps: true,
                                yAxisID: 'y'
                            }
                        ]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        animation: {
                            duration: 0 // Desactivar animación para impresión
                        },
                        scales: {
                            x: {
                                type: 'time',
                                time: {
                                    unit: 'day',
                                    tooltipFormat: 'dd MMM yyyy',
                                    displayFormats: { day: 'dd/MM' }
                                },
                                ticks: {
                                    maxTicksLimit: 15,
                                    autoSkip: true
                                }
                            },
                            y: {
                                beginAtZero: true,
                                max: 5, // Escala de 0 a 5
                                ticks: { stepSize: 1 }
                            }
                        },
                        plugins: {
                            tooltip: {
                                mode: 'index',
                                intersect: false
                            }
                        },
                        interaction: {
                            intersect: false,
                            mode: 'index',
                        }
                    }
                });
            }
        });
    </script>
</body>
</html>
