<?php

namespace common\logic\Producer\ProducerPriceRange\Repository;

use common\helpers\Price;
use common\logic\AbstractRepository;
use common\logic\Producer\ProducerPriceRange\Model\ProducerPriceRange;

class ProducerPriceRangeRepository extends AbstractRepository
{
    protected ProducerPriceRangeRepositoryQuery $query;

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

    /**
     * Retourne les options de base nécessaires à la fonction de recherche.
     *
     */
    public function getDefaultOptionsSearch(): array
    {
        return [
            'with' => [],
            'join_with' => [],
            'orderby' => '',
            'attribute_id_producer' => ''
        ];
    }

    public function findOneProducerPriceRangeById(int $id)
    {
        return ProducerPriceRange::searchOne([
            'id' => $id
        ]);
    }

    public function queryProducerPriceRanges()
    {
        return ProducerPriceRange::find()->orderBy('range_begin ASC');
    }

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

    public function getAmountToBeBilledByTurnover(float $turnover = null, $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;
        }
    }
}