<?php
// /reports/exercises_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'; // Salir de la carpeta /reports/ para encontrar db.php
$page_title = "Informe d'Exercicis"; // Título específico
$return_url = isset($_GET['return_to']) ? '../' . basename($_GET['return_to']) : '../dashboard.php'; // URL para el botón "Tornar"

// --- 2. RECOPILACIÓN DE DATOS ---
$stmt = $db->prepare("
    SELECT
        e.id, e.title, e.series, e.repetitions, e.rest_time, e.creation_date,
        v.filename as video_filename,
        i.filename as image_filename,
        cat.name as category_name,
        c.nombre as creator_name, c.apellido as creator_surname, /* Restaurado */
        (SELECT GROUP_CONCAT(t.name, ', ')
         FROM ejercicio_tags et
         JOIN tags t ON et.tag_id = t.id
         WHERE et.ejercicio_id = e.id) as tags
    FROM ejercicios e
    LEFT JOIN videos v ON e.id_video = v.id
    LEFT JOIN images i ON e.id_image = i.id
    LEFT JOIN categorias cat ON e.id_categoria = cat.id
    LEFT JOIN cuentas c ON e.id_creator = c.id /* Restaurado JOIN con LEFT JOIN */
    ORDER BY e.title ASC
");
$stmt->execute();
$exercises = $stmt->fetchAll(PDO::FETCH_ASSOC);

function getImagePath($filename) {
    if (empty($filename)) return null;
    $systemImages = ['logo.jpg', 'logo2.jpg', 'img_defecte.jpg'];
    $folder = in_array($filename, $systemImages) ? 'logos/' : 'images/';
    return "../{$folder}{$filename}";
}

function getThumbnailHtml($video_filename, $image_filename) {
    if (!empty($video_filename)) {
        $isEmbed = str_starts_with($video_filename, 'http');
        if ($isEmbed) {
            if (preg_match('/youtube\.com\/embed\/([a-zA-Z0-9\-_]+)/', $video_filename, $matches)) {
                return '<img src="https://img.youtube.com/vi/' . $matches[1] . '/mqdefault.jpg" class="report-thumbnail" alt="Video Thumbnail">';
            }
            return '<div class="thumbnail-placeholder"><i class="bi bi-film"></i><small>Vídeo URL</small></div>';
        } else {
            return '<video src="../videos/' . htmlspecialchars($video_filename) . '#t=0.5" class="report-thumbnail" preload="metadata"></video>';
        }
    }
    if (!empty($image_filename)) {
        $imgPath = getImagePath($image_filename);
        if ($imgPath) {
             return '<img src="' . htmlspecialchars($imgPath) . '" class="report-thumbnail" alt="Image Thumbnail">';
        }
    }
    return '<div class="thumbnail-placeholder"><i class="bi bi-camera-video-off"></i><small>Sense medis</small></div>';
}
?>
<!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;
        }
        body { background-color: #e9ecef; }
        .report-container {
            max-width: 1200px; 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; }
        .exercise-table { font-size: 0.85rem; }
        .exercise-table th { background-color: #f8f9fa; }
        .exercise-table td { vertical-align: middle; }
        .report-thumbnail { width: 100px; height: 56.25px; object-fit: cover; border: 1px solid #dee2e6; border-radius: 4px; background-color: #f0f0f0; }
        .thumbnail-placeholder { width: 100px; height: 56.25px; display: flex; flex-direction: column; align-items: center; justify-content: center; border: 1px dashed #ced4da; border-radius: 4px; color: #6c757d; background-color: #f8f9fa; }
        .thumbnail-placeholder i { font-size: 1.5rem; }
        .thumbnail-placeholder small { font-size: 0.65rem; }

        @media print {
            body { background-color: #ffffff; margin: 0; font-size: 9pt; }
            .no-print { display: none !important; }
            .report-container { width: 100%; max-width: 100%; margin: 0; padding: 10mm; border: none; box-shadow: none; position: static; }

            /* ===== CORRECCIÓN AQUÍ ===== */
            /* Mostrar ambos títulos y centrarlos */
             .report-brand-header, .report-title-header {
                text-align: center; /* Centrar ambos títulos */
                display: block !important; /* Asegurar que se muestren */
            }
            .report-brand-header {
                 margin-bottom: 5px; /* Menos espacio debajo del logo */
                 font-size: 1.2rem; /* Un poco más pequeño para imprimir */
                 color: var(--custom-brand-purple) !important; /* Forzar color */
            }
            .report-title-header {
                 margin-bottom: 20px;
                 border-bottom: 1px solid #ccc;
                 padding-bottom: 10px;
                 font-size: 1rem; /* Un poco más pequeño para imprimir */
                 color: #333 !important; /* Color oscuro para imprimir */
            }
            /* ============================ */

            .exercise-table th { background-color: #f8f9fa !important; -webkit-print-color-adjust: exact; print-color-adjust: exact; }
            .report-thumbnail, .thumbnail-placeholder { border: 1px solid #ccc !important; }
            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="exercise-list">
                <?php if (empty($exercises)): ?>
                    <p class="text-muted">No s'han trobat exercicis registrats.</p>
                <?php else: ?>
                    <table class="table table-sm table-bordered table-striped exercise-table">
                        <thead class="table-light">
                            <tr>
                                <th style="width: 110px;">Media</th>
                                <th>Títol</th>
                                <th>Pauta (S/R/D)</th>
                                <th>Categoria</th>
                                <th>Etiquetes</th>
                                <th>Creat per</th>
                            </tr>
                        </thead>
                        <tbody>
                        <?php foreach ($exercises as $ex): ?>
                            <tr>
                                <td class="text-center">
                                    <?= getThumbnailHtml($ex['video_filename'] ?? null, $ex['image_filename'] ?? null) ?>
                                </td>
                                <td><strong><?= htmlspecialchars($ex['title']) ?></strong></td>
                                <td><?= htmlspecialchars($ex['series']) ?> / <?= htmlspecialchars($ex['repetitions']) ?> / <?= htmlspecialchars($ex['rest_time']) ?></td>
                                <td><?= htmlspecialchars($ex['category_name'] ?? 'N/A') ?></td>
                                <td style="white-space: normal;"><?= htmlspecialchars($ex['tags'] ?? 'N/A') ?></td>
                                <td><?= htmlspecialchars(($ex['creator_name'] ?? 'N/A') . ' ' . ($ex['creator_surname'] ?? '')) ?></td>
                            </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                <?php endif; ?>
            </section>
        </main>
    </div>

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