<?php
/**
 * Project-Pro Blog — Front controller: szczegół wpisu
 *
 * @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 ProjectproblogPostModuleFrontController extends ModuleFrontController
{
    public $php_self = 'post';

    /** @var BlogPost|null */
    protected $post = null;

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

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

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

        if ($this->slug === '') {
            Tools::redirect('index.php?controller=404');
        }

        $this->post = BlogPost::getByLinkRewrite($this->slug, $idLang);

        if (!$this->post) {
            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;

        // Kategorie wpisu z URL-ami
        $categoryIds  = BlogPost::getCategories((int) $this->post->id);
        $postCats     = $this->loadCategories($categoryIds, $idLang);

        // Pierwsza kategoria (do breadcrumba)
        $primaryCat = !empty($postCats) ? $postCats[0] : null;

        // URL miniaturki
        $thumbnailUrl = $this->post->getThumbnailUrl();

        // Powiązane data_upd — wyświetl tylko gdy różni się od data_add
        $showUpdated = $this->post->date_upd
            && substr($this->post->date_upd, 0, 10) !== substr($this->post->date_add, 0, 10);

        // Drzewo kategorii do sidebara
        $categoryTree = $this->enrichCategoryTree(
            BlogCategory::getCategoryTree($idLang),
            $idLang
        );

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

        $this->context->smarty->assign([
            'blog_post'           => $this->post,
            'blog_post_cats'      => $postCats,
            'blog_primary_cat'    => $primaryCat,
            'blog_thumbnail'      => $thumbnailUrl,
            'blog_show_updated'   => $showUpdated,
            'blog_url'            => Projectproblog::getBlogUrl($idLang),
            'blog_category_tree'  => $categoryTree,
            'blog_current_cat'    => null,
        ]);

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

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

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

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

        // Jeśli wpis ma kategorię — dodaj ją do breadcrumba
        if ($this->post) {
            $idLang      = (int) $this->context->language->id;
            $categoryIds = BlogPost::getCategories((int) $this->post->id);

            if (!empty($categoryIds)) {
                $catRow = Db::getInstance()->getRow(
                    'SELECT cl.`name`, cl.`link_rewrite`
                     FROM `' . _DB_PREFIX_ . 'projectproblog_category_lang` cl
                     WHERE cl.`id_category` = ' . (int) $categoryIds[0] . '
                       AND cl.`id_lang` = ' . (int) $idLang
                );

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

            $breadcrumb['links'][] = [
                'title' => $this->post->title,
                'url'   => '',
            ];
        }

        return $breadcrumb;
    }

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

    /**
     * Wyłącza canonical redirection — patrz komentarz w list.php.
     */
    protected function canonicalRedirection($canonical_url = '')
    {
    }

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

    /**
     * Rekurencyjnie dodaje url do węzłów drzewa kategorii (sidebar).
     */
    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;
    }

    /**
     * Pobiera dane kategorii po ID-kach i dodaje URL-e.
     */
    protected function loadCategories(array $categoryIds, $idLang)
    {
        if (empty($categoryIds)) {
            return [];
        }

        $idList = implode(',', array_map('intval', $categoryIds));

        $rows = Db::getInstance()->executeS(
            'SELECT c.`id_category`, cl.`name`, cl.`link_rewrite`
             FROM `' . _DB_PREFIX_ . 'projectproblog_category` c
             LEFT JOIN `' . _DB_PREFIX_ . 'projectproblog_category_lang` cl
                ON c.`id_category` = cl.`id_category` AND cl.`id_lang` = ' . (int) $idLang . '
             WHERE c.`id_category` IN (' . $idList . ') AND c.`active` = 1
             ORDER BY cl.`name` ASC'
        );

        if (!is_array($rows)) {
            return [];
        }

        foreach ($rows as &$row) {
            $row['url'] = Projectproblog::getCategoryUrl($row['link_rewrite'], $idLang);
        }
        unset($row);

        return $rows;
    }

    /**
     * Ustawia meta title / description / keywords dla layoutu.
     */
    protected function setPageMeta()
    {
        if (!$this->post) {
            return;
        }

        $metaTitle = $this->post->meta_title ?: $this->post->title;
        $metaDesc  = $this->post->meta_description ?: '';
        $metaKw    = $this->post->meta_keywords ?: '';

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

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

        $page['meta']['title']       = $metaTitle;
        $page['meta']['description'] = $metaDesc;
        $page['meta']['keywords']    = $metaKw;

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