<?php
/**
 * For the full copyright and license information, please view the
 * docs/licenses/LICENSE.txt file that was distributed with this source code.
 */
use PrestaShop\PrestaShop\Adapter\Presenter\Supplier\SupplierPresenter;
use PrestaShop\PrestaShop\Adapter\Supplier\SupplierProductSearchProvider;
use PrestaShop\PrestaShop\Core\Product\Search\ProductSearchQuery;
use PrestaShop\PrestaShop\Core\Product\Search\SortOrder;

class SupplierControllerCore extends ProductListingFrontController
{
    /** @var string */
    public $php_self = 'supplier';

    /** @var Supplier|null */
    protected $supplier;

    /** @var SupplierPresenter */
    protected $supplierPresenter;

    public function canonicalRedirection(string $canonicalURL = ''): void
    {
        if (Validate::isLoadedObject($this->supplier)) {
            parent::canonicalRedirection($this->context->link->getSupplierLink($this->supplier));
        } elseif ($canonicalURL) {
            parent::canonicalRedirection($canonicalURL);
        }
    }

    /**
     * Returns canonical URL for current supplier or a supplier list
     *
     * @return string
     */
    public function getCanonicalURL(): string
    {
        if (Validate::isLoadedObject($this->supplier)) {
            return $this->buildPaginatedUrl($this->context->link->getSupplierLink($this->supplier));
        }

        return $this->context->link->getPageLink('supplier');
    }

    /**
     * Initialize supplier controller.
     *
     * @see FrontController::init()
     */
    public function init(): void
    {
        if ($id_supplier = (int) Tools::getValue('id_supplier')) {
            $this->supplier = new Supplier($id_supplier, $this->context->language->id);

            if (!Validate::isLoadedObject($this->supplier) || !$this->supplier->active) {
                $this->redirect_after = '404';
                $this->redirect();
            } else {
                $this->canonicalRedirection();
            }
        }

        // Initialize presenter, we will use it for all cases
        $this->supplierPresenter = new SupplierPresenter($this->context->link);

        parent::init();
    }

    /**
     * Assign template vars related to page content.
     *
     * @see FrontController::initContent()
     */
    public function initContent(): void
    {
        if (Configuration::get('PS_DISPLAY_SUPPLIERS')) {
            parent::initContent();

            if (Validate::isLoadedObject($this->supplier) && $this->supplier->active && $this->supplier->isAssociatedToShop()) {
                $this->assignSupplier();
                $this->doProductSearch(
                    'catalog/listing/supplier',
                    ['entity' => 'supplier', 'id' => $this->supplier->id]
                );
            } else {
                $this->assignAll();
                $this->setTemplate('catalog/suppliers', ['entity' => 'suppliers']);
            }
        } else {
            $this->redirect_after = '404';
            $this->redirect();
        }
    }

    /**
     * Gets the product search query for the controller. This is a set of information that
     * a filtering module or the default provider will use to fetch our products.
     *
     * @return ProductSearchQuery
     */
    protected function getProductSearchQuery(): ProductSearchQuery
    {
        $query = new ProductSearchQuery();
        $query
            ->setQueryType('supplier')
            ->setIdSupplier($this->supplier->id)
            ->setSortOrder(new SortOrder('product', 'position', 'asc'));

        return $query;
    }

    /**
     * Default product search provider used if no filtering module stood up for the job
     *
     * @return SupplierProductSearchProvider
     */
    protected function getDefaultProductSearchProvider(): SupplierProductSearchProvider
    {
        return new SupplierProductSearchProvider(
            $this->getTranslator(),
            $this->supplier
        );
    }

    /**
     * Assign template vars if displaying one supplier.
     */
    protected function assignSupplier(): void
    {
        $supplierVar = $this->supplierPresenter->present(
            $this->supplier,
            $this->context->language
        );

        // Chained hook call - if multiple modules are hooked here, they will receive the result of the previous one as a parameter
        $filteredSupplier = Hook::exec(
            'filterSupplierContent',
            ['object' => $supplierVar],
            null,
            false,
            true,
            false,
            null,
            true
        );
        if (!empty($filteredSupplier['object'])) {
            $supplierVar = $filteredSupplier['object'];
        }

        $this->context->smarty->assign([
            'supplier' => $supplierVar,
        ]);
    }

    /**
     * Assign template vars if displaying the supplier list.
     */
    protected function assignAll(): void
    {
        $suppliersVar = $this->getTemplateVarSuppliers();

        if (!empty($suppliersVar)) {
            foreach ($suppliersVar as $k => $supplier) {
                // Chained hook call - if multiple modules are hooked here, they will receive the result of the previous one as a parameter
                $filteredSupplier = Hook::exec(
                    'filterSupplierContent',
                    ['object' => $supplier],
                    null,
                    false,
                    true,
                    false,
                    null,
                    true
                );
                if (!empty($filteredSupplier['object'])) {
                    $suppliersVar[$k] = $filteredSupplier['object'];
                }
            }
        }

        $this->context->smarty->assign([
            'suppliers' => $suppliersVar,
        ]);
    }

    public function getTemplateVarSuppliers(): array
    {
        $suppliers = Supplier::getSuppliers(true, $this->context->language->id, true);

        foreach ($suppliers as &$supplier) {
            $supplier = $this->supplierPresenter->present(
                $supplier,
                $this->context->language
            );
        }

        return $suppliers;
    }

    public function getListingLabel(): string
    {
        if (Validate::isLoadedObject($this->supplier) && $this->supplier->active && $this->supplier->isAssociatedToShop()) {
            return $this->trans('List of products by supplier %supplier_name%', ['%supplier_name%' => $this->supplier->name], 'Shop.Theme.Catalog');
        } else {
            return $this->trans('List of all suppliers', [], 'Shop.Theme.Catalog');
        }
    }

    public function getBreadcrumbLinks(): array
    {
        $breadcrumb = parent::getBreadcrumbLinks();
        $breadcrumb['links'][] = [
            'title' => $this->trans('Suppliers', [], 'Shop.Theme.Catalog'),
            'url' => $this->context->link->getPageLink('supplier'),
        ];

        if (!empty($this->supplier)) {
            $breadcrumb['links'][] = [
                'title' => $this->supplier->name,
                'url' => $this->context->link->getSupplierLink($this->supplier),
            ];
        }

        return $breadcrumb;
    }

    /**
     * Generates structured data this page, depending on if we are displaying a supplier or a list of suppliers.
     *
     * @return array
     */
    public function getStructuredData(): array
    {
        // If we are displaying a supplier, we will use the product listing structured data
        if (Validate::isLoadedObject($this->supplier) && $this->supplier->active && $this->supplier->isAssociatedToShop()) {
            return parent::getStructuredData();
        }

        // Otherwise, we will display the basic data, the same as in FrontController
        return FrontController::getStructuredData();
    }

    /**
     * Initializes a set of commonly used variables related to the current page, available for use
     * in the template. @see FrontController::assignGeneralPurposeVariables for more information.
     *
     * @return array
     */
    public function getTemplateVarPage(): array
    {
        $page = parent::getTemplateVarPage();

        if (!empty($this->supplier)) {
            $page['body_classes']['supplier-id-' . $this->supplier->id] = true;
            $page['body_classes']['supplier-' . $this->supplier->name] = true;
        }

        return $page;
    }

    /**
     * @return Supplier|null
     */
    public function getSupplier(): ?Supplier
    {
        return $this->supplier;
    }
}
