<?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
 */
declare(strict_types=1);

namespace PrestaShop\Module\AgileMultisellerPro\Repository;

use Doctrine\ORM\EntityRepository;
use PrestaShop\Module\AgileMultisellerPro\Form\Configuration\Membership\DataConfiguration as MembershipDataConfiguration;
use PrestaShop\Module\AgileMultisellerPro\Helper\AgileHelper;

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

class SellerInfoCategoryRepository extends EntityRepository
{
    /**
     * @param int $idSellerinfo
     *
     * @return array
     */
    public function getSellerIdsCategories(int $idSellerinfo = 0): array
    {
        $idsCategories = [];

        /** @var QueryBuilder $qb */
        $qb = $this->createQueryBuilder('sic')
            ->select('sic.idCategory')
            ->andWhere('sic.sellerInfo = :idSellerinfo')
            ->setParameter('idSellerinfo', $idSellerinfo);

        foreach ($qb->getQuery()->getScalarResult() as $sellerCategory) {
            $idsCategories[] = (int) $sellerCategory['idCategory'];
        }

        return $idsCategories;
    }

    public function getSellerCategories(int $idSellerinfo = 0, $isMembership = false): array
    {
        $categories = [];

        $context = \Context::getContext();
        $idLang = (int) $context->language->id;

        $sql = 'SELECT c.id_category, c.id_parent, cl.name
            FROM ' . _DB_PREFIX_ . 'category c
                INNER JOIN ' . _DB_PREFIX_ .
                'sellerinfo_category sic ON (c.id_category=sic.id_category AND (IFNULL(sic.id_sellerinfo, 0)=0 ' .
                'OR IFNULL(sic.id_sellerinfo ,0)=' . (int) $idSellerinfo . '))
                LEFT JOIN ' . _DB_PREFIX_ .
                'category_lang cl ON (c.id_category=cl.id_category AND cl.id_lang=' . (int) $idLang .
                ' AND cl.id_shop=' . (int) $context->shop->id . ')
                WHERE c.id_category > 1
                    AND active = 1
        ';

        if ((int) \Configuration::get('AGILE_MS_ALLOW_REGISTER_ATHOME') != 1) {
            $sql .= ' AND c.id_category != 2';
        }

        if (false === $isMembership) {
            $sql .= ' AND c.id_category != ' . (int) \Configuration::get(MembershipDataConfiguration::AGILE_MEMBERSHIP_CID);
        }

        $categories = [];

        if ($caterows = \Db::getInstance()->ExecuteS($sql)) {
            foreach ($caterows as $category) {
                $categories[$category['id_category']] = $category;

                $categories += $this->getChildrenCategories($category['id_category'], $idLang);
            }
        }

        $categories = AgileHelper::getSortedFullnameCategory($categories);

        return array_column($categories, 'name', 'id_category');
    }

    private function getChildrenCategories($id_category, $idLang)
    {
        $categories = [];

        if ($childrenCategories = \Category::getChildren((int) $id_category, $idLang)) {
            foreach ($childrenCategories as $category) {
                $category['id_parent'] = $id_category;
                $categories[$category['id_category']] = $category;
                $categories += $this->getChildrenCategories($category['id_category'], $idLang);
            }
        }

        return $categories;
    }
}
