<?php declare(strict_types=1);

namespace Shop\Presentation\Modules\AllOrdersWidget;

use Core\ModuleController;
use MoySklad\Entities\Documents\Orders\CustomerOrder;
use Shop\Presentation\Config\Main;
use Shop\Presentation\Helpers\Price;
use Shop\Infrastructure\Models\Order\Order;
use Shop\Infrastructure\Repositories\CustomerOrder\CustomerOrderCriteria;
use Shop\Infrastructure\Repositories\CustomerOrder\CustomerOrderRepository;
use Shop\Presentation\UseCases\Shopping\ShoppingService;

/**
 * Description of AllOrdersWidget
 *
 * @author Diamond Code Generator
 */
class AllOrdersWidget extends ModuleController
{


    public function __construct(private ShoppingService         $shoppingService,
                                private CustomerOrderRepository $orderRepository,
                                private Main                    $mainConf
    )
    {
    }

    public function process(): string
    {
        $criteria = CustomerOrderCriteria::create()
            ->setSortById('DESC')
            ->setFilterByCreateMonthDate((new \DateTime())->format('Y-m'));
        
        $ordersMonth = $this->orderRepository->findByCriteria($criteria);
        $ordersCount = $ordersMonth->count();

        $criteria = CustomerOrderCriteria::create()
            ->setSortById('DESC')
            ->setFilterByStateId($this->mainConf->getStateDefault())
            ->setLimit(1);

        $orders = $this->orderRepository->findByCriteria($criteria);
        /** @var Order $lastOrder */
        $lastOrder = $orders->current();

        if ($this->mainConf->getWishfulSumOrderMonth()) {
            $ordersProfit = round(($ordersMonth->getSum() / $this->mainConf->getWishfulSumOrderMonth()) * 100);
        } else {
            $ordersProfit = 0;
        }

        return $this->render([
            'orders_sum' => Price::format($ordersMonth->getSum(), 0),
            "orders_count" => $ordersCount,
            'last_order_sum' => !$lastOrder ? 0 : Price::format($lastOrder->getSum(), 0),
            'orders_profit' => $ordersProfit > 100 ? 100 : $ordersProfit,
            'cur' => $this->shoppingService->getDefaultCurrency()
        ]);
    }
}               