<?php

namespace App\Classes\Modules\Vouchers\Services;

use App\Classes\General\Eloquent\AbstractUpdateRecord;
use App\Classes\Modules\Vouchers\DataTransferObjects\VoucherObject;
use App\Models\Voucher;

class CreatesVoucher extends AbstractUpdateRecord
{
    /** @var CheckIfVoucherExists */
    private $voucherExists;

    /**
     * CreatesVoucher constructor.
     * @param CheckIfVoucherExists $voucherExists
     */
    public function __construct(CheckIfVoucherExists $voucherExists)
    {
        $this->voucherExists = $voucherExists;
    }

    /**
     * @param VoucherObject $object
     * @return \Illuminate\Database\Eloquent\Model
     * @throws \App\Classes\Exceptions\MalformedRequestException
     */
    public function execute(VoucherObject $object) {
        if(!$this->voucherExists->execute($object->getCode()))
        {
            $model = new Voucher();
            $model->code = $object->getCode();
            $model->name = $object->getName();
            $model->type = $object->getType();
            $model->value = $object->getValue();
            $model->start_date = $object->getStartDate();
            $model->end_date = $object->getEndDate();
            return $this->handler($model);
        }
        return null;
    }
}
