<?php

namespace Velis\Bpm\Ticket\Mixin;

use Velis\App;
use Survey\Survey;
use Survey\Question;
use Velis\Bpm\User;

/**
 * Ticket visits functionality
 * @author Daniel Zaucha <daniel.zaucha@velis.pl>
 */
trait SurveyTrait
{
    /**
     * Ticket survey
     *
     * @var \Survey\Survey
     */
    protected $_survey;


    /**
     * Survey questions
     *
     * @var \Survey\Question[]
     */
    protected $_questions;


    /**
     * Surveys for ticket based on classification
     *
     * @var Survey\Survey[]
     */
    protected static $_surveys = [];


    /**
     * Checks whether survey tab should be visible for the currently logged user.
     */
    public function canAccessSurvey(?User $user = null): bool
    {
        if (!$user) {
            $user = App::$user;
        }

        return $user->canAccessSurvey();
    }


    public function canEditReport()
    {
        $this->getSurvey();

        if ($this->isFinished() || !App::$user->hasPriv('Survey', 'SurveyAnswerEdit')) {
            return false;
        }

        return true;
    }


    /**
     * Sets ticket survey
     * @param Survey $survey
     */
    public function setSurvey(Survey $survey)
    {
        $this->_survey = $survey;
    }


    /**
     * Returns survey
     */
    public function getSurvey($surveys = [])
    {
        if (!isset($this->_survey) && $this->ticket_category_id) {
            if (!self::$_surveys[$this->ticket_category_id]) {
                self::$_surveys[$this->ticket_category_id] = Survey::listAll([
                    'ticket_category_id' => $this->ticket_category_id,
                    'survey_type_id' => 'Ticket'
                ]);
            }

            $this->_survey = reset(self::$_surveys[$this->ticket_category_id]);
        }

        return $this->_survey;
    }


    /**
     * Returns questions
     */
    public function getSurveyQuestions()
    {
        $this->getSurvey();

        if (!isset($this->_questions)) {
            $this->_questions = $this->_survey->getQuestions();
            Question::loadQuestionAnswers($this->_questions, $this->id());
        }

        return $this->_questions;
    }
}
