<?php

declare(strict_types=1);

namespace KupShop\KupShopBundle\DiscountFieldDefinition;

use Query\QueryBuilder;

/**
 * Discount is calculated using product price and price common.
 */
class PriceCommonDiscountFieldDefinition extends AbstractDiscountFieldDefinition
{
    protected function getColumn(): string
    {
        return "IF({$this->getPriceForDiscountColumn()} > 0, (100 - {$this->getPriceColumn()}*(100-p.discount)/{$this->getPriceForDiscountColumn()}), p.discount)";
    }

    protected function getPriceColumn(): string
    {
        if (findModule(\Modules::PRODUCTS_VARIATIONS)) {
            return 'COALESCE(pv.price, p.price)';
        }

        return 'p.price';
    }

    protected function getPriceForDiscountColumn(): ?string
    {
        if (findModule(\Modules::PRODUCTS_VARIATIONS)) {
            return 'COALESCE(pv.price_common, p.price_common)';
        }

        return 'p.price_common';
    }

    protected function getSpecs(): array
    {
        $specs = [];

        $specs[] = function (QueryBuilder $qb) {
            $qb->joinVariationsOnProducts();
        };

        return $specs;
    }
}
