<?php

namespace MtcPharmacy\QualifyingAnswers\Classes;

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

class QualifyingAnswer extends Model
{
    public $does_qualify = false;

    protected $table = 'assessment_qualifying_answers';

    protected $fillable = [
        'question_id',
        'qualifying_answer',
    ];

    protected $casts = [
        'qualifying_answer' => 'array',
    ];

    public function group()
    {
        return $this->belongsTo(QualifyingAnswersGroup::class, 'group_id');
    }

    public function equals(array $provided_answer_array = [])
    {
        $equals = false;

        $qualifying_answer_array = $this->qualifying_answer;
        if (! is_array($qualifying_answer_array)) {
            $qualifying_answer_array = [$qualifying_answer_array];
        }

        // Remove NULL elements.
        $provided_answer_array = array_filter($provided_answer_array);
        $qualifying_answer_array = array_filter($qualifying_answer_array);

        $qualifying_answer_array = array_map('strtolower', $qualifying_answer_array);
        $provided_answer_array = array_map('strtolower', $provided_answer_array);

        if (array_intersect($provided_answer_array, $qualifying_answer_array)) {
            $equals = true;
        }

        // Any anwswer is fine.
        if (! $qualifying_answer_array) {
            $equals = true;
        }

        return $equals;
    }

    public static function getGroupsConfigs(Assessment $assessment)
    {
        $configs = [];

        $form_question_ids = self::getRelevantQuestionIds($assessment);
        $configured_answers = self::query()
            ->whereIn('question_id', $form_question_ids)
            ->where('qualifying_answer', '<>', '')
            ->whereNot('qualifying_answer', '[]')
            ->whereNotNull('qualifying_answer')
            ->get();

        foreach ($configured_answers as $configured_answer) {
            $configs[$configured_answer->group->groups_config->id] = $configured_answer->group->groups_config;
        }

        return collect($configs);
    }

    public static function getRelevantQuestionIds(Assessment $assessment)
    {
        return $assessment->form->questions->pluck('id');
    }

    public function isRelevantToAssessment(Assessment $assessment)
    {
        $form_question_ids = self::getRelevantQuestionIds($assessment);

        return $form_question_ids->contains($this->question_id);
    }

    public static function ensureRelevantRowsExistForShopItem(Item $item)
    {
        $groups_config = QualifyingAnswersGroupsConfig::query()
            ->where('item_id', $item->id)
            ->first();

        if (! $groups_config) {
            $groups_config = QualifyingAnswersGroupsConfig::create([
                'item_id' => $item->id,
            ]);
            $groups_config->save();
        }

        $groups_config->ensureAllGroupsExist();
        $groups_config->ensureAllAnswersExist();
    }

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

        $provided_answer = $assessment
            ->answers
            ->where('question_id', $this->question_id)
            ->first()
            ->answer;

        if (strpos($provided_answer, '"') !== false) {
            $provided_answer = json_decode($provided_answer);
        } else {
            $provided_answer = [$provided_answer];
        }

        $result = $this->equals($provided_answer);

        $_SESSION['QA'][$this->group->groups_config->item_id]['groups'][$this->group->id]['questions'][$this->question_id] =
            [
                'expected_answer' => $this->qualifying_answer,
                'provided_answer' => $provided_answer,
                'result' => $result,
            ];

        return $result;
    }
}
