<?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\SellerinfoRating;
use PrestaShop\PrestaShop\Core\Product\Search\Pagination;

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

class AgileMultiSellerProMyReviewsModuleFrontController extends AgileModuleFrontController
{
    public function setMedia()
    {
        parent::setMedia();

        Media::addJsDef([
            'asr_pleaseenterreply' => $this->trans(
                'Please entery your reply message', [], 'Modules.Agilemultisellerpro.Raitings'
            ),
        ]);

        $this->registerJavascript(
            'asr-ratingform-js',
            '/modules/agilemultisellerpro/views/js/front/myreview.js',
            ['position' => 'bottom', 'priority' => 100]
        );

        $this->registerJavascript(
            'agile_sellerpage',
            '/modules/agilemultisellerpro/views/js/sellerpage.js',
            ['position' => 'bottom', 'priority' => 100]
        );
    }

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

        $this->n = (int) Tools::getValue('n');
        $this->p = (int) Tools::getValue('page');

        if ($this->p <= 0) {
            $this->p = 1;
        }

        if ($this->n <= 0) {
            $this->n = max(1, (int) Configuration::get('PS_PRODUCTS_PER_PAGE'));
        }

        $this->context->smarty->assign([
            'seller_tab_id' => 9,
            'reviews' => $this->entityManager->getRepository(SellerinfoRating::class)
                ->getRatingsBySellerInfo($this->sellerinfo, $this->p, $this->n),
            'pagination' => $this->getTemplateVarPagination(),
        ]);

        $this->setTemplate('module:agilemultisellerpro/views/templates/front/reviews/myreviews.tpl');
    }

    private function getTemplateVarPagination()
    {
        $totalRatingsCount = $this->entityManager->getRepository(SellerinfoRating::class)
            ->getTotalRatingsBySellerInfo($this->sellerinfo);

        $page = $this->p;
        $perPage = $this->n;

        $pagination = new Pagination();
        $pagination
            ->setPage($page)
            ->setPagesCount(
                (int) ceil($totalRatingsCount / $perPage)
            )
        ;

        $itemsShownFrom = ($perPage * ($page - 1)) + 1;
        $itemsShownTo = $perPage * $page;

        $pages = array_map(function ($link) {
            $link['url'] = $this->updateQueryString([
                'page' => $link['page'] > 1 ? $link['page'] : null,
            ]);

            return $link;
        }, $pagination->buildLinks());

        // Filter next/previous link on first/last page
        $pages = array_filter($pages, function ($page) use ($pagination) {
            if ('previous' === $page['type'] && 1 === $pagination->getPage()) {
                return false;
            }
            if ('next' === $page['type'] && $pagination->getPagesCount() === $pagination->getPage()) {
                return false;
            }

            return true;
        });

        return [
            'total_items' => $totalRatingsCount,
            'items_shown_from' => $itemsShownFrom,
            'items_shown_to' => ($itemsShownTo <= $totalRatingsCount) ? $itemsShownTo : $totalRatingsCount,
            'current_page' => $pagination->getPage(),
            'pages_count' => $pagination->getPagesCount(),
            'pages' => $pages,
            // Compare to 3 because there are the next and previous links
            'should_be_displayed' => (count($pagination->buildLinks()) > 3),
        ];
    }

    public function postProcess()
    {
        if (Tools::isSubmit('submitResponse')) {
            $sellerinfoRating = $this->entityManager
                ->getRepository(SellerinfoRating::class)
                ->find((int) Tools::getValue('idSellerinfoRating'));

            if ($sellerinfoRating) {
                $sellerinfoRating
                    ->setResponse(trim(strip_tags(Tools::getValue('response'))));

                $this->entityManager->persist($sellerinfoRating);
                $this->entityManager->flush();
            } else {
                $this->errors[] = $this->trans(
                    'Invalid review id', [], 'Modules.Agilemultisellerpro.Raitings'
                );
            }
        }
    }
}
