<?php
// /reports/taxonomy_report.php

// --- 1. GESTIÓN DE SESIÓN Y DEPENDENCIAS ---
session_start();
// PERMISO: Solo para Superadmin
if (!isset($_SESSION['user_id']) || $_SESSION['user_rol'] !== 'superadmin') {
    header('Location: ../index.php'); // Salir de la carpeta /reports/
    exit;
}
require '../db.php';
$page_title = "Informe de Catàleg (Taxonomia)"; // Título específico
$return_url = isset($_GET['return_to']) ? '../' . basename($_GET['return_to']) : '../dashboard.php'; // URL para "Tornar"

// --- 2. RECOPILACIÓN DE DATOS ---
// ... (Tu código PHP existente para obtener $all_categories, $all_tags y la función render_taxonomy_list) ...
$stmt_cats = $db->prepare("SELECT id, name, parent_id FROM categorias ORDER BY name");
$stmt_cats->execute();
$all_categories = $stmt_cats->fetchAll(PDO::FETCH_ASSOC);
$stmt_tags = $db->prepare("SELECT id, name, parent_id FROM tags ORDER BY name");
$stmt_tags->execute();
$all_tags = $stmt_tags->fetchAll(PDO::FETCH_ASSOC);

function render_taxonomy_list($items, $parent_id = null, $level = 0) {
    $html = '';
    $children = [];
    foreach ($items as $item) {
        if ($item['parent_id'] == $parent_id) { $children[] = $item; }
    }
    if (empty($children)) { return ''; }
    // Sort children alphabetically by name before rendering
    usort($children, function($a, $b) { return strcmp($a['name'], $b['name']); });

    $html .= '<ul class="taxonomy-list ' . ($level == 0 ? 'list-group list-group-flush' : 'list-group') . '">';
    foreach ($children as $child) {
        $padding = $level * 20; // Indentación
        $html .= '<li class="list-group-item" style="padding-left: ' . $padding . 'px;">';
        $prefix = $level > 0 ? str_repeat('&nbsp;&nbsp;&nbsp;&nbsp;', $level-1) . '↳ ' : ''; // Add arrow for children
        $html .= $prefix . '<strong>' . htmlspecialchars($child['name']) . '</strong> (ID: ' . $child['id'] . ')';
        // Recursividad
        $html .= render_taxonomy_list($items, $child['id'], $level + 1);
        $html .= '</li>';
    }
    $html .= '</ul>';
    return $html;
}
?>
<!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 { /* 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 LISTA (existentes, ajustados) */
        .section-title { font-weight: 600; border-bottom: 1px solid #dee2e6; padding-bottom: 8px; margin-top: 25px; margin-bottom: 15px; color: #31a3a3; }
        .taxonomy-list { padding-left: 0; list-style-type: none; }
        .taxonomy-list ul { padding-left: 0; margin-top: 5px; list-style-type: none; }
        .taxonomy-list li.list-group-item { border-bottom: 1px solid #f0f0f0 !important; padding: 6px 5px !important; background-color: transparent !important; border-top: none !important; border-left: none !important; border-right: none !important; }
        .taxonomy-list li strong { color: #212529; }
        .taxonomy-list .card-body { padding: 0; } /* Quitar padding extra */

        /* 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; }
            /* Estilos impresión lista */
            .section-title { margin-top: 15px; }
            .card-body { padding: 0 !important; }
            .taxonomy-list li.list-group-item { border-bottom: 1px solid #ddd !important; padding: 4px 0 !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="category-list">
                <h3 class="section-title">Categories Anatòmiques (<?= count($all_categories) ?>)</h3>
                <?php if (empty($all_categories)): ?>
                    <p class="text-muted">No s'han trobat categories.</p>
                <?php else: ?>
                    <div class="card card-body border-0 p-0"> <?php echo render_taxonomy_list($all_categories); ?>
                    </div>
                <?php endif; ?>
            </section>

            <section id="tag-list">
                <h3 class="section-title">Etiquetes Funcionals (<?= count($all_tags) ?>)</h3>
                 <?php if (empty($all_tags)): ?>
                    <p class="text-muted">No s'han trobat etiquetes.</p>
                <?php else: ?>
                    <div class="card card-body border-0 p-0"> <?php echo render_taxonomy_list($all_tags); ?>
                    </div>
                <?php endif; ?>
            </section>
        </main>
    </div>

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