<?php

namespace MtcPharmacy\Subscriptions\Classes;

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


class SubscriptionPreference extends Model
{
    protected $table = 'subscription_preferences';

    protected $fillable = [
        'item_id',
        'item_size_id',
        'is_allowed',
        'is_required',
        'max_number_of_issues',
        'can_be_paused',
        'interval_multiplier',
        'interval',
    ];

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

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


    public static function ensureItemPreferencesExist(int $item_id)
    {
        $shop_item = ShopItem::find($item_id);

        if ($shop_item) {
            $o = self::query()
                ->where('item_id', $shop_item->id)
                ->first()
            ;

            if (! $o) {
                self::create([
                    'item_id' => $shop_item->id,
                ]);
            }

            foreach ($shop_item->sizes as $shop_item_size) {
                $o = self::query()
                    ->where('item_id', $shop_item->id)
                    ->where('item_size_id', $shop_item_size->id)
                    ->first()
                ;

                if (! $o) {
                    self::create([
                        'item_id' => $shop_item->id,
                        'item_size_id' => $shop_item_size->id,
                    ]);
                }
            }
        }
    }


    public static function init($shop_item_id, $shop_item_size_id = null)
    {
        $sub_config = self::query()
            ->where('item_id', $shop_item_id)
            ->where('item_size_id', $shop_item_size_id)
            ->first()
        ;

        return $sub_config;
    }


    public function getIntervalApproximateEquivalentInDays()
    {
        $interval = $this->interval_multiplier;

        switch ($this->interval) {
        case Subscription::INTERVAL_DAYS:
            $interval_days = 1;
            break;
        case Subscription::INTERVAL_WEEKS:
            $interval_days = 7;
            break;
        case Subscription::INTERVAL_MONTHS:
            $interval_days = 30;
            break;
        }

        $interval *= $interval_days;

        return $interval;
    }

}
