<?php

namespace App;

use Mtc\Shop\Item\Size;
use Illuminate\Database\Eloquent\Model;
use Mtc\Shop\Assessment\Assessment;


class SizeRestriction extends Model
{
    protected $table = 'item_sizes__restrictions';

    protected $fillable = [
        'question_id',
        'item_size_id',
        'restricting_answer',
    ];

    private $item_size = null;


    public static function getForItemSize(Size $item_size)
    {
        $restrictions = self::query()
            ->where('item_size_id', $item_size->id)
            ->get()
            ->pluck('restricting_answer', 'question_id')
        ;

        return $restrictions->toArray();
    }


    public static function isSizeRestricted(Size $item_size)
    {
        $is_restricted = false;

        $completed_assessment = Assessment::getCompletedForItem($item_size->item);

        $restricting_answers = self::getForItemSize($item_size);

        foreach ($restricting_answers as $q_id => $restricting_answer) {
            if (! $restricting_answer) continue;

            $provided_answer = $completed_assessment
                ->answers
                ->where('question_id', $q_id)
                ->first()
                ->answer
            ;

            if (strtolower($provided_answer) == strtolower($restricting_answer)) {
                $is_restricted = true;
                break;
            }
        }

        return $is_restricted;
    }

}
