<?php

namespace MtcPharmacy\QualifyingAnswers\Classes;

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


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


    protected $table = 'assessment_qualifying_answers__groups_config';

    protected $fillable = [
        'item_id',
        'logic',
    ];


    public function groups()
    {
        return $this->hasMany(QualifyingAnswersGroup::class, 'config_id');
    }


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


    public function ensureAllGroupsExist()
    {
        $group_templates = QualifyingAnswersGroupTemplate::all();

        foreach ($group_templates as $group_template) {
            $temp_group = $this
                ->groups
                ->where('template_id', $group_template->id)
                ->first()
            ;

            if (! $temp_group) {
                $temp_group = QualifyingAnswersGroup::create();
                $temp_group->template()->associate($group_template);
                $temp_group->save();

                $this->groups()->save($temp_group);
            }
        }

    }


    private function getAllConfiguredAnswers()
    {
        $answers = collect([]);

        foreach ($this->groups as $group) {
            foreach ($group->answers as $answer) {
                $answers->push($answer);
            }
        }

        return $answers;
    }


    public function ensureAllAnswersExist()
    {
        $configured_answers = $this->getAllConfiguredAnswers();
        $configured_question_ids = $configured_answers->pluck('question_id')->toArray();

        $shop_item = $this->item;
        $assessment_form = $shop_item->findAssessmentForm();
        $questions = QualifyingAnswersHelper::getRelevantQuestions($assessment_form);

        foreach ($questions as $question) {
            if (! in_array($question->id, $configured_question_ids)) {
                $temp_answer = QualifyingAnswer::create([
                    'question_id' => $question->id,
                ]);
                $temp_answer->save();

                $default_group = $this->groups()->first();
                $default_group->answers()->save($temp_answer);
            }
        }
    }


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

        $_SESSION['QA'][$this->item_id] = [
            'logic' => $this->logic,
            'result' => null,
            'groups' => [],
        ];

        $temp_results = [];
        foreach ($this->groups as $group) {
            $does_group_qualify = $group->doesQualify($assessment);

            if (! is_null($does_group_qualify)) {
                $temp_results[$group->id] = (int)$group->doesQualify($assessment);
            }
        }

        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;
        }

        $_SESSION['QA'][$this->item_id]['result'] = $result;

        return $result;
    }


    public function getAnswers()
    {
        $answers = collect([]);

        $assessment_form = $this->item->findAssessmentForm();

        $active_question_ids = QualifyingAnswersHelper::getRelevantQuestions($assessment_form)
            ->pluck('id')
            ->toArray()
        ;

        foreach ($this->groups as $group) {
            foreach ($group->answers as $answer) {
                $answer->load('group');
                $answer->load('group.groups_config');
                $answer->load('group.template');
                if (in_array($answer->question_id, $active_question_ids)) {
                    $answers->push($answer);
                }
            }
        }

        return $answers;
    }

}

