<?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\Sellerinfo;
use PrestaShop\Module\AgileMultisellerPro\Entity\SellerinfoRating;
use PrestaShop\Module\AgileMultisellerPro\Entity\SellerinfoRatingCriterion;
use PrestaShop\Module\AgileMultisellerPro\Entity\SellerinfoRatingGrade;

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

class AgileMultiSellerProFeedbackWaitlistModuleFrontController extends AgileModuleFrontController
{
    public $auth = true;
    public $ssl = true;

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

        Media::addJsDef([
            'asr_pleaseentercomment' => $this->trans(
                'Please enter your comment', [], 'Modules.Agilemultisellerpro.Raitings'
            ),
            'asr_pleaseenterrating' => $this->trans(
                'Please select your rating', [], 'Modules.Agilemultisellerpro.Raitings'
            ),
        ]);

        $this->registerJavascript(
            'asr-ratingform-js',
            '/modules/agilemultisellerpro/views/js/front/ratingform.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->context->smarty->assign([
            'criterions' => $this->getCriterions(),
            'agileFeedbacks' => $this->entityManager
                ->getRepository(SellerinfoRating::class)
                ->getFeedbackWaitingList((int) $this->context->customer->id, (int) $this->context->language->id, true),
        ]);

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

    protected function getCriterions()
    {
        $criterions = [];
        $sellerinfoRatingCriterionRepository = $this->entityManager->getRepository(SellerinfoRatingCriterion::class);

        $idLang = (int) $this->context->language->id;

        foreach ($sellerinfoRatingCriterionRepository->findAll() as $sellerinfoRatingCriterion) {
            $criterions[] = [
                'id_sellerinfo_rating_criterion' => $sellerinfoRatingCriterion->getIdSellerinfoRatingCriterion(),
                'name' => $sellerinfoRatingCriterion->getLangByLangId($idLang)->getName(),
            ];
        }

        return $criterions;
    }

    public function postProcess()
    {
        if (Tools::isSubmit('submitFeedback')) {
            $idCustomer = (int) $this->context->customer->id;
            $idOrder = (int) Tools::getValue('rating_id_order');
            $sellerinfoRatingRepository = $this->entityManager->getRepository(SellerinfoRating::class);

            if (
                $idOrder > 0
                && !$sellerinfoRatingRepository->findOneBy(['idOrder' => $idOrder, 'idCustomer' => $idCustomer])
            ) {
                $idSellerinfo = (int) Tools::getValue('rating_id_sellerinfo');

                $sellerInfo = $this->entityManager->getRepository(Sellerinfo::class)->find($idSellerinfo);

                if ($sellerInfo) {
                    $sellerinfoRating = new SellerinfoRating();

                    $sellerinfoRating->setSellerinfo($sellerInfo)
                        ->setIdOrder($idOrder)
                        ->setIdLang((int) $this->context->language->id)
                        ->setIdCustomer($idCustomer)
                        ->setCustomer($this->getFormatNameByCustomer($idCustomer))
                        ->setContent(strip_tags(Tools::getValue('content')))
                        ->setIpAddress($_SERVER['REMOTE_ADDR'])
                    ;

                    $sellerinfoRatingCriterionRepository = $this->entityManager->getRepository(SellerinfoRatingCriterion::class);

                    foreach ($sellerinfoRatingCriterionRepository->findAll() as $sellerinfoRatingCriterion) {
                        $idSellerinfoRatingCriterion = $sellerinfoRatingCriterion->getIdSellerinfoRatingCriterion();
                        $sellerinfoRatingGrade = new SellerinfoRatingGrade();

                        $sellerinfoRatingGrade->setSellerinfoRatingCriterion($sellerinfoRatingCriterion)
                            ->setGrade((int) Tools::getValue($idSellerinfoRatingCriterion . '_rating_grade'))
                        ;

                        $sellerinfoRating->addSellerinfoRatingGrade($sellerinfoRatingGrade);
                    }

                    $this->entityManager->persist($sellerinfoRating);
                    $this->entityManager->flush();
                }
            }
        }
    }

    public function getFormatNameByCustomer($idCustomer)
    {
        $customer = new Customer($idCustomer);

        if (Validate::isLoadedObject($customer)) {
            return $customer->firstname . ' ' . strtoupper(substr($customer->lastname, 0, 1)) . '.';
        } else {
            return '';
        }
    }
}
