<?php

namespace MtcPharmacy\QualifyingAnswers\Classes;

use Mtc\Shop\Assessment\Assessment;
use Illuminate\Support\Collection;


class QualifyingAnswersFilter
{
    private $all_configured_item_ids = [];
    private $rejected_item_ids = [];
    private $qualified_item_ids = [];


    public function getQualifiedItemIDs()
    {
        return $this->qualified_item_ids;
    }

    public function getRejectedItemIDs()
    {
        return $this->rejected_item_ids;
    }


    public function getDebugInfo()
    {
        return $_SESSION['QA'];
    }


    public static function init(Assessment $assessment = null)
    {
        $accepted = collect([]);
        $rejected = collect([]);

        if (! $assessment) {
            return new self($accepted, $rejected);
        }

        unset($_SESSION['QA']);

        $configs = QualifyingAnswer::getGroupsConfigs($assessment);

        foreach ($configs as $config) {
            if ($config->doesQualify($assessment)) {
                $accepted->push($config->item);
            } else {
                $rejected->push($config->item);
            }
        }

        return new self($accepted, $rejected);
    }


    private function __construct(Collection $accepted, Collection $rejected)
    {
        $this->qualified_item_ids = $accepted
            ->pluck('id')
            ->unique()
            ->toArray()
        ;

        $this->rejected_item_ids = $rejected
            ->pluck('id')
            ->unique()
            ->toArray()
        ;

        $this->all_configured_item_ids = array_merge(
            $this->qualified_item_ids,
            $this->rejected_item_ids
        );
    }

}
