<?php

namespace TwigExtension;

use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;
use Helpers\Trad\ITrad;
use Helpers\Trad\Trad;
use Psr\Container\ContainerInterface;

class PaginationExtension extends AbstractExtension
{
    
    /** @phpstan-ignore-next-line */
    private readonly ITrad $trad;
    
    public function __construct(ContainerInterface $contenaire)
    {
        $this->trad = $contenaire->get(ITrad::class);
    }

    public function getFunctions()
    {
        return [
            new TwigFunction('paginations', $this->paginations(...), [
                'is_safe' => [
                    'html'
                ]
            ])
        ];
    }
    
    /**
     * paginations
     *
     * @param  string $path
     * @param  string $params
     * @param  string $div
     * @param  string|int|null $pageActuelle
     * @param  string|int|null $maxPage
     * @param  string|int|null $totalArticle
     */
    public function paginations(?string $path = null, ?int $totalPages = null, $pageActuelle = null, ?string $params = null, ?string $div = null, $maxPage = 0, $totalArticle = 0, string $idPagination = ''): string
    {

        $html = '';

        if ($totalArticle >= 1000) {
            $totalPages = $maxPage;
            if ($pageActuelle == $maxPage) {
                $html = "
                <div class='msg_pagination'>
                    <span>".Trad::strBuild($this->trad->t('Votre recherche a plus de @1@ résultats, veuillez affiner votre recherche.'), $totalArticle)."</span>
                </div>";
            }
        }

        if ($totalPages > 1) {
            $html .= "
            <div class='containers'>
                <nav aria-label='Page navigation'>
                    <ul class='pagination' id='pagination$idPagination'></ul>
                </nav>
            </div>
            <script type='text/javascript'>
                $('#pagination$idPagination').twbsPagination({
                    totalPages: " . $totalPages . ",
                    visiblePages: 5,
                    startPage : " . $pageActuelle . ",
                    next : '>',
                    prev : '<',
                    last : '>>',
                    first : '<<',
                    initiateStartPageClick : false,
                    onInit: function () {
                        // fire first page loading
                    },
                    onPageClick: function (event, page) {
                        ";

            if ($params != '') {
                $params .= ',\'page\' : page';
            } else {
                $params = '\'page\' : page';
            }

            /*if ($oldPost != '') {
                $params .= ',\'oldPost\' : \''.$oldPost.'\' ';
            }*/
            if ($div != null) {
                $html .= '
                                    activeLoader();
                                    $.ajax({
                                        url: \'' . $path . '\',      
                                        type: \'POST\',                   
                                        dataType: \'html\',                 
                                        data: {' . $params . '},                 
                                        success: function (htmlData) { 
                                            var result = $(\'<div />\').append(htmlData).find("#' . $div . '").html();
                                            if(result)
                                            {
                                                let $div = $("#'.$div.'");
                                                $div.html(result);
                                                if(typeof $div.find(\'.table\')[0] !== \'undefined\' )
                                                {
                                                    $div.find(\'.table\')[0].scrollIntoView({
                                                        behavior: "smooth",
                                                        block: "start",
                                                    });
                                                }
                                            }
                                            else                                       	
                                            {
                                                $( \'#' . $div . '\' ).replaceWith( $("#' . $div . '").html(htmlData));

                                            }   
                                            ' . ($div == 'modal-body' ? '' : '
                                                $(\'html, body\').animate({
                                                    scrollTop: $("#' . $div . '").offset().top
                                                }, 1);
                                            ') . '

                                            // colorTrTable("#' . $div . '");
                                            desactiveLoader();
                                        }
                                    
                                    });';
            } else {
                $html .= "var url = '" . $path . "';
                                redirectJSWithPost( url , {" . $params . "});";
            }
            $html .= "
                            }    
                        });
            
            </script>";
        }

        return $html;
    }
}
