<?php

namespace common\logic\Producer\Producer\Service;

use common\components\DolibarrApi;
use common\logic\AbstractManager;
use common\logic\Producer\Producer\Model\Producer;
use common\logic\Producer\Producer\Repository\ProducerRepository;
use common\logic\Producer\ProducerPriceRange\Repository\ProducerPriceRangeRepository;
use yii\base\ErrorException;

class DolibarrProducerUtils extends AbstractManager
{
    protected DolibarrApi $dolibarrApi;
    protected ProducerPriceRangeRepository $producerPriceRangeRepository;
    protected ProducerRepository $producerRepository;

    public function loadDependencies(): void
    {
        $this->dolibarrApi = \Yii::$app->dolibarrApi;
        $this->producerPriceRangeRepository = $this->loadService(ProducerPriceRangeRepository::class);
        $this->producerRepository = $this->loadService(ProducerRepository::class);
    }

    public function generateDolibarrProducerInvoice(Producer $producer)
    {
        $idProduct = $this->getDolibarrProductId($producer);
        if(!$idProduct) {
            throw new ErrorException("Dolibarr : pas d'id product trouvé pour le producteur ".$producer->name);
        }

        $idInvoice = $this->dolibarrApi->createInvoice($producer->dolibarr_socid);
        $this->dolibarrApi->addInvoiceLine($idInvoice, $idProduct);
        $responseValidate = $this->dolibarrApi->validateInvoice($idInvoice);
        $this->dolibarrApi->generateInvoicePdf($responseValidate['ref']);
    }

    private function getDolibarrProductId(Producer $producer)
    {
        if($producer->dolibarr_product_id) {
            $idProduct = $producer->dolibarr_product_id;
        }
        else {
            $producerPriceRange = $this->producerPriceRangeRepository->getProducerPriceRangeByTurnover($this->producerRepository->getTurnoverLastMonth($producer));
            if($producerPriceRange && $producerPriceRange->dolibarr_product_id) {
                $idProduct = $producerPriceRange->dolibarr_product_id;
            }
        }

        return $idProduct;
    }
}