<?php
/**
 * Project-Pro Blog — Front controller: lista wpisów
 *
 * @author    Project-Pro <https://www.project-pro.pl>
 * @copyright 2024 Project-Pro
 */

if (!defined('_PS_VERSION_')) {
    exit;
}

require_once _PS_MODULE_DIR_ . 'projectproblog/classes/BlogCategory.php';
require_once _PS_MODULE_DIR_ . 'projectproblog/classes/BlogPost.php';

class ProjectproblogListModuleFrontController extends ModuleFrontController
{
    public $php_self = 'list';

    /** @var BlogCategory|null */
    protected $currentCategory = null;

    /** @var string */
    protected $slug = '';

    public function init()
    {
        parent::init();

        $idLang     = (int) $this->context->language->id;
        $this->slug = Tools::getValue('slug', '');

        // Jeśli podano slug kategorii — rozwiąż go
        if ($this->slug !== '') {
            $this->currentCategory = BlogCategory::getByLinkRewrite($this->slug, $idLang);
            if (!$this->currentCategory) {
                Tools::redirect('index.php?controller=404');
            }
        }
    }

    public function initContent()
    {
        parent::initContent();

        $this->registerStylesheet(
            'module-projectproblog-blog',
            'modules/projectproblog/views/css/blog.css',
            ['media' => 'all', 'priority' => 200]
        );

        $idLang     = (int) $this->context->language->id;
        $page       = max(1, (int) Tools::getValue('page', 1));
        $perPage    = Projectproblog::POSTS_PER_PAGE;
        $idCategory = $this->currentCategory ? (int) $this->currentCategory->id : null;

        // Wpisy
        $rawPosts = BlogPost::getList($idLang, $page, $perPage, $idCategory);
        $total    = BlogPost::getCount($idLang, $idCategory);
        $pages    = max(1, (int) ceil($total / $perPage));

        // Wzbogac wpisy o URL-e
        $posts = $this->enrichPosts($rawPosts, $idLang);

        // Paginacja
        $pagination = $this->buildPagination($page, $pages, $this->slug, $idLang);

        // Drzewo kategorii z URL-ami
        $categoryTree = $this->enrichCategoryTree(
            BlogCategory::getCategoryTree($idLang),
            $idLang
        );

        // Meta strony
        $this->setPageMeta($idLang);

        $this->context->smarty->assign([
            'blog_posts'           => $posts,
            'blog_category_tree'   => $categoryTree,
            'blog_current_cat'     => $this->currentCategory,
            'blog_pagination'      => $pagination,
            'blog_page'            => $page,
            'blog_pages_count'     => $pages,
            'blog_total'           => $total,
            'blog_url'             => Projectproblog::getBlogUrl($idLang),
        ]);

        $this->setTemplate('module:projectproblog/views/templates/front/list.tpl');
    }

    /* ------------------------------------------------------------------ */
    /*  Breadcrumb                                                          */
    /* ------------------------------------------------------------------ */

    public function getBreadcrumbLinks()
    {
        $breadcrumb = parent::getBreadcrumbLinks();

        $breadcrumb['links'][] = [
            'title' => $this->l('Blog'),
            'url'   => Projectproblog::getBlogUrl(),
        ];

        if ($this->currentCategory) {
            $breadcrumb['links'][] = [
                'title' => $this->currentCategory->name,
                'url'   => Projectproblog::getCategoryUrl($this->currentCategory->link_rewrite),
            ];
        }

        return $breadcrumb;
    }

    /* ------------------------------------------------------------------ */
    /*  Canonical URL                                                       */
    /* ------------------------------------------------------------------ */

    /**
     * Wyłącza canonical redirection — PS generuje błędny fallback URL
     * (bez fc=module) gdy hookModuleRoutes nie załadował tras w Dispatcher.
     */
    protected function canonicalRedirection($canonical_url = '')
    {
    }

    /* ------------------------------------------------------------------ */
    /*  Helpery prywatne                                                    */
    /* ------------------------------------------------------------------ */

    /**
     * Dodaje thumbnail_url i url do każdego wpisu.
     */
    protected function enrichPosts(array $posts, $idLang)
    {
        $base = $this->context->link->getBaseLink();

        foreach ($posts as &$post) {
            $post['thumbnail_url'] = $post['thumbnail']
                ? $base . 'modules/projectproblog/views/img/posts/' . $post['thumbnail']
                : null;

            $post['url'] = Projectproblog::getPostUrl($post['link_rewrite'], $idLang);
        }
        unset($post);

        return $posts;
    }

    /**
     * Rekurencyjnie dodaje url do węzłów drzewa kategorii.
     */
    protected function enrichCategoryTree(array $tree, $idLang)
    {
        foreach ($tree as &$node) {
            $node['category']['url'] = Projectproblog::getCategoryUrl(
                $node['category']['link_rewrite'],
                $idLang
            );
            $node['children'] = $this->enrichCategoryTree($node['children'], $idLang);
        }
        unset($node);

        return $tree;
    }

    /**
     * Buduje tablicę linków paginacji.
     * Każdy element: ['page' => int, 'url' => string, 'current' => bool]
     */
    protected function buildPagination($currentPage, $pagesCount, $slug, $idLang)
    {
        if ($pagesCount <= 1) {
            return [];
        }

        $links = [];

        for ($i = 1; $i <= $pagesCount; $i++) {
            $params = [];
            if ($slug !== '') {
                $params['slug'] = $slug;
            }
            if ($i > 1) {
                $params['page'] = $i;
            }

            $links[] = [
                'page'    => $i,
                'url'     => $this->context->link->getModuleLink(
                    'projectproblog',
                    'list',
                    $params,
                    true,
                    $idLang
                ),
                'current' => ($i === $currentPage),
            ];
        }

        // Linki poprzednia/następna
        $prev = null;
        $next = null;

        if ($currentPage > 1) {
            $params = $slug !== '' ? ['slug' => $slug] : [];
            if ($currentPage - 1 > 1) {
                $params['page'] = $currentPage - 1;
            }
            $prev = $this->context->link->getModuleLink('projectproblog', 'list', $params, true, $idLang);
        }

        if ($currentPage < $pagesCount) {
            $params = $slug !== '' ? ['slug' => $slug] : [];
            $params['page'] = $currentPage + 1;
            $next = $this->context->link->getModuleLink('projectproblog', 'list', $params, true, $idLang);
        }

        return [
            'pages' => $links,
            'prev'  => $prev,
            'next'  => $next,
        ];
    }

    /**
     * Ustawia meta title/description strony listy.
     */
    protected function setPageMeta($idLang)
    {
        if ($this->currentCategory) {
            $title = $this->currentCategory->meta_title ?: $this->currentCategory->name . ' — Blog';
            $desc  = $this->currentCategory->meta_description ?: '';
            $kw    = $this->currentCategory->meta_keywords ?: '';
        } else {
            $title = $this->l('Blog');
            $desc  = '';
            $kw    = '';
        }

        $page = $this->context->smarty->getTemplateVars('page') ?: [];

        if (!isset($page['meta'])) {
            $page['meta'] = [];
        }

        $page['meta']['title']       = $title;
        $page['meta']['description'] = $desc;
        $page['meta']['keywords']    = $kw;

        $this->context->smarty->assign('page', $page);
    }
}
