<?php

namespace App\Traits;


use App\Classes\Modules\Orders\Steps\Requirements\StepManager;
use App\Models\Order;
use App\Models\OrderStep;
use Illuminate\Http\Request;

trait OrderStepTrait
{
    abstract function getOrderId();

    abstract function getCurrentStep();
    abstract function setCurrentStep(string $currentStep): void;

    abstract function getNextStep();
    abstract function setNextStep(?string $nextStep): void;

    public function CompleteOrderCurrentStep(){
        $orderStep = OrderStep::where('order_id', $this->getOrderId())
            ->where('reference_id', $this->getCurrentStep())->firstOrFail();

        $orderStep->complete = 1;

        if($orderStep->save()){
            return $this->UpdateOrderCurrentStep();
        }

        return false;
    }

    public function UpdateOrderCurrentStep(){
        OrderStep::where('order_id', $this->getOrderId())
            ->where('reference_id', $this->getCurrentStep())->firstOrFail();

        $order = Order::findOrFail($this->getOrderId());
        $order->current_step = $this->getNextStep();

        if($this->getNextStep() === null){
            $order->complete = true;
        }

        if($order->save()){
            return true;
        }

        return false;
    }

    public function ProcessStep(?Request $request): bool {
        return (new StepManager($this->getOrderId(), $this->getCurrentStep(), $request))->execute();
    }


}