<?php

namespace MtcPharmacy\Bundles\Classes;

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


class BundleType extends Model
{
    protected $table = 'bundle_types';

    public $timestamps = false;

    protected $fillable = [
        'assessment_form_id',
    ];


    public function items()
    {
        return $this->hasMany(BundleTypeItem::class);
    }

    public function scopeGroupBuyTypes($query)
    {
        return $query->whereRaw('LENGTH(url) = 0');
    }


    public static function getContainingShopItem(ShopItem $shop_item, ShopItemSize $shop_item_size = null)
    {
        $shop_item_id = $shop_item->id;
        $shop_item_size_id = $shop_item_size->id ?? null;

        $bundle_types = self::whereHas('items', function (Builder $query) use ($shop_item_id, $shop_item_size_id) {
            $query->where('shop_item_id', $shop_item_id);
            $query->where('shop_item_size_id', $shop_item_size_id);
        })->get();

        return $bundle_types;
    }


    private function doesItemExist(ShopItem $shop_item, ShopItemSize $shop_item_size = null)
    {
        $shop_item_id = $shop_item->id;
        $shop_item_size_id = $shop_item_size->id ?? null;

        $existing_items = $this
            ->items()
            ->where('shop_item_id', $shop_item_id)
            ->where('shop_item_size_id', $shop_item_size_id)
            ->get()
        ;

        return $existing_items->count() > 0;
    }


    public function addItem(ShopItem $shop_item, ShopItemSize $shop_item_size = null)
    {
        if ($this->doesItemExist($shop_item, $shop_item_size)) return;

        $bti = new BundleTypeItem();
        $bti->shop_item()->associate($shop_item);
        if ($shop_item_size) {
            $bti->shop_item_size()->associate($shop_item_size);
        }

        $this->items()->save($bti);
    }


    public function findByShopItemId($shop_item_id, $shop_item_size_id = null)
    {
        $bti = $this
            ->items()
            ->where('shop_item_id', $shop_item_id)
            ->where('shop_item_size_id', $shop_item_size_id)
            ->first()
        ;

        return $bti;
    }


    public function getShopItems()
    {
        $shop_items = collect([]);

        foreach ($this->items as $bti) {
            $shop_items->push($bti->shop_item);
        }

        return $shop_items;
    }

}
