<?php

namespace App\Classes\Modules\Orders\Processors;

use App\Classes\Modules\Orders\DataTransferObjects\OrderObject;
use App\Classes\Modules\Orders\Services\FetchesOrder;
use App\Classes\Modules\Orders\Services\UpdatesCurrentStep;
use App\Classes\Modules\OrderSteps\Services\FetchesOrderSteps;
use App\Classes\Modules\Orders\Standards\Rules\CanUpdateCurrentStep;
use App\Classes\ValueObjects\Constants\OrderStatus;
use App\Classes\ValueObjects\Constants\OrderSteps;
use App\Models\Order;
use App\Models\Step;

class UpdatesOrderCurrentStepProcessor
{
    private $canUpdateCurrentStep;

    private $updatesCurrentStep;

    private $fetchesOrder;

    private $fetchesOrderSteps;

    public function __construct(CanUpdateCurrentStep $canUpdateCurrentStep, FetchesOrder $fetchesOrder, FetchesOrderSteps $fetchesOrderSteps, UpdatesCurrentStep $updatesCurrentStep)
    {
        $this->canUpdateCurrentStep = $canUpdateCurrentStep;
        $this->updatesCurrentStep = $updatesCurrentStep;
        $this->fetchesOrder = $fetchesOrder;
        $this->fetchesOrderSteps = $fetchesOrderSteps;
    }

    public function execute(int $orderId, string $currentStep){

        $order_object = new OrderObject(0, '', '', 0, 0, $currentStep, $orderId,0,0);

        $this->canUpdateCurrentStep->passes($order_object);

        $order = $this->fetchesOrder->execute(['id'=>$order_object->getId()]);

        //Count steps / obligations that pending
        $order_steps_processing = $this->fetchesOrderSteps->getRepository()->where(['owner_id'=>$order_object->getId(), 'status'=> OrderStatus::PROCESSING])->count();

        //If no more steps / obligations, then update Order status to complete (Contract fullfilled)
        if($order_steps_processing==0){
            $order_object->setStatus(OrderStatus::COMPLETE);
        }else{
            $order_object->setStatus($order->status);
        }

        $order_object->setCurrentStep($currentStep);

        $order = $this->updatesCurrentStep->execute($order, $order_object);

    }
}
