<?php

    global $twig;

    // Paramètres de la pagination
    $perPage = 30;
    $currentPage = isset($_GET['page']) ? (int)$_GET['page'] : 1;
    if ($currentPage < 1) {
        $currentPage = 1;
    }

    // Calcul du nombre total d'éléments et de pages
    $totalItems = count($tq);
    $totalPages = ceil($totalItems / $perPage);

    // Découpage du tableau pour ne garder que les éléments de la page courante
    $offset = ($currentPage - 1) * $perPage;
    $quotesPaginated = array_slice($tq, $offset, $perPage);

    echo $twig->render('head.html.twig', array(
        'title'   => "Search",
        'style'   => "public/styles/styleSearch.css",
        'scripts' => array("public/script/theme-toggle.js")
    ));

    echo $twig->render('bandeau.html.twig');
    echo $twig->render('filtre.html.twig', array(
        'search' => $search,
        'type'   => $type,
    ));

    echo $twig->render('quoteLittle.html.twig', [
        'quotes' => $quotesPaginated,
        'titre'  => "Résultats"
    ]);
?>

<div class="pagination-container">
    <button id="prev-page" <?php if($currentPage <= 1) echo "disabled"; ?>>Page précédente</button>
    <select id="page-selector">
        <?php for($page = 1; $page <= $totalPages; $page++): ?>
            <option value="<?php echo $page; ?>" <?php if($page == $currentPage) echo "selected"; ?>>Page <?php echo $page; ?></option>
        <?php endfor; ?>
    </select>
    <button id="next-page" <?php if($currentPage >= $totalPages) echo "disabled"; ?>>Page suivante</button>
    <div class="spinner" id="spinner"></div>
</div>

<script>
document.getElementById('page-selector').addEventListener('change', function() {
    document.getElementById('spinner').style.display = 'inline-block';
    window.location.href = "?page=" + this.value;
});

document.getElementById('prev-page').addEventListener('click', function() {
    var selector = document.getElementById('page-selector');
    var newPage = parseInt(selector.value) - 1;
    if(newPage >= 1) {
        document.getElementById('spinner').style.display = 'inline-block';
        window.location.href = "?page=" + newPage;
    }
});

document.getElementById('next-page').addEventListener('click', function() {
    var selector = document.getElementById('page-selector');
    var newPage = parseInt(selector.value) + 1;
    if(newPage <= <?php echo $totalPages; ?>) {
        document.getElementById('spinner').style.display = 'inline-block';
        window.location.href = "?page=" + newPage;
    }
});
</script>

<?php
    echo "</div>";
    //echo $twig->render('resultat.html.twig');
?>
