<?php

/*
 * This file is part of EC-CUBE
 *
 * Copyright(c) EC-CUBE CO.,LTD. All Rights Reserved.
 *
 * http://www.ec-cube.co.jp/
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Eccube\Repository;

use Doctrine\ORM\QueryBuilder;
use Eccube\Entity\CustomerFavoriteProduct;
use Symfony\Bridge\Doctrine\RegistryInterface;

/**
 * CustomerFavoriteProductRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class CustomerFavoriteProductRepository extends AbstractRepository
{
    public function __construct(RegistryInterface $registry)
    {
        parent::__construct($registry, CustomerFavoriteProduct::class);
    }

    /**
     * @param \Eccube\Entity\Customer $Customer
     * @param \Eccube\Entity\Product  $Product
     */
    public function addFavorite(\Eccube\Entity\Customer $Customer, \Eccube\Entity\Product $Product)
    {
        if ($this->isFavorite($Customer, $Product)) {
            return;
        } else {
            $CustomerFavoriteProduct = new \Eccube\Entity\CustomerFavoriteProduct();
            $CustomerFavoriteProduct->setCustomer($Customer);
            $CustomerFavoriteProduct->setProduct($Product);

            $em = $this->getEntityManager();
            $em->persist($CustomerFavoriteProduct);
            $em->flush();
        }
    }

    /**
     * @param  \Eccube\Entity\Customer $Customer
     * @param  \Eccube\Entity\Product  $Product
     *
     * @return bool
     */
    public function isFavorite(\Eccube\Entity\Customer $Customer, \Eccube\Entity\Product $Product)
    {
        $qb = $this->createQueryBuilder('cf')
            ->select('COUNT(cf.Product)')
            ->andWhere('cf.Customer = :Customer AND cf.Product = :Product')
            ->setParameters([
                'Customer' => $Customer,
                'Product' => $Product,
            ]);
        $count = $qb
            ->getQuery()
            ->getSingleScalarResult();

        return $count > 0;
    }

    /**
     * @param  \Eccube\Entity\Customer $Customer
     *
     * @return QueryBuilder
     */
    public function getQueryBuilderByCustomer(\Eccube\Entity\Customer $Customer)
    {
        $qb = $this->createQueryBuilder('cfp')
            ->select('cfp, p')
            ->innerJoin('cfp.Product', 'p')
            ->where('cfp.Customer = :Customer AND p.Status = 1')
            ->setParameter('Customer', $Customer);

        // Order By
        $qb->addOrderBy('cfp.create_date', 'DESC');

        return $qb;
    }

    /**
     * お気に入りを削除します.
     *
     * @param \Eccube\Entity\CustomerFavoriteProduct $CustomerFavoriteProduct
     */
    public function delete($CustomerFavoriteProduct)
    {
        $em = $this->getEntityManager();
        $em->remove($CustomerFavoriteProduct);
        $em->flush($CustomerFavoriteProduct);
    }
}
