<?php
$title = "Events";
$menu = "menus/men_event_reader";
$header = "headers/hea_event_reader";

$this->setVar('menu', $menu);
$this->setVar('header', $header);
$this->setVar('title', $title);



?>

<?= $this->extend('layouts/default') ?>
<?= $this->section('content') ?>
<div class="content relative lg:px-4 flex-grow">
    <!--:Prelaoder:-->
    <div id="preloader" class="absolute inset-0 w-full h-[75vh] flex items-center justify-center z-50">
        <div class="size-12 bg-white shadow-xl rounded-full flex items-center justify-center">
            <div class="animate-spin rounded-full size-10 border-b-2 border-primary"></div>
        </div>
    </div>

    <div id="readers-container" class="px-4 grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-5 gap-4 mb-4">


    </div>
    <div id="readerstp-container" class="px-4 grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-5 gap-4 mb-4">


    </div>
    <?php
    echo "<pre>";
    print_r($config_tp);
    echo "</pre>";

    ?>
    <?php
    // $config_tp['timingpoint'] doit exister
    $timingPoints = $config_tp['timingpoint'] ?? [];
    ?>

    <div class="px-4" data-collapse-root>

        <!-- Header du collapse -->
        <div class="flex items-center justify-between p-3 bg-white dark:bg-zinc-900 rounded-t-xl shadow-card">
            <p class="text-left font-semibold">Config (<?php echo count($timingPoints); ?> timing points)</p>

            <button data-collapse-btn class="text-zinc-700 dark:text-white">
                <i data-lucide="chevron-down" class="w-5 h-5"></i>
            </button>
        </div>

        <!-- Contenu collapsable -->
        <div data-collapse-content class="mt-2">

            <?php foreach ($timingPoints as $tp): ?>

                <!-- ========================= -->
                <!-- BLOC TIMING POINT (TP)   -->
                <!-- ========================= -->
                <div class="rounded-xl bg-blue-300 dark:bg-zinc-900 shadow-card mb-4">
                    <div class="grid grid-cols-1 p-2 md:grid-cols-4">

                        <!-- Icone + Nom du TP -->
                        <div class="flex items-center gap-3.5 p-4">
                            <div class="flex items-center justify-center p-4 rounded-lg shrink-0 bg-red-500/10 text-red-500">
                                <span class="icon-[lucide--mouse-pointer-2] text-xl"></span>
                            </div>
                            <div class="flex-grow">
                                <p class="mb-1 font-semibold"><?php echo $tp['tp_name']; ?></p>
                                <p class="mb-1 text-sm text-zinc-600">tp_id : <?php echo $tp['tp_id']; ?></p>
                            </div>
                        </div>

                        <!-- Temp minimum read -->
                        <div class="flex items-center gap-3.5 p-4">
                            <div class="flex items-center justify-center p-4 rounded-lg shrink-0 bg-primary/20 text-primary">
                                <i data-lucide="timer" class="w-4 h-4"></i>
                            </div>

                            <div class="flex-grow">
                                <?php
                                $minRead = $tp['config_tp']['clef_temp_minimum_read'][0] ?? null;
                                ?>
                                <p class="mb-1 text-sm">
                                    Minimum read : <?php echo $minRead['value1'] ?? ''; ?>
                                </p>
                                <p class="mb-1 text-sm">
                                    Mode : <?php echo $minRead['value2'] ?? ''; ?>
                                </p>
                            </div>
                        </div>

                        <!-- Liste des contrôleurs -->
                        <div class="flex items-center gap-3.5 p-4">
                            <div class="flex-grow">
                                <?php foreach ($tp['config_tp']['clef_controleur'] ?? [] as $ctrl): ?>
                                    <p class="mb-1 text-sm">
                                        <?php echo $ctrl['value1']; ?>
                                        - (<?php echo $ctrl['value2']; ?>)
                                        - (<?php echo $ctrl['value3']; ?>)
                                    </p>
                                <?php endforeach; ?>
                            </div>
                        </div>

                        <!-- Case vide ou future config -->
                        <div class="flex items-center gap-3.5 p-4">
                            <div class="flex items-center justify-center p-4 rounded-lg shrink-0 bg-yellow-500/20 text-yellow-500">
                            </div>
                            <div class="flex-grow"></div>
                        </div>

                    </div>
                </div>

                <!-- ========================= -->
                <!-- BLOC INTERVAL              -->
                <!-- ========================= -->
                <?php if (isset($tp['config_tp_interval'])): ?>
                    <div class="rounded-xl bg-blue-300 dark:bg-zinc-900 shadow-card mb-4">
                        <div class="grid grid-cols-1 p-2 md:grid-cols-4">

                            <!-- Titre interval -->
                            <div class="flex items-center gap-3.5 p-4 font-semibold">
                                Interval
                            </div>

                            <!-- Valeur interval -->
                            <div class="flex items-center gap-3.5 p-4 text-sm">
                                <?php
                                $interval = $tp['config_tp_interval']['clef_temp_minimum_read_entre'][0] ?? null;
                                echo $interval['value1'] ?? '';
                                ?>
                            </div>

                            <div class="flex items-center gap-3.5 p-4"></div>
                            <div class="flex items-center gap-3.5 p-4"></div>

                        </div>
                    </div>
                <?php endif; ?>

            <?php endforeach; ?>

        </div>
    </div>







<script>
    const DEBUG = <?= (ENVIRONMENT === 'development') ? 'true' : 'false' ?>;

    const conId = <?= json_encode($data['config']['con_id'] ) ?>;

    document.addEventListener('DOMContentLoaded', () => {

        const container = document.getElementById('readers-container');
        const eventId = <?= json_encode($id) ?>;

        let refreshRate = 1000; // 1 seconde en ms (sera mis à jour par le JSON)

        async function loadReaders() {
            try {
                const response = await fetch('/event/reader-json/' + eventId);
                const json = await response.json();
                if (DEBUG) {
                console.log('JSON complet reçu:', json);
                console.log('json.readers = ', json.readers);
                console.log('Array.isArray(json.readers) = ', Array.isArray(json.readers));
                }
                // MAJ du rate si tu changes plus tard dans DB
                refreshRate = json.refreshRate * 1000;

                // Reconstruire les cartes
                let html = '';
                const readersRaw = json.readers ?? [];
                const readers = Array.isArray(readersRaw) ? readersRaw : Object.values(readersRaw);

                readers.forEach(reader => {
                    // Préparer les dates
                    const start = new Date(reader.start_time * 1000)
                        .toISOString().replace('T', ' ').substring(0, 19);

                    const end = new Date(reader.end_time * 1000)
                        .toISOString().replace('T', ' ').substring(0, 19);

                    html += `
    <div class="p-4 gap-2.5 rounded-xl shadow-card" style="background-color:${reader.bg_color};">
        <div class="flex flex-col">
            <div class="flex items-center justify-between mb-1">
                <div class="flex items-center gap-2">
                    <div class="size-10 rounded-lg bg-zinc-100 dark:bg-zinc-800 flex items-center justify-center">
                        <span class="icon-[${reader.icon}] text-xl"></span>
                    </div>
                    <h5 class="text-1xl m-0">${reader.location}</h5>
                </div>
            </div>

            <div class="flex items-center justify-between mb-1">
                <span class="px-3 py-1 text-sm text-black dark:text-white">Lectures</span>
                <span class="badge bg-green-500/10 text-sky-950">${reader.count}</span>
            </div>

            <div class="flex items-center justify-between mb-1">
                <span class="badge bg-green-500/10 text-amber-900">${start}</span>
            </div>

            <div class="flex items-center justify-between mb-1">
                <span class="badge bg-green-500/10 text-blue-500">${end}</span>
            </div>
        </div>
    </div>
    `;
                });


                // Injecter dans le DOM
                container.innerHTML = html;

            } catch (err) {
                console.error('Erreur AJAX Reader:', err);
            }

            // Relancer après X secondes
            setTimeout(loadReaders, refreshRate);
        }

        // Premier appel
        loadReaders();
        loadReaderTP();
    });

    async function loadReaderTP() {
        try {
            const response = await fetch('/event/readertp-json/' + conId );
            const json = await response.json();

            refreshRate = json.refreshRate * 1000;

            const containerTP = document.getElementById('readerstp-container');
            const listTP = json.readertimingpoint?.timingpoint ?? [];
            let html = '';

            listTP.forEach(tp => {
                html += `
                <div class="p-4 gap-2.5 rounded-xl shadow-card bg-white dark:bg-zinc-900">
                    <div class="flex flex-col">

                        <div class="flex items-center justify-between mb-1">
                            <h5 class="text-1xl m-0">${tp.tp_name}</h5>
                        </div>

                        <div class="flex items-center justify-between mb-1">
                            <span class="px-3 py-1 text-sm text-black dark:text-white">Readers</span>
                            <span class="badge bg-green-500/10 text-sky-950">${tp.tp_reader}</span>
                        </div>

                        <div class="flex items-center justify-between mb-1">
                            <span class="badge bg-green-500/10 text-amber-900">Trie: ${tp.tp_trie}</span>
                        </div>

                    </div>
                </div>
            `;
            });

            containerTP.innerHTML = html;

        } catch (err) {
            console.error('Erreur AJAX TP:', err);
        }

        setTimeout(loadReaderTP, refreshRate);
    }




</script>

<?= $this->endSection() ?>



