<?php
// /reports/treatments_report.php
// CORREGIDO: Sintaxis de CONCAT() para MySQL

// --- 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';
$page_title = "Informe de Tractaments"; // Título específico
$return_url = isset($_GET['return_to']) ? '../' . basename($_GET['return_to']) : '../dashboard.php'; // URL para "Tornar"

// --- 2. RECOPILACIÓN DE DATOS ---
// --- ★★★ INICIO CORRECCIÓN MYSQL ★★★ ---
// (GROUP_CONCAT(c.nombre || ' ' || c.apellido, ', ') -> CONCAT(c.nombre, ' ', c.apellido) SEPARATOR ', ')
$stmt_treatments = $db->prepare("
    SELECT
        t.id, t.title, t.status, t.start_date, t.end_date, t.realizacion_percent,
        p.nombre as patient_name, p.apellido as patient_apellido,
        (SELECT GROUP_CONCAT(CONCAT(c.nombre, ' ', c.apellido) SEPARATOR ', ')
         FROM tratamiento_fisios_asignados tfa
         JOIN cuentas c ON tfa.fisio_id = c.id
         WHERE tfa.tratamiento_id = t.id) as fisios_asignados
    FROM tratamientos t
    LEFT JOIN cuentas p ON t.paciente_id = p.id
    WHERE t.is_protocol = 0
    ORDER BY t.start_date DESC
");
// --- ★★★ FIN CORRECCIÓN MYSQL ★★★ ---
$stmt_treatments->execute();
$treatments = $stmt_treatments->fetchAll(PDO::FETCH_ASSOC);
$treatment_ids = array_column($treatments, 'id');
$exercises_by_treatment = [];
if (!empty($treatment_ids)) {
    $placeholders = implode(',', array_fill(0, count($treatment_ids), '?'));
    $stmt_ex = $db->prepare("
        SELECT te.tratamiento_id, e.title as exercise_title, te.series, te.repetitions, te.rest_time
        FROM tratamiento_ejercicios te
        JOIN ejercicios e ON te.ejercicio_id = e.id
        WHERE te.tratamiento_id IN ($placeholders)
        ORDER BY te.tratamiento_id, te.id ASC
    ");
    $stmt_ex->execute($treatment_ids);
    $all_exercises = $stmt_ex->fetchAll(PDO::FETCH_ASSOC);
    foreach ($all_exercises as $ex) {
        $exercises_by_treatment[$ex['tratamiento_id']][] = $ex;
    }
}
function formatDate($dateStr) {
    if (empty($dateStr)) return 'N/A';
    try { return (new DateTime($dateStr))->format('d/m/Y'); }
    catch (Exception $e) { return 'Data invàlida'; }
}
?>
<!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 */
            --custom-primary-teal-dark: #4aa597; /* Para el badge */
        }
        body { background-color: #e9ecef; }
        .report-container { /* Contenedor principal */
            max-width: 900px; /* Ancho original */
            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 TARJETA (existentes) */
        .section-title { font-weight: 600; border-bottom: 1px solid #dee2e6; padding-bottom: 8px; margin-top: 25px; margin-bottom: 15px; color: #31a3a3; }
        .treatment-card { border: 1px solid #dee2e6; padding: 15px; margin-bottom: 15px; border-radius: 5px; background-color: #f8f9fa; }
        .treatment-card h5 { font-weight: 600; }
        .treatment-card .list-group-item { background-color: transparent; border: none; padding: 4px 0 4px 8px; font-size: 0.9rem;}
        .data-list dt { font-weight: 600; }
        .data-list dd { margin-bottom: 0.3rem; }
        .percent-badge { background-color: var(--custom-primary-teal-dark) !important; color: white; }

        /* 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; }
            /* Asegurar colores */
            .treatment-card { background-color: #f8f9fa !important; border: 1px solid #ced4da !important; page-break-inside: avoid; -webkit-print-color-adjust: exact; print-color-adjust: exact; }
             .percent-badge { background-color: var(--custom-primary-teal-dark) !important; color: white !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="treatment-list">
                <h3 class="section-title">Total de Tractaments (<?= count($treatments) ?>)</h3>
                <?php if (empty($treatments)): ?>
                    <p class="text-muted">No s'han trobat tractaments registrats.</p>
                <?php else: ?>
                    <?php foreach ($treatments as $treatment): ?>
                        <div class="treatment-card">
                            <h5 class="mb-2"><?= htmlspecialchars($treatment['title']) ?></h5>
                            <dl class="row data-list small mb-2">
                                <dt class="col-sm-2">Pacient</dt>
                                <dd class="col-sm-10"><?= htmlspecialchars($treatment['patient_name'] . ' ' . $treatment['patient_apellido']) ?></dd>
                                <dt class="col-sm-2">Estat</dt>
                                <dd class="col-sm-4">
                                    <?= htmlspecialchars($treatment['status']) ?>
                                    <?php if (in_array($treatment['status'], ['Completat', 'Omés']) && isset($treatment['realizacion_percent'])): ?>
                                        <span class="badge percent-badge ms-2">
                                            <i class="bi bi-check-circle me-1"></i><?= htmlspecialchars($treatment['realizacion_percent']) ?>%
                                        </span>
                                    <?php endif; ?>
                                </dd>
                                <dt class="col-sm-2">Dates</dt>
                                <dd class="col-sm-4"><?= formatDate($treatment['start_date']) ?> - <?= formatDate($treatment['end_date']) ?></dd>
                                <dt class="col-sm-2">Fisios</dt>
                                <dd class="col-sm-10"><?= htmlspecialchars($treatment['fisios_asignados'] ?? 'N/A') ?></dd>
                            </dl>
                            <hr class="my-2">
                            <h6>Exercicis Inclosos:</h6>
                            <?php $exercises = $exercises_by_treatment[$treatment['id']] ?? []; ?>
                            <?php if (empty($exercises)): ?>
                                <p class="small text-muted mb-0">Aquest tractament no té exercicis assignats.</p>
                            <?php else: ?>
                                <ul class="list-group list-group-flush small">
                                    <?php foreach ($exercises as $ex): ?>
                                        <li class="list-group-item">
                                            <strong><?= htmlspecialchars($ex['exercise_title']) ?></strong>
                                            <span class="text-muted">(<?= htmlspecialchars($ex['series']) ?> / <?= htmlspecialchars($ex['repetitions']) ?> / <?= htmlspecialchars($ex['rest_time']) ?>)</span>
                                        </li>
                                    <?php endforeach; ?>
                                </ul>
                            <?php endif; ?>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </section>
        </main>
    </div>

    <script>
        document.getElementById('print-btn').addEventListener('click', function() {
            window.print();
        });
    </script>
</body>
</html>
