<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use MtcPharmacy\Bundles\Classes\BundleType;
use MtcPharmacy\Subscriptions\Classes\Subscription;


class SubscriptionBundleType extends Model
{
    protected $table = 'subscriptions_bundletypes';

    public $timestamps = false;

    protected $fillable = [
        'subscription_id',
        'bundletype_id',
    ];


    public function bundleType()
    {
        return $this->hasOne(BundleType::class, 'id', 'bundletype_id');
    }


    public function subscription()
    {
        return $this->hasOne(Subscription::class, 'id', 'subscription_id');
    }


    public static function isSubscriptionEditable(Subscription $subscription)
    {
        $is_editable = false;

        $sbt = self::query()
            ->where('subscription_id', $subscription->id)
            ->first()
        ;

        $bundle_type_url = $sbt->bundleType->url ?? null;
        if ($bundle_type_url) {
            $is_editable = true;
        }

        return $is_editable;
    }


    public static function relate(Subscription $subscription, BundleType $bundle_type)
    {
        $sbt = self::create([
            'subscription_id' => $subscription->id,
            'bundletype_id' => $bundle_type->id,
        ]);

        $sbt->save();
    }

}
