<?php

namespace MtcPharmacy\Multisite\Classes;

use Illuminate\Database\Eloquent\Model;
use Mtc\Shop\Item as ShopItem;

class MultisiteBaseEntity extends Model
{
    protected $table = 'multisite__base_entities';

    protected $fillable = [
        'concrete_entity_id',
        'concrete_entity_type',
        'mode',
    ];

    public static function getTableName()
    {
        return app(__CLASS__)->getTable();
    }

    public function custom_entities()
    {
        return $this->hasMany(MultisiteCustomEntity::class, 'parent_entity_id', 'id');
    }

    public function ensureCustomEntitiesExist()
    {
        $sites = MultisiteSite::all();

        foreach ($sites as $site) {
            $custom_item = MultisiteCustomEntity::query()
                ->where('site_id', $site->id)
                ->where('parent_entity_id', $this->id)
                ->first();

            if ($custom_item) {
                continue;
            } else {
                $duplicate_concrete_entity = $this->getConcreteEntity()
                    ->replicateWithRelations();

                MultisiteCustomEntity::create([
                    'parent_entity_id' => $this->id,
                    'concrete_entity_type' => $this->concrete_entity_type,
                    'concrete_entity_id' => $duplicate_concrete_entity->id,
                    'site_id' => $site->id,
                ]);
            }
        }
    }

    public function getConcreteClass()
    {
        $concrete_class = null;

        switch ($this->concrete_entity_type) {
            case MultisiteConstants::ENTITY_TYPE_SHOP_BRAND:
                $concrete_class = \Mtc\Shop\Brand::class;
                break;

            case MultisiteConstants::ENTITY_TYPE_SHOP_CATEGORY:
                $concrete_class = \Mtc\Shop\Category::class;
                break;

            case MultisiteConstants::ENTITY_TYPE_SHOP_ITEM:
                $concrete_class = \Mtc\Shop\Item::class;
                break;

            case MultisiteConstants::ENTITY_TYPE_CMS_PAGE:
                $concrete_class = \Mtc\Cms\Models\Page::class;
                break;

            case MultisiteConstants::ENTITY_TYPE_SITE_MENU:
                $concrete_class = \Mtc\Plugins\SiteMenu\Classes\SiteMenu::class;
                break;
        }

        return $concrete_class;
    }

    public function getConcreteEntity()
    {
        $concrete_entity = null;

        $concrete_class = $this->getConcreteClass();
        if ($concrete_class) {
            $concrete_entity = $concrete_class::find($this->concrete_entity_id);
        }

        if (! $concrete_entity) {
            throw new \Exception("Couldn't find concrete entity.");
        }

        return $concrete_entity;
    }
}
