<?php

namespace Modules\Bitrix\Traits;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\MorphOne;
use Illuminate\Database\Eloquent\Model;
use Modules\Bitrix\Models\BitrixId;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

use Illuminate\Support\Facades\Log;

trait Bitrixable
{
    public function bitrixy(): MorphOne
    {
        return $this->MorphOne(BitrixId::class, 'bitrixable');
    }
    public function bitrixId()
    {
        if ($row = $this->bitrixy()->first())
        {
            return $row->bx_id;
        }
        return false;
    }
    public function setBitrixId($id = null)
    {
        $bitrixy = $this->bitrixy;
        if (!$bitrixy)
        {
            $bitrixId = new BitrixId();
            $bitrixId->bx_id = $id ?? null;
            $this->bitrixy()->save($bitrixId);
        }
        if ($id)
        {
            $bitrixy = $this->bitrixy;
            $bitrixy->bx_id = $id;
            $bitrixy->save();
        }
        return true;
    }
    protected static function create(array $attributes = [])
    {
        $model = new static();
        $model->fill($attributes);
        $model->save();

        try
        {
            $model->setBitrixId();
            return $model;
        }
        catch (\Exception $e)
        {
            $model->delete();
            Log::error($e->getMessage());
            throw new \Exception('Error of bitrix identifier getter');
        }
    }

    public static function firstOrCreate($attributes = [], $values = [])
    {
        $model = new static();
        foreach ($attributes as $key => $value)
        {
            $model = $model->where($key, $value);
        }
        if ($model->count())
        {
            return $model->first();
        }
        else
        {
            self::create(array_merge($attributes, $values));
        }
        return true;
    }

    /*protected function save() {
        if ($bitrixId = $this->bitrixy()) 
        {
            $bitrixId = $bitrixId->bx_id;

        }
        parent::save();
    }*/
}


