<?php

namespace MtcPharmacy\Subscriptions\Classes;

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

class SubscriptionItem extends Model
{
    protected $table = 'subscription_items';

    protected $fillable = [];

    public function subscription()
    {
        return $this->belongsTo(Subscription::class);
    }

    public function shop_item()
    {
        return $this->belongsTo(ShopItem::class);
    }

    public function shop_item_size()
    {
        return $this->belongsTo(ShopItemSize::class);
    }

    public function getDisplayName()
    {
        $name = $this->shop_item->name;

        if ($this->shop_item_size) {
            $name .= " // {$this->shop_item_size->size}";
        }

        return $name;
    }

    public static function getAllowedItems()
    {
        $allowed_items = [];

        $shop_items = ShopItem::active()->get();

        foreach ($shop_items as $shop_item) {
            if ($shop_item->sizes->count()) {
                foreach ($shop_item->sizes as $shop_item_size) {
                    $key = "{$shop_item->id}:{$shop_item_size->id}";
                    $allowed_items[$key] = "{$shop_item->name} // {$shop_item_size->size}";
                }
            } else {
                $key = "{$shop_item->id}";
                $allowed_items[$key] = "{$shop_item->name}";
            }
        }

        return $allowed_items;
    }

    public static function createFromShopItem(ShopItem $shop_item, ShopItemSize $shop_item_size = null)
    {
        $si = new self;

        $si->shop_item()->associate($shop_item);

        if ($shop_item_size) {
            $si->shop_item_size()->associate($shop_item_size);
        }

        return $si;
    }
}
