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

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

class SellerinfoRatingRepository extends EntityRepository
{
    public function getAverageBySellerInfo($sellerinfo): float
    {
        $qb = $this->createQueryBuilder('sr');

        $qb
            ->select('avg(sr.grade) AS rating')
            ->andWhere('sr.sellerInfo = :sellerinfo')
            ->setParameter('sellerinfo', $sellerinfo)
            ->groupBy('sr.sellerInfo');

        if ($result = $qb->getQuery()->getOneOrNullResult()) {
            return round((float) $result['rating'], 1);
        } else {
            return 0;
        }
    }

    public function getAveragesCriterionBySellerInfo($sellerinfo)
    {
        $averages = [];

        $qb = $this->createQueryBuilder('sr');

        $qb
            ->select('avg(srg1.grade) AS rating, srg1 as sellerinfoRatingGrade')
            ->leftJoin('sr.sellerinfoRatingGrades', 'srg')
            ->leftJoin(SellerinfoRatingGrade::class, 'srg1', 'WITH', 'srg1.sellerinfoRating = srg.sellerinfoRating')
            ->andWhere('sr.sellerInfo = :sellerinfo')
            ->setParameter('sellerinfo', $sellerinfo)
            ->groupBy('srg1.sellerinfoRatingCriterion');

        foreach ($qb->getQuery()->getResult() as $result) {
            if ($result['sellerinfoRatingGrade']) {
                $idSellerinfoRatingCriterion = $result['sellerinfoRatingGrade']->getSellerinfoRatingCriterion()->getIdSellerinfoRatingCriterion();
                $averages[$idSellerinfoRatingCriterion] = (float) $result['rating'];
            }
        }

        return $averages;
    }

    public function getRatingsBySellerInfo($sellerinfo, $p = 1, $n = 10)
    {
        $p = (int) $p;
        $n = (int) $n;

        if ($p <= 1) {
            $p = 1;
        }

        if ($n <= 0) {
            $n = 10;
        }

        $qb = $this->createQueryBuilder('sr');

        $qb->andWhere('sr.sellerInfo = :sellerinfo')
            ->setParameter('sellerinfo', $sellerinfo)
            ->orderBy('sr.dateAdd', 'DESC')
            ->setFirstResult(($p - 1) * $n)
            ->setMaxResults($n);

        $ratings = $qb->getQuery()->getArrayResult();

        foreach ($ratings as &$rating) {
            $rating['stars'] = AgileHelperRating::getStarsImages($rating['grade']);
            $rating['dateAdd'] = $rating['dateAdd']->format('Y-m-d H:i:s');
            $rating['dateUpd'] = $rating['dateUpd']->format('Y-m-d H:i:s');
        }

        return $ratings;
    }

    public function getTotalRatingsBySellerInfo($sellerinfo)
    {
        $qb = $this->createQueryBuilder('sr');

        $qb->select('COUNT(sr.idSellerinfoRating) AS count')
            ->andWhere('sr.sellerInfo = :sellerinfo')
            ->setParameter('sellerinfo', $sellerinfo);

        $ratings = $qb->getQuery()->getSingleScalarResult();

        return $ratings;
    }

    public function getFeedbackWaitingCount($idCustomer, $isPaid = false)
    {
        if ((int) $idCustomer == 0) {
            return 0;
        }

        $conn = $this->getEntityManager()->getConnection();

        $idSellerinfo = 0;
        $sellerInfo = $this->getEntityManager()->getRepository(Sellerinfo::class)->getLinkedSellerID((int) $idCustomer);

        if ($sellerInfo) {
            $idSellerinfo = $sellerInfo->getIdSellerinfo();
        }

        $sql = '
            SELECT COUNT(DISTINCT o.id_order) AS num
            FROM `' . _DB_PREFIX_ . 'orders` o
                LEFT JOIN `' . _DB_PREFIX_ . 'sellerinfo_order` sio ON (o.id_order = sio.id_order)
                LEFT JOIN `' . _DB_PREFIX_ . 'sellerinfo` s ON (sio.id_sellerinfo = s.id_sellerinfo)
                LEFT JOIN `' . _DB_PREFIX_ . 'sellerinfo_rating` sir ON (o.id_order = sir.id_order)
                ' . $this->getOrderPaidJoin($isPaid) . '
            WHERE o.id_customer = :idCustomer
                AND o.date_add >= DATE_ADD(CURDATE() , INTERVAL -120 DAY )
                AND s.id_sellerinfo != :idSellerinfo
                AND sir.id_order IS NULL
                AND IFNULL(sio.id_sellerinfo,0) > 0
                ' . $this->getOrderPaidWhere($isPaid) . '
        ';

        $res = $conn->fetchAssociative(
            $sql,
            [
                'idCustomer' => $idCustomer,
                'idSellerinfo' => $idSellerinfo,
            ]
        );

        return (isset($res['num']) && $res['num'] > 0) ? (int) $res['num'] : 0;
    }

    public function getFeedbackWaitingList($idCustomer, $idLang, $isPaid = false)
    {
        $conn = $this->getEntityManager()->getConnection();

        $idSellerinfo = 0;
        $sellerInfo = $this->getEntityManager()->getRepository(Sellerinfo::class)->getLinkedSellerID((int) $idCustomer);

        if ($sellerInfo) {
            $idSellerinfo = $sellerInfo->getIdSellerinfo();
        }

        $sql = 'SELECT o.id_order, sl.company, IFNULL(sio.id_sellerinfo,0) AS id_sellerinfo, o.date_add
            FROM `' . _DB_PREFIX_ . 'orders` o
                LEFT JOIN `' . _DB_PREFIX_ . 'sellerinfo_order` sio ON (o.id_order = sio.id_order)
                LEFT JOIN `' . _DB_PREFIX_ . 'sellerinfo` s ON (sio.id_sellerinfo = s.id_sellerinfo)
                LEFT JOIN `' . _DB_PREFIX_ . 'sellerinfo_lang` sl ON (sl.id_sellerinfo = s.id_sellerinfo AND sl.id_lang = :idLang)
                LEFT JOIN `' . _DB_PREFIX_ . 'sellerinfo_rating` sir ON (o.id_order=sir.id_order AND sir.id_sellerinfo = sio.id_sellerinfo)
                ' . $this->getOrderPaidJoin($isPaid) . '
            WHERE o.id_customer = :idCustomer
                AND o.date_add >= DATE_ADD(CURDATE() , INTERVAL -120 DAY)
                AND s.id_sellerinfo != :idSellerinfo
                AND sir.id_order IS NULL
                AND IFNULL(sio.id_sellerinfo,0) > 0
                ' . $this->getOrderPaidWhere($isPaid) . '
                GROUP BY o.`id_order`
            ';

        $res = $conn->fetchAll(
            $sql,
            [
                'idCustomer' => $idCustomer,
                'idSellerinfo' => $idSellerinfo,
                'idLang' => $idLang,
            ]
        );

        return $res;
    }

    private function getOrderPaidJoin($isPaid)
    {
        if (!$isPaid) {
            return '';
        }

        return ' LEFT JOIN `' . _DB_PREFIX_ . 'order_history` oh ON (o.`id_order` = oh.`id_order`)
            LEFT JOIN `' . _DB_PREFIX_ . 'order_state` os ON (os.`id_order_state` = oh.`id_order_state`)';
    }

    private function getOrderPaidWhere($isPaid)
    {
        if (!$isPaid) {
            return '';
        }

        return ' AND os.`paid` = 1';
    }
}
