<?php

require_once BASE_PATH
    . '/app/models/GalleryItem.php';


class GalleryController
{
    private GalleryItem $galleryModel;


    public function __construct()
    {
        $this->galleryModel =
            new GalleryItem();
    }


    public function index(): void
    {
        $category =
            trim(
                $_GET['category']
                ?? ''
            );


        $categories =
            $this->galleryModel
                ->getVisibleCategories();


        if (
            $category !== ''
            && !in_array(
                $category,
                $categories,
                true
            )
        ) {

            $category = '';
        }


        $page =
            max(
                1,
                (int)
                ($_GET['page']
                    ?? 1)
            );


        $perPage = 20;


        $totalItems =
            $this->galleryModel
                ->countVisible(
                    $category
                );


        $totalPages =
            max(
                1,
                (int)
                ceil(
                    $totalItems
                    / $perPage
                )
            );


        $page =
            min(
                $page,
                $totalPages
            );


        $galleryItems =
            $this->galleryModel
                ->getVisible(
                    $category,
                    $perPage,
                    ($page - 1)
                    * $perPage
                );


        require BASE_PATH
            . '/app/views/gallery/index.php';
    }
}