<?php

namespace MtcPharmacy\QualifyingAnswers\Classes;

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


class QualifyingAnswersGroup extends Model
{
    const LOGIC_AND = 'and';
    const LOGIC_OR = 'or';


    protected $table = 'assessment_qualifying_answers__groups';

    protected $fillable = [
        'template_id',
        'logic',
        'config_id',
    ];


    public function groups_config()
    {
        return $this->belongsTo(QualifyingAnswersGroupsConfig::class, 'config_id');
    }


    public function answers()
    {
        return $this->hasMany(QualifyingAnswer::class, 'group_id');
    }


    public function template()
    {
        return $this->belongsTo(QualifyingAnswersGroupTemplate::class, 'template_id');
    }


    public function doesQualify(Assessment $assessment)
    {
        $result = null;

        if ($this->answers->count()) {
            $_SESSION['QA'][$this->groups_config->item_id]['groups'][$this->id] = [
                'label' => $this->template->label,
                'logic' => $this->logic,
                'result' => null,
                'questions' => [],
            ];
        }

        $temp_results = [];
        foreach ($this->answers as $answer) {
            if ($answer->isRelevantToAssessment($assessment)) {
                $temp_results[$answer->id] = (int)$answer->doesQualify($assessment);
            }
        }


        if ($temp_results) {
            $result = false;
            if ($this->logic == self::LOGIC_AND) {
                if ( array_sum($temp_results) == count($temp_results) ) $result = true;
            } elseif ($this->logic == self::LOGIC_OR) {
                if (array_sum($temp_results) > 0) $result = true;
            }
        }

        if ($this->answers->count()) {
            $_SESSION['QA'][$this->groups_config->item_id]['groups'][$this->id]['result'] = $result;
        }

        if (is_null($result)) {
            unset($_SESSION['QA'][$this->groups_config->item_id]['groups'][$this->id]);
        }

        return $result;
    }
}

