<?php


namespace Shop\Services\ComplexRate;


use Propel\Runtime\ActiveQuery\Criteria;
use Shop\Config\Main;
use Shop\Domain\Customer\Contracts\CustomerEntityInterface;

/**
 * @deprecated
 * Class ComplexRateService
 * @package Shop\Services\ComplexRate
 */
class ComplexRateService
{
    protected $mainConfig;

    /**
     * ComplexRateService constructor.
     * @param Main $mainConfig
     */
    public function __construct(Main $mainConfig)
    {
        $this->mainConfig = $mainConfig;
    }

    /**
     * @param CustomerEntityInterface $customer
     * @param int|null $brandId
     * @return float
     */
    public function getComplexRateByCustomer(CustomerEntityInterface $customer, ?int $brandId = null): float
    {

        if ($customer->getGroupId() === $this->mainConfig->getDefaultGuestGroup()) {
            $customerId = "%";
            $customerGroupId = "%";
        } else {
            $customerId = $customer->getId();
            $customerGroupId = $customer->getCustomerGroup()->getId();
        }

        $brandId = $brandId??'%';

        $shopId = $this->customerService->getCurrentShopId();

        $complexQ =
            \Shop\Models\ComplexRate\ComplexRateQuery::create()
                ->addAnd("", sprintf("'%s' LIKE `brand_id`", $brandId), Criteria::CUSTOM)
                ->addAnd("", sprintf("'%s' LIKE `shop_id`", $shopId), Criteria::CUSTOM)
                ->addAnd("", sprintf("'%s' LIKE `customer_id`", $customerId), Criteria::CUSTOM)
                ->addAnd("", sprintf("'%s' LIKE `customer_group_id`", $customerGroupId), Criteria::CUSTOM)
                ->orderBy("brand_id", Criteria::DESC)
                ->orderBy("shop_id", Criteria::DESC)
                ->orderBy("customer_id", Criteria::DESC)
                ->orderBy("customer_group_id", Criteria::DESC)
                ->orderByPriority(Criteria::DESC);

        $complex = $complexQ->findOne();

        if (!$complex) {
            return 0.00;
        }

        return (float)$complex->getRate();
    }
}