<?php

namespace Yuvayana\AcadlixImporter\Models;

use Illuminate\Database\Eloquent\Model;

defined('ABSPATH') || exit();

if (!class_exists('WpAdvQuizStatistic')) {
  class WpAdvQuizStatistic extends Model
  {
    protected $table;

    public function __construct($attributes = [])
    {
      parent::__construct($attributes);
      $this->table = acadlix()->helper()->acadlix_wp_prefix("wp_adv_quiz_statistic");
    }

    public function question()
    {
      return $this->belongsTo(WpAdvQuizQuestion::class, "question_id", "id");
    }


    public function getAnswerDataAttribute($value)
    {
      // return $value;
      $answer_data = json_decode($value);
      $question = WpAdvQuizQuestion::find($this->question_id);
      if ($question) {
        switch ($question->answer_type) {
          case 'singleChoice':
          case 'multipleChoice':
            if (is_array($answer_data)) {
              $result = array_keys($answer_data, "1");
              $answer_data = empty($result) ? null : $result;
            }
            break;
          case 'sortingChoice':
            if (is_array($answer_data)) {
              $answer_data = array_map('intval', $answer_data);
            }
            break;
          case 'matrixSortingChoice':
            if (is_array($answer_data)) {
              $answer_data = array_map('intval', $answer_data);
              $question_answer_data = $question->answer_data['matrixSortingChoice'];
              $new_arr = [];
              if (is_array($question_answer_data)) {
                foreach ($question_answer_data as $key => $val) {
                  $new_arr[] = isset($answer_data[$key])
                    ? $answer_data[$key] > 0
                    ? $answer_data[$key]
                    : null
                    : null;
                }
              }
              $answer_data = empty($new_arr) ? null : (array_unique($new_arr) === [null] ? null : $new_arr);
            }
            break;
          case 'freeChoice':
          case 'fillInTheBlank':
            if (is_array($answer_data)) {
              $result = array_filter($answer_data, 'strlen');
              $answer_data = empty($result) ? null : $answer_data;
            }
            break;
        }
      }
      return $answer_data;
    }
  }
}