<?php

namespace Yuvayana\AcadlixImporter\Models;

use Illuminate\Database\Eloquent\Model;

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

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

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

    public function statistics()
    {
      return $this->hasMany(WpAdvQuizStatistic::class, "statistic_ref_id", "statistic_ref_id");
    }

    public function getAccuracy()
    {
      if ($this->statistics()->count() == 0) {
        return 0;
      }
      $correct_count = $this->statistics()->where("correct_count", 1)->count();
      $solved_count = $this->statistics()->where("solved_count", 1)->count();

      if ($solved_count > 0 && $correct_count > 0) {
        return round($correct_count / $solved_count * 100, 2);
      }
      return 0;
    }

    public function getPoints()
    {
      if ($this->statistics()->count() == 0) {
        return 0;
      }
      $correct_points = $this->statistics()->where("correct_count", 1)->where("solved_count", 1)->sum("points");
      $incorrect_points = $this->statistics()
        ->where("incorrect_count", 1)
        ->where("solved_count", 1)
        ->with('question') // Load the related question
        ->get()
        ->sum(function ($statistic) {
          return $statistic->question ? $statistic->question->negative_points : 0;
        });

      return $correct_points - $incorrect_points;
    }

    public function getTotalPoints()
    {
      if ($this->statistics()->count() == 0) {
        return 0;
      }

      return $this->statistics()
        ->with('question') // Load the related question
        ->get()
        ->sum(function ($statistic) {
          return $statistic->question ? $statistic->question->points : 0;
        });
    }

    public function getResult()
    {
      if ($this->statistics()->count() == 0) {
        return 0;
      }

      if ($this->getTotalPoints() > 0) {
        return round($this->getPoints() / $this->getTotalPoints() * 100, 2);
      }

      return 0;
    }

  }
}