<?php
/**
 * 2007-2023 PrestaShop
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Academic Free License (AFL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/afl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@prestashop.com so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade PrestaShop to newer
 * versions in the future. If you wish to customize PrestaShop for your
 * needs please refer to http://www.prestashop.com for more information.
 *
 * @author    PrestaShop SA <contact@prestashop.com>
 * @copyright 2007-2023 PrestaShop SA
 * @license   http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
 *  International Registered Trademark & Property of PrestaShop SA
 */

use PrestaShop\Module\AgileMultisellerPro\Controller\Front\AgileModuleFrontController;
use PrestaShop\Module\AgileMultisellerPro\Entity\SellerinfoCategory;
use PrestaShop\Module\AgileMultisellerPro\Form\Configuration\DataConfiguration;

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

class AgileMultiSellerProAjaxAgileCategoriesModuleFrontController extends AgileModuleFrontController
{
    public $auth = false;

    /**
     * @var Product
     */
    protected $object;

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

        $action = Tools::getValue('action');

        if ($action == 'renderCategoriesTreeForProduct') {
            $this->renderCategoriesTreeForProduct();
        } elseif ($action == 'getChildrenCategories') {
            $this->getChildrenCategories();
        } elseif ($action == 'searchCategory') {
            $this->searchCategory();
        } elseif ($action == 'getParentCategoriesId') {
            $this->getParentCategoriesId();
        }

        exit;
    }

    protected function renderCategoriesTreeForProduct()
    {
        $this->object = new Product((int) Tools::getValue('id_product'));
        $id_language = (int) Context::getContext()->language->id;
        $root = Category::getRootCategory();
        $sql = 'SELECT id_category_default FROM ' . _DB_PREFIX_ .
            'product WHERE id_product=' . (int) $this->object->id;
        $default_category = (int) Db::getInstance()->getValue($sql);

        if (!$this->object->id) {
            $selected_cat = Category::getCategoryInformations(
                Tools::getValue('categoryBox', [$default_category]),
                $id_language
            );
        } else {
            if (Tools::isSubmit('categoryBox')) {
                $selected_cat = Category::getCategoryInformations(
                    Tools::getValue('categoryBox', [$default_category]),
                    $id_language
                );
            } else {
                $selected_cat = Product::getProductCategoriesFull($this->object->id, $id_language);
            }
        }

        if (!array_key_exists($default_category, $selected_cat)) {
            $sql = 'SELECT id_category, name, link_rewrite, id_lang FROM ' . _DB_PREFIX_ .
                'category_lang WHERE id_category=' . $default_category .
                ' AND id_lang=' . (int) $id_language;
            $selected_cat[$default_category] = Db::getInstance()->getRow($sql);
        }

        $tab_root = ['id_category' => $root->id, 'name' => $root->name];
        $helper = new Helper();
        $helper->bootstrap = true;

        $category_tree = $helper->renderCategoryTree(
            $tab_root,
            $selected_cat,
            'categoryBox',
            false,
            false,
            []
        );

        $category_tree = str_replace(
            '<script type="text/javascript">searchCategory();</script>',
            '',
            $category_tree
        );

        if (!headers_sent()) {
            header('Content-Type: application/json');
        }

        exit(json_encode([
            'category_tree' => $category_tree,
        ]));
    }

    protected function getChildrenCategories()
    {
        if (Tools::isSubmit('getChildrenCategories') && Tools::isSubmit('id_category_parent')) {
            $children_categories = [];

            $categories = $this->entityManager->getRepository(SellerinfoCategory::class)
                ->getSellerCategories($this->sellerinfo->getIdSellerinfo());

            if ($categories) {
                foreach ($categories as $idCategory => $categoryName) {
                    $children_categories[] = $this->makeCategory($idCategory, $categoryName);
                }
            } else {
                $defCategory = new Category(
                    Configuration::get(DataConfiguration::AGILE_MS_DEFAULT_CATEGORY),
                    $this->context->language->id
                );

                if (Validate::isLoadedObject($defCategory)) {
                    $children_categories[] = $this->makeCategory($defCategory->id, $defCategory->name);
                }
            }

            exit(json_encode($children_categories));
        }
    }

    protected function makeCategory($idCategory, $name)
    {
        return [
            'id_category' => $idCategory,
            'name' => $name,
            'level_depth' => 2,
            'has_children' => 0,
            'nbSelectedSubCat' => 0,
        ];
    }

    protected function searchCategory()
    {
        $q = Tools::getValue('q');
        $limit = Tools::getValue('limit');

        $results = Db::getInstance()->executeS(
            'SELECT c.`id_category`, cl.`name`
            FROM `' . _DB_PREFIX_ . 'category` c
            LEFT JOIN `' . _DB_PREFIX_ . 'category_lang` cl ON (c.`id_category` = cl.`id_category`' .
            Shop::addSqlRestrictionOnLang('cl') . ')
            WHERE cl.`id_lang` = ' . (int) $this->context->language->id . ' AND c.`level_depth` <> 0
            AND cl.`name` LIKE \'%' . pSQL($q) . '%\'
            GROUP BY c.id_category
            ORDER BY c.`position`
            LIMIT ' . (int) $limit
        );

        if ($results) {
            foreach ($results as $result) {
                echo trim($result['name']) . '|' . (int) $result['id_category'] . "\n";
            }
        }
    }

    protected function getParentCategoriesId()
    {
        $id_category = (int) Tools::getValue('id_category');

        $category = new Category((int) $id_category);

        $results = Db::getInstance()->executeS('SELECT `id_category` FROM `' . _DB_PREFIX_ . 'category` c
            WHERE c.`nleft` < ' . (int) $category->nleft . ' AND c.`nright` > ' . (int) $category->nright);

        foreach ($results as $result) {
            $output[] = $result;
        }

        exit(json_encode($output));
    }
}
