<?php

namespace domain\Producer\ProducerPriceRange;

use common\helpers\Price;
use domain\_\AbstractRepository;

class ProducerPriceRangeRepository extends AbstractRepository
{
    protected ProducerPriceRangeRepositoryQuery $query;

    public function loadDependencies(): void
    {
        $this->loadQuery(ProducerPriceRangeRepositoryQuery::class);
    }

    /**
     * Retourne les options de base nécessaires à la fonction de recherche.
     */
    public function getDefaultOptionsSearch(): array
    {
        return [
            self::WITH => [],
            self::JOIN_WITH => [],
            self::ORDER_BY => 'range_begin ASC',
            self::ATTRIBUTE_ID_PRODUCER => ''
        ];
    }

    public function findOneProducerPriceRangeById(int $id)
    {
        return $this->createDefaultQuery()
            ->filterById($id)
            ->findOne();
    }

    public function queryProducerPriceRanges()
    {
        return $this->createDefaultQuery();
    }

    public function findProducerPriceRanges()
    {
        return $this->queryProducerPriceRanges()->find();
    }

    public function getProducerPriceRangeByTurnover(float $turnover = 0): ?ProducerPriceRange
    {
        $producerPriceRangeArray = $this->findProducerPriceRanges();
        foreach ($producerPriceRangeArray as $producerPriceRange) {
            if ($turnover >= $producerPriceRange->range_begin && $turnover < $producerPriceRange->range_end) {
                return $producerPriceRange;
            }
        }

        return null;
    }

    public function getAmountToBeBilledByTurnover(float $turnover = 0, $format = false)
    {
        $amountToBeBilled = 0;
        $producerPriceRangeArray = $this->findProducerPriceRanges();
        foreach ($producerPriceRangeArray as $priceRange) {
            if ($turnover >= $priceRange->range_begin && $turnover < $priceRange->range_end) {
                $amountToBeBilled = $priceRange->price;
            }
        }

        if ($format) {
            return Price::format($amountToBeBilled, 0);
        } else {
            return $amountToBeBilled;
        }
    }
}