<?php
/**
 * Project-Pro Blog — Admin Categories Controller
 *
 * @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';

class AdminProjectproBlogCategoriesController extends ModuleAdminController
{
    public function __construct()
    {
        $this->bootstrap  = true;
        $this->table      = 'projectproblog_category';
        $this->className  = 'BlogCategory';
        $this->lang       = true;
        $this->identifier = 'id_category';

        $this->_defaultOrderBy  = 'position';
        $this->_defaultOrderWay = 'ASC';

        parent::__construct();

        // JOIN musi być po parent::__construct() — wtedy $this->context jest już dostępny
        $this->_join =
            'LEFT JOIN `' . _DB_PREFIX_ . 'projectproblog_category_lang` parent_lang
                ON (a.`id_parent` = parent_lang.`id_category`
                    AND parent_lang.`id_lang` = ' . (int) $this->context->language->id . ')';

        $this->_select = 'parent_lang.`name` AS parent_name';

        $this->addRowAction('edit');
        $this->addRowAction('delete');

        /* -------------------------------------------------------- */
        /*  Lista                                                     */
        /* -------------------------------------------------------- */
        $this->fields_list = [
            'id_category' => [
                'title' => $this->l('ID'),
                'align' => 'center',
                'class' => 'fixed-width-xs',
            ],
            'name' => [
                'title'      => $this->l('Nazwa'),
                'filter_key' => 'b!name',
            ],
            'parent_name' => [
                'title'  => $this->l('Kategoria nadrzędna'),
                'search' => false,
            ],
            'position' => [
                'title' => $this->l('Pozycja'),
                'align' => 'center',
                'class' => 'fixed-width-xs',
            ],
            'active' => [
                'title'  => $this->l('Aktywna'),
                'active' => 'status',
                'type'   => 'bool',
                'align'  => 'center',
                'class'  => 'fixed-width-sm',
            ],
        ];

        /* -------------------------------------------------------- */
        /*  Formularz                                                 */
        /* -------------------------------------------------------- */
        $this->fields_form = [
            'legend' => [
                'title' => $this->l('Kategoria bloga'),
                'icon'  => 'icon-folder',
            ],
            'input' => [
                [
                    'type'    => 'select',
                    'label'   => $this->l('Kategoria nadrzędna'),
                    'name'    => 'id_parent',
                    'options' => [
                        'query' => BlogCategory::getCategoriesForSelect(
                            $this->context->language->id,
                            (int) Tools::getValue('id_category')
                        ),
                        'id'   => 'id_category',
                        'name' => 'name',
                    ],
                    'hint' => $this->l('Zostaw "brak" jeśli to kategoria główna.'),
                ],
                [
                    'type'     => 'switch',
                    'label'    => $this->l('Aktywna'),
                    'name'     => 'active',
                    'required' => false,
                    'is_bool'  => true,
                    'values'   => [
                        ['id' => 'active_on',  'value' => 1, 'label' => $this->l('Tak')],
                        ['id' => 'active_off', 'value' => 0, 'label' => $this->l('Nie')],
                    ],
                ],
                [
                    'type'  => 'text',
                    'label' => $this->l('Pozycja'),
                    'name'  => 'position',
                    'class' => 'fixed-width-xs',
                    'hint'  => $this->l('Kolejność na liście (mniejsza liczba = wyżej).'),
                ],
                [
                    'type'     => 'text',
                    'label'    => $this->l('Nazwa'),
                    'name'     => 'name',
                    'lang'     => true,
                    'required' => true,
                    'hint'     => $this->l('Nazwa wyświetlana na stronie.'),
                ],
                [
                    'type'     => 'text',
                    'label'    => $this->l('Przyjazny URL (slug)'),
                    'name'     => 'link_rewrite',
                    'lang'     => true,
                    'required' => true,
                    'hint'     => $this->l('Tylko małe litery, cyfry i myślniki. Generowany automatycznie z nazwy.'),
                ],
                [
                    'type'  => 'textarea',
                    'label' => $this->l('Opis'),
                    'name'  => 'description',
                    'lang'  => true,
                    'rows'  => 5,
                ],
                [
                    'type'  => 'text',
                    'label' => $this->l('Meta title'),
                    'name'  => 'meta_title',
                    'lang'  => true,
                ],
                [
                    'type'  => 'text',
                    'label' => $this->l('Meta keywords'),
                    'name'  => 'meta_keywords',
                    'lang'  => true,
                    'hint'  => $this->l('Słowa kluczowe oddzielone przecinkami.'),
                ],
                [
                    'type'  => 'textarea',
                    'label' => $this->l('Meta description'),
                    'name'  => 'meta_description',
                    'lang'  => true,
                    'rows'  => 3,
                ],
            ],
            'submit' => [
                'title' => $this->l('Zapisz'),
            ],
        ];
    }

    /* ------------------------------------------------------------------ */
    /*  Zapis — auto-generowanie slug z nazwy                              */
    /* ------------------------------------------------------------------ */

    public function processSave()
    {
        $languages = Language::getLanguages(false);

        foreach ($languages as $lang) {
            $idLang    = (int) $lang['id_lang'];
            $name      = Tools::getValue('name_' . $idLang);
            $slug      = Tools::getValue('link_rewrite_' . $idLang);

            // jeśli slug pusty — wygeneruj z nazwy
            if (empty(trim((string) $slug)) && !empty(trim((string) $name))) {
                $_POST['link_rewrite_' . $idLang] = Tools::link_rewrite($name);
            }
        }

        return parent::processSave();
    }

    /* ------------------------------------------------------------------ */
    /*  Toggle active (kliknięcie boolki na liście)                        */
    /* ------------------------------------------------------------------ */

    public function processStatus()
    {
        $cat = new BlogCategory((int) Tools::getValue($this->identifier));
        if (!Validate::isLoadedObject($cat)) {
            $this->errors[] = $this->l('Nie znaleziono kategorii.');
            return false;
        }

        $cat->active = !(bool) $cat->active;

        return (bool) $cat->update();
    }
}
