<?php
/**
 * Project-Pro Blog — BlogCategory ObjectModel
 *
 * @author    Project-Pro <https://www.project-pro.pl>
 * @copyright 2024 Project-Pro
 */

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

class BlogCategory extends ObjectModel
{
    /** @var int */
    public $id_parent = 0;

    /** @var bool */
    public $active = true;

    /** @var int */
    public $position = 0;

    /** @var string */
    public $date_add;

    /** @var string */
    public $date_upd;

    // --- multilang ---

    /** @var string */
    public $name;

    /** @var string */
    public $description;

    /** @var string */
    public $link_rewrite;

    /** @var string */
    public $meta_title;

    /** @var string */
    public $meta_keywords;

    /** @var string */
    public $meta_description;

    public static $definition = [
        'table'     => 'projectproblog_category',
        'primary'   => 'id_category',
        'multilang' => true,
        'fields'    => [
            // główna tabela
            'id_parent' => ['type' => self::TYPE_INT,  'validate' => 'isUnsignedInt'],
            'active'    => ['type' => self::TYPE_BOOL, 'validate' => 'isBool'],
            'position'  => ['type' => self::TYPE_INT,  'validate' => 'isUnsignedInt'],
            'date_add'  => ['type' => self::TYPE_DATE, 'validate' => 'isDate'],
            'date_upd'  => ['type' => self::TYPE_DATE, 'validate' => 'isDate'],

            // multilang
            'name'             => ['type' => self::TYPE_STRING, 'lang' => true, 'validate' => 'isGenericName',  'required' => true, 'size' => 255],
            'description'      => ['type' => self::TYPE_HTML,   'lang' => true, 'validate' => 'isCleanHtml'],
            'link_rewrite'     => ['type' => self::TYPE_STRING, 'lang' => true, 'validate' => 'isLinkRewrite',  'required' => true, 'size' => 255],
            'meta_title'       => ['type' => self::TYPE_STRING, 'lang' => true, 'validate' => 'isGenericName',  'size' => 255],
            'meta_keywords'    => ['type' => self::TYPE_STRING, 'lang' => true, 'validate' => 'isGenericName',  'size' => 255],
            'meta_description' => ['type' => self::TYPE_STRING, 'lang' => true, 'validate' => 'isGenericName',  'size' => 512],
        ],
    ];

    /**
     * Zwraca płaską listę kategorii do selecta w formularzu.
     * Format: [['id_category' => x, 'name' => '...'], ...]
     */
    public static function getCategoriesForSelect($idLang, $currentId = 0)
    {
        $rows = Db::getInstance()->executeS(
            'SELECT c.`id_category`, cl.`name`
             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` != ' . (int) $currentId . '
             ORDER BY cl.`name` ASC'
        );

        $result = [['id_category' => 0, 'name' => '— brak (kategoria główna) —']];
        if (is_array($rows)) {
            $result = array_merge($result, $rows);
        }

        return $result;
    }

    /**
     * Zwraca drzewo kategorii do wyświetlenia na froncie.
     * Wynik: tablica zagnieżdżona ['category' => [...], 'children' => [...]]
     */
    public static function getCategoryTree($idLang, $idParent = 0)
    {
        $rows = Db::getInstance()->executeS(
            'SELECT c.`id_category`, c.`id_parent`, c.`position`, 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.`active` = 1
             ORDER BY c.`position` ASC, cl.`name` ASC'
        );

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

        // indeks po id_parent
        $byParent = [];
        foreach ($rows as $row) {
            $byParent[(int) $row['id_parent']][] = $row;
        }

        return self::buildTree($byParent, $idParent);
    }

    private static function buildTree(array $byParent, $parentId)
    {
        if (!isset($byParent[$parentId])) {
            return [];
        }

        $tree = [];
        foreach ($byParent[$parentId] as $cat) {
            $tree[] = [
                'category' => $cat,
                'children' => self::buildTree($byParent, (int) $cat['id_category']),
            ];
        }

        return $tree;
    }

    /**
     * Pobiera kategorię po link_rewrite dla bieżącego języka.
     */
    public static function getByLinkRewrite($linkRewrite, $idLang)
    {
        $row = Db::getInstance()->getRow(
            'SELECT c.`id_category`
             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 cl.`link_rewrite` = \'' . pSQL($linkRewrite) . '\' AND c.`active` = 1'
        );

        if (!$row) {
            return null;
        }

        return new BlogCategory((int) $row['id_category'], $idLang);
    }
}
