<?php

namespace common\logic\Order\ProductOrder\Service;

use common\helpers\Price;
use common\logic\AbstractService;
use common\logic\Config\Unit\Service\UnitSolver;
use common\logic\Order\Order\Model\Order;
use common\logic\Order\ProductOrder\Model\ProductOrder;
use common\logic\Product\Product\Service\ProductSolver;
use common\logic\SolverInterface;

class ProductOrderSolver extends AbstractService implements SolverInterface
{
    protected UnitSolver $unitSolver;
    protected ProductSolver $productSolver;

    public function loadDependencies(): void
    {
        $this->unitSolver = $this->loadService(UnitSolver::class);
        $this->productSolver = $this->loadService(ProductSolver::class);
    }

    public function getQuantityPriorityPieces(ProductOrder $productOrder): string
    {
        $quantityPieces = $this->getQuantityPieces($productOrder);
        if($quantityPieces) {
            return $quantityPieces;
        }
        else {
            return $this->getQuantityWithUnit($productOrder);
        }
    }

    public function getQuantityWithUnit(ProductOrder $productOrder): string
    {
        return $productOrder->quantity.' '.$this->productSolver->strUnit($productOrder->product);
    }

    public function getQuantityPieces(ProductOrder $productOrder): float
    {
        if ($productOrder->unit == 'piece') {
            return $productOrder->quantity;
        }
        else {
            if ($productOrder->product && $productOrder->product->weight > 0) {
                return $productOrder->quantity / $this->productSolver->getWeightUnitReference($productOrder->product);
            }
        }

        return 0;
    }

    public function getQuantityToCoefficientOfUnit(ProductOrder $productOrder): float
    {
        return $productOrder->quantity * $this->unitSolver->getUnitCoefficient($productOrder->unit);
    }

    public function getPriceWithTax(ProductOrder $productOrder)
    {
        return Price::getPriceWithTax($productOrder->price, $productOrder->taxRate->value);
    }

    public function getPriceByTypeTotal(ProductOrder $productOrder, string $typeTotal = Order::AMOUNT_TOTAL)
    {
        if ($typeTotal == Order::INVOICE_AMOUNT_TOTAL && $productOrder->invoice_price) {
            return $productOrder->invoice_price;
        }

        return $productOrder->price;
    }

    public function getPriceUnitReference(ProductOrder $productOrder): ?float
    {
        if($productOrder->unit == 'piece') {
            if($productOrder->product->weight) {
                $price = (1000 * $productOrder->price) / $productOrder->product->weight;
            }
            else {
                return null;
            }
        }
        else {
            $price = $productOrder->price;
        }

        return $price;
    }
}