<?php

$arrMusic = [
    'Открываем',
    'набор',
    'на',
    'оплачиваемую',
    'стажировку',
    'Вы',
    'спрашивали',
    'вы',
    'ждали',
    'и',
    'вот',
    'мы',
    'возвращаемся',
    'с',
    'анонсом',
    'стажировки',
    'для',
    'разработчиков!',
    '6 месяцев',
];

class Page {
    public string $html = "";
    public string $feed = "";
    public string $paginator = "";
    // ... другие свойства

    public function __construct() {} // Пустой конструктор

    public function __toString(): string {
        return $this->html;
    }
}


interface PageBuilder {
    public function setFeed();
    public function setPaginator();
//    ... другие методы для установки свойств
    public function build();
}

//implements PageBuilder {
class MusicPageBuilder  implements PageBuilder {

    private Page $page;

    const LIMIT = 5;
    const OFFSET = 0;
    private $data = [];
    private $limit = Null;
    private $offset = Null;
    private $flag = 'ajax';


    public function __construct($data, $flag = 'ajax' ) {

        $this->page = new Page();
        $this->flag = $flag; 
        $this->data = $data;
        $this->limit = isset($_GET['limit'])? $_GET['limit'] : self::LIMIT;
        $this->offset = isset($_GET['offset']) ? $_GET['offset']: self::OFFSET;
    }

    public function setFeed(){
        $portial = array_slice($this->data, $this->offset, $this->limit);
        $this->page->feed ='<ul id="feed">';
        foreach ( $portial as $val ) {
            $this->page->feed .= "<li> $val</li>";
        }
        $this->page->feed .= '</ul>';
        return $this;
    }

    public function setPaginator(){
        $len = sizeof($this->data);
        $contPage = intdiv($len, $this->limit);
        for ($i = 0; $i < $contPage; $i++ ) {
            $this->page->paginator .= '<a href="portial.php?offset='.self::LIMIT*$i.
            '&limit='. self::LIMIT .'">'. $i. '</a>&nbsp; ';
        }
        return $this;
    }

    public function build(){
        $feed = $this->page->feed;
        $paginator = $this->page->paginator;
        $pg =  ($this->flag == 'ajax')?$feed: $paginator;
        $this->page->html =  <<< EOF
         <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>Document</title>
        </head>
        <body> 
             $pg 
          
            <button id="paginator" data-id=1 type="button" ">Далее...</button>
        </body>

        </html>

        <script>

           async function getFetch(url) {
              const response = await fetch(url, { method:'get'} )
              return await response.text(); 

           }
           async function getPage(event) {
             event.stopPropagation()
             event.preventDefault()
            
            let num_page = event.target.getAttribute('data-id')
            console.log(num_page)
            let limit = 5
            url = 'portial.php?offset=' + limit*num_page +'&limit=' + limit
            console.log(url)
            let data = await getFetch(url)
            if (!data) event.target.remove()
            feed = document.getElementById('feed')
            feed.innerHTML = feed.innerHTML + data
            event.target.setAttribute('data-id', parseInt(num_page) + 1)  
            
          }
       
           const parent = document.getElementById('paginator')
           parent.addEventListener('click' , getPage )
       
        </script>

        EOF;
        return $this->page;
    }

}

// Клиентский код
$builder = new MusicPageBuilder($arrMusic);
$page = $builder->setFeed()->setPaginator()->build();
echo $page . PHP_EOL;

// $p = new Paginator($arrMusic);
// $p->renderFeed();
// $p->renderPaginator();
// $p->renderPage();
