<?php

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

require_once BASE_PATH
    . '/app/models/ProductCategory.php';
require_once BASE_PATH
    . '/app/models/ProductReview.php';

class ProductController
{
    private Product $productModel;

    private ProductCategory $categoryModel;


    public function __construct()
    {
        $this->productModel =
            new Product();

        $this->categoryModel =
            new ProductCategory();
    }


    /**
     * Danh sách sản phẩm.
     */
    public function index(): void
    {
        $categories =
            $this->categoryModel
                ->getActiveCategories();


        $categorySlug =
            trim(
                $_GET['category']
                ?? ''
            );


        $currentCategory = null;

        $categoryId = null;


        if ($categorySlug !== '') {

            $currentCategory =
                $this->categoryModel
                    ->findBySlug(
                        $categorySlug
                    );


            if ($currentCategory) {

                $categoryId =
                    (int)
                    $currentCategory['id'];
            }
        }


        $search =
            trim(
                $_GET['search']
                ?? ''
            );


        $pet =
            $_GET['pet']
            ?? '';


        if (
            !in_array(
                $pet,
                [
                    '',
                    'dog',
                    'cat'
                ],
                true
            )
        ) {

            $pet = '';
        }


        $sort =
            $_GET['sort']
            ?? 'newest';


        $allowedSorts = [
            'newest',
            'price_asc',
            'price_desc',
            'best_selling',
            'name_asc'
        ];


        if (
            !in_array(
                $sort,
                $allowedSorts,
                true
            )
        ) {

            $sort = 'newest';
        }


        $minPrice =
            $_GET['min_price']
            ?? '';


        $maxPrice =
            $_GET['max_price']
            ?? '';


        $filters = [

            'search' =>
                $search,

            'category_id' =>
                $categoryId,

            'pet' =>
                $pet,

            'min_price' =>
                $minPrice,

            'max_price' =>
                $maxPrice,

            'sort' =>
                $sort
        ];


        // ==========================================
        // PAGINATION
        // ==========================================

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


        $perPage = 12;


        $totalProducts =
            $this->productModel
                ->countAll($filters);


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


        if ($page > $totalPages) {

            $page =
                $totalPages;
        }


        $offset =
            ($page - 1)
            * $perPage;


        $products =
            $this->productModel
                ->getAll(
                    $filters,
                    $perPage,
                    $offset
                );


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


    /**
     * Chi tiết sản phẩm.
     */
    public function detail(): void
    {
        $slug =
            trim(
                $_GET['slug']
                ?? ''
            );


        if ($slug === '') {

            $this->notFound();

            return;
        }


        $product =
            $this->productModel
                ->findBySlug($slug);


        if (!$product) {

            $this->notFound();

            return;
        }

$reviewModel =
    new ProductReview();


$reviewSummary =
    $reviewModel
        ->getSummary(
            (int)
            $product['id']
        );


$reviews =
    $reviewModel
        ->getVisibleForProduct(
            (int)
            $product['id'],
            20
        );
        $productImages =
            $this->productModel
                ->getImages(
                    (int)
                    $product['id']
                );


        $relatedProducts =
            $this->productModel
                ->getRelatedProducts(

                    (int)
                    $product['category_id'],

                    (int)
                    $product['id'],

                    4
                );


        require BASE_PATH
            . '/app/views/products/detail.php';
    }


    private function notFound(): void
    {
        http_response_code(404);

        require BASE_PATH
            . '/app/views/errors/404.php';
    }
}