<?php

class Activity extends Eloquent
{

  public function section()
  {
    return $this->belongsTo('Section');
  }

  public function rubric()
  {
    //     return $this->belongsTo('Rubric');
    return $this->belongsToMany('Rubric', 'rubric_activity');
  }

  public function course()
  {
    return $this->belongsTo('Course');
  }

  public function assessed_students()
  {
    return $this->belongsToMany('Student', 'assessments')->withPivot('scores', 'percentage')->withTimestamps();
  }
  public function amount_of_assessed_students()
  {

    $activity_criterion = DB::table('activity_criterion')->where('activity_id', '=', $this->id)->lists('id');
    $amount_of_students = DB::table('assessments')->whereIn('activity_criterion_id', $activity_criterion)->lists('student_id');

    return count($amount_of_students);
  }

  public function criteria_achieved()
  {

    $activity_criterion = DB::table('activity_criterion')
      ->where('activity_id', '=', $this->id)
      ->get();

    $criteria_achieved = [];
    foreach ($activity_criterion as $index => $single_ac) {


      $assessments_passed = count(DB::table('assessments')
        ->where('score', '>=', $this->rubric[0]->expected_points)
        ->where('activity_criterion_id', '=', $single_ac->id)
        ->lists('student_id'));
      $assessments_attempted = count(DB::table('assessments')
        ->where('activity_criterion_id', '=', $single_ac->id)
        ->lists('student_id'));

      if ($assessments_attempted != 0 && (($assessments_passed / $assessments_attempted) * 100) >= $this->rubric[0]->expected_percentage) {
        $criteria_achieved[$single_ac->criterion_id] = 1;
      } else {
        $criteria_achieved[$single_ac->criterion_id] = 0;
      }
    }
    return  $criteria_achieved;
  }

  public function formativeActionsWithCriteria()
  {
    return DB::table('activity_criterion')
      ->join('transformative_activity_criterion', 'transformative_activity_criterion.activity_criterion_id', '=', 'activity_criterion.id')
      ->join('criteria', 'criteria.id', '=', 'activity_criterion.criterion_id')
      ->join('transformative_actions', 'transformative_actions.id', '=', 'transformative_activity_criterion.trans_action_id')
      ->where('activity_id', $this->id)
      ->get();
  }

  // cap_array
  public function getCapArrayAttribute()
  {
    $criteria_achieved_percentage = [];


    $criterias = DB::table('criteria')
      ->join('activity_criterion', 'activity_criterion.criterion_id', '=', 'criteria.id')
      ->join('assessments', 'activity_criterion.id', '=', 'assessments.activity_criterion_id')
      ->where('activity_criterion.activity_id', '=', $this->id)
      ->select(
        array(
          'activity_criterion.id as id',
          'activity_criterion.criterion_id as criterion_id',
          'activity_criterion.activity_id as activity_id'
        )
      )
      ->addSelect('criteria.name', 'criteria.subcriteria')
      ->get();

    foreach ($criterias as $index => $single_crit) {


      $single_crit->outcome_id = json_encode(DB::table('criterion_objective_outcome')
        ->where('criterion_id', '=', $single_crit->criterion_id)
        ->lists('outcome_id'));
      $amount_of_students = count(DB::table('assessments')
        ->where("activity_criterion_id", '=', $single_crit->id)
        ->lists('student_id'));


      $student_pass = DB::table('assessments')
        ->where("activity_criterion_id", '=', $single_crit->id)
        ->where('score', '>=', $this->rubric[0]->expected_points)
        ->lists('student_id');
      $amount_of_students_passed = count(DB::table('assessments')
        ->where("activity_criterion_id", '=', $single_crit->id)
        ->where('score', '>=', $this->rubric[0]->expected_points)
        ->lists('student_id'));

      $single_crit->score_percentage = ($amount_of_students_passed / $amount_of_students) * 100;

      //this is for criteria graph

      $single_crit->outcome_names_html = "<tr><td style='color:#e70033; padding:0'>Learning Outcomes:</td>";
      $outcome_names = DB::table('outcomes')
        ->whereIn('id', json_decode($single_crit->outcome_id))
        ->lists('name');
      foreach ($outcome_names as $index => $name) {
        $string_to_add = str_repeat("<td>" . $name . ", </td></tr>", ($index + 1) % 2) . str_repeat("<tr><td style='padding:0'>" . $name . ", </td>", $index % 2);
        $single_crit->outcome_names_html .= $string_to_add;
      }

      $single_crit->outcome_names_html .= str_repeat("<td></td></tr>", $index % 2);
      $criteria_achieved_percentage[$single_crit->criterion_id] = $single_crit;
    }
    return $criteria_achieved_percentage;
  }

  public function allActivityCriterionInfo()
  {

    $activity_criterion = DB::table('activity_criterion')
      ->join('criteria', 'criteria.id', '=', 'activity_criterion.criterion_id')
      ->where('activity_id', $this->id)
      ->select('activity_criterion.activity_id', 'activity_criterion.criterion_id', 'criteria.*')
      ->distinct()
      ->get();




    return $activity_criterion;
  }

  public function getOutcomeReport()
  {
    $outcomes = DB::table('activity_criterion')
      ->join('criterion_objective_outcome', 'activity_criterion.criterion_id', '=', 'criterion_objective_outcome.criterion_id')
      ->join('outcomes', 'outcomes.id', '=', 'criterion_objective_outcome.outcome_id')
      ->where('activity_criterion.activity_id', $this->id)
      ->select('outcomes.*')
      ->distinct()
      ->get();
    Log::info(json_encode($this));

    if (isset($this->rubric[0])) $rubric = $this->rubric[0];
    else $rubric = new stdClass();
    $outcomes_dict = [];
    foreach ($outcomes as $outcome) {
      $outcomes_dict[$outcome->id] = $outcome;
    }

    /*

    foreach($outcomes as $outcome){
      $ac_criteria = DB::table('criterion_objective_outcome as cobo')
      ->join('activity_criterion as ac','ac.criterion_id','=','cobo.criterion_id')
      ->where("outcome_id",$outcome->id)
      ->where("activity_id",$this->id)
      ->select('ac.*')
      ->distinct()
      ->get();
      $conteo_de_criterios = 0;
      $students_who_achieved =[];

      $outcome->students_attempted = DB::table("assessments")
      ->join("activity_criterion as ac", 'ac.id','=','assessments.activity_criterion_id')
      ->join("criterion_objective_outcome as cobo",'cobo.criterion_id','=','ac.criterion_id')
      ->where('outcome_id',$outcome->id)
      ->where('ac.activity_id',$this->id)
      ->count();
      

      foreach($ac_criteria as $criterion){
        $students_attempted = Criterion::students_attempted($criterion->criterion_id, $this->id);
        $students_achieved = DB::table('assessments')
				->join('activity_criterion', 'assessments.activity_criterion_id', '=', 'activity_criterion.id')
				->where('activity_criterion.id', $criterion->id)
				->where('assessments.score', '>=', $rubric->expected_points)
				->lists("student_id");
        if((count($students_achieved)/$students_attempted) * 100 >$rubric->expected_percentage){
          foreach($students_achieved as $stu_id){
            if(!array_key_exists($stu_id, $students_who_achieved)){
              $students_who_achieved[$stu_id] = 1;
            }
          }
          $conteo_de_criterios++;

        


        }

      }
      $outcome->students_achieved = count($students_who_achieved);

    }*/

    /* $students_attempted =  DB::table('assessments')
      ->join('activity_criterion', 'assessments.activity_criterion_id', '=', 'activity_criterion.id')
      ->where('activity_criterion.activity_id', $this->id)

      ->get();*/



    foreach ($outcomes_dict as $outcome) {

      // dame los criterios que son de este dominio, y de esta actividad.

      $ac_criteria = DB::table('criterion_objective_outcome as cobo')
        ->join('activity_criterion as ac', 'ac.criterion_id', '=', 'cobo.criterion_id')
        ->where("outcome_id", $outcome->id)
        ->where("activity_id", $this->id)
        ->select('ac.*')
        ->distinct()
        ->lists('id');

      /*$student_achieved = DB::table('assessments')
        ->whereIn('activity_criterion_id', $ac_criteria)
        ->where('score', '>=', $rubric->expected_points)
        ->groupBy('student_id')
        ->select('student_id', 'count(activity_criterion_id)');
      $students_attempted = DB::table('assessments as a')
        ->whereIn('a.activity_criterion_id', $ac_criteria)
        ->groupBy('a.student_id')
        ->leftJoin('assessments as b', function ($join) use ($ac_criteria, $rubric) {
          $join->on('b.student_id', '=', 'a.student_id')
            ->where('b.activity_criterion_id', '=', 'a.activity_criterion_id')
            ->where('b.score', '>=', $rubric->expected_points);
        })
        ->select('a.student_id', DB::raw('count(`a`.`activity_criterion_id`) attempted'), DB::raw('count(`b`.`activity_criterion_id`) achieved'));
      Log::info($students_attempted->get());*/

      $students_attempted = DB::table('assessments as a')
        ->whereIn('a.activity_criterion_id', $ac_criteria)
        ->groupBy('a.student_id')
        ->select(
          'a.student_id',
          DB::raw('count(`a`.`activity_criterion_id`) attempted'),
          DB::raw("count(case when score >= {$rubric->expected_points} then 1 else null end) as achieved")
        )->get();

      $outcome->attempted = count($students_attempted);

      $conteo_outcome_achieved = 0;

      foreach ($students_attempted as $student) {
        Log::info($student->achieved / $student->attempted * 100);
        if ($student->achieved / $student->attempted * 100 >= $outcome->expected_outcome) {
          $conteo_outcome_achieved++;
        }
      }
      Log::info(json_encode($outcome));

      $outcome->achieved = $conteo_outcome_achieved;
      if (isset($outcome->attempted) && $outcome->attempted != 0) $outcome->percentage = round(($outcome->achieved / $outcome->attempted * 100), 2);

      /*foreach ($students_attempted as $student) {
        $student_criteria[$student];
      }

      $conteo_de_criterios = 0;
      $students_who_achieved = [];
      foreach ($ac_criteria as $ac) {
        $students_attempted = DB::table("assessments")
          ->where('activity_criterion_id', $ac->id)
          ->get();
      }*/
    }
    return $outcomes_dict;
  }

  public function getTransformingActionAttribute()
  {
    return TransformativeAction::join('transformative_activity_criterion', 'trans_action_id', '=', 'transformative_actions.id')
      ->join('activity_criterion', 'activity_criterion.id', '=', 'transformative_activity_criterion.activity_criterion_id')
      ->where('activity_id', $this->id)->first();
  }
  // o_ach_array
  public function getOAchArrayAttribute($value)
  {
    /*
    $outcomes_achieved = [];
    $all_criterion = DB::table('activity_criterion')
      ->where('activity_criterion.activity_id', '=', $this->id)
      ->get();

    $attempted_criteria = 0;
    $passed_criteria = 0;

    $all_outcomes = DB::table('outcomes')->get();


    foreach ($all_criterion as $index => $activity_crit) {

      $amount_of_outcomes_attempted = DB::table('criterion_objective_outcome')
        ->join('outcomes', 'outcomes.id', '=', 'criterion_objective_outcome.outcome_id')
        ->where('criterion_id', '=', $activity_crit->criterion_id)
        ->select('criterion_objective_outcome.outcome_id')
        ->distinct()
        ->orderBy('criterion_objective_outcome.outcome_id')
        ->select('outcomes.id', 'outcomes.expected_outcome')
        ->get();
      $passed_criteria = count(DB::table('assessments')
        ->where('activity_criterion_id', '=', $activity_crit->id)
        ->where('score', '>=', $this->rubric[0]->expected_points)
        ->lists('student_id'));
      $attempted_criteria = count(DB::table('assessments')
        ->where('activity_criterion_id', '=', $activity_crit->id)
        ->lists('student_id'));
      Log::info("For activity_crit " . ($activity_crit->id));
      $percent_for_criteria = ($passed_criteria / $attempted_criteria) * 100;
      Log::info('Percent calculated' . $percent_for_criteria);


      $percent_for_criteria = ($passed_criteria / $attempted_criteria) * 100;

      foreach ($amount_of_outcomes_attempted as $index2 => $outcome) {

        if ($percent_for_criteria >= $this->rubric[0]->expected_percentage) {
          if (array_key_exists($outcome->id, $outcomes_achieved)) $outcomes_achieved[$outcome->id] += 1;
          else $outcomes_achieved[$outcome->id] = 1;
        }
      }
    }

    return $outcomes_achieved;*/

    $outcomes_achieved = [];

    $criteria_achieved = $this->criteria_achieved();


    $all_outcomes = DB::table('outcomes')->lists('id');

    foreach ($all_outcomes as $outcome_id) {
      $outcomes_achieved[$outcome_id] = 0;
    }

    foreach ($criteria_achieved as $criterion_id => $passed) {

      if ($passed == 1) {
        $outcomes_related = DB::table('criterion_objective_outcome')
          ->where("criterion_id", '=', $criterion_id)
          ->select('outcome_id')
          ->distinct()
          ->lists('outcome_id');

        foreach ($outcomes_related as $index => $outcome_id) {

          $outcomes_achieved[$outcome_id] += 1;
        }
      }
    }
    return $outcomes_achieved;
  }


  public function is_assessed()
  {
    $all_criterion = DB::table('activity_criterion')
      ->where('activity_criterion.activity_id', '=', $this->id)
      ->lists('id');

    $assessments = DB::table('assessments')
      ->whereIn('activity_criterion_id', $all_criterion)
      ->lists('id');

    //     return boolval(count($assessments));
    return (bool)(count($assessments));
  }

  public function isStudentAssessed($student_id)
  {
    return DB::table('activities')
      ->join('activity_criterion as ac', 'ac.activity_id', '=', 'activities.id')
      ->join('assessments', 'assessments.activity_criterion_id', '=', 'ac.id')
      ->where('activity_id', $this->id)
      ->where('student_id', $student_id)
      ->count();
  }
  public function transforming_actions()
  {
    $transformative_action = DB::table('activities')
      ->join('activity_criterion as ac', 'ac.activity_id', '=', 'activities.id')
      ->join('transformative_activity_criterion as tac', 'tac.activity_criterion_id', '=', 'ac.id')
      ->join('transformative_actions as ta', 'ta.id', '=', 'tac.trans_action_id')
      ->where('activities.id', $this->id)
      ->select('ta.*')
      ->first();
    if ($transformative_action)
      return $transformative_action->description;
    else return '';
  }

  // o_att_array

  public function getOAttArrayAttribute()
  {


    $outcomes_attempted = [];

    $all_criterion = DB::table('activity_criterion')
      ->join('assessments', 'assessments.activity_criterion_id', '=', 'activity_criterion.id')
      ->where('activity_criterion.activity_id', '=', $this->id)
      ->groupBy('criterion_id')

      ->lists('criterion_id');

    foreach ($all_criterion as $index => $criterion_id) {

      $amount_of_outcomes = DB::table('criterion_objective_outcome')
        ->where('criterion_id', '=', $criterion_id)
        ->select('criterion_objective_outcome.outcome_id')
        ->distinct()
        ->orderBy('criterion_objective_outcome.outcome_id')
        ->lists('outcome_id');

      foreach ($amount_of_outcomes as $index2 => $outcome_id) {
        if (array_key_exists($outcome_id, $outcomes_attempted)) $outcomes_attempted[$outcome_id] += 1;
        else $outcomes_attempted[$outcome_id] = 1;
      }
    }

    //return json_decode($this->outcomes_attempted, true);
    return $outcomes_attempted;
  }
}