<?php
namespace AcademyPro\Classes;

use Academy\Classes\ExportBase;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}


class QuizAttemptExport extends ExportBase {
	public function get_quiz_attempts_for_export() {
		$attempt_array = [];
		$empty_quiz_attempt = array(
			'quiz_title'         => '',
			'attempt_date'       => '',
			'course_title'       => '',
			'student_name'       => '',
			'total_questions'    => '',
			'answered_questions' => '',
			'correct_answers'    => '',
			'incorrect_answers'  => '',
			'total_marks'        => '',
			'earned_marks'       => '',
			'result'             => '',
		);

		$quiz_attempts = \AcademyQuizzes\Classes\Query::get_all_quiz_attempts();
		if ( count( $quiz_attempts ) ) {
			foreach ( $quiz_attempts as $attempt ) {
				$answered_question = $attempt->total_answered_questions;
				$attempt_info = json_decode( json_decode( $attempt->attempt_info ) );

				$attempt_array[] = [
					'quiz_title'         => get_the_title( $attempt->quiz_id ),
					'attempt_date'       => $attempt->attempt_started_at,
					'course_title'       => get_the_title( $attempt->course_id ),
					'student_name'       => ( get_userdata( $attempt->user_id ) )->user_login,
					'total_questions'    => $attempt->total_questions,
					'answered_questions' => $answered_question,
					'correct_answers'    => $attempt_info->total_correct_answers,
					'incorrect_answers'  => $answered_question - $attempt_info->total_correct_answers,
					'total_marks'        => $attempt->total_marks,
					'earned_marks'       => $attempt->earned_marks,
					'result'             => $attempt->attempt_status,
				];
			}//end foreach
			return $attempt_array;
		}//end if

		return array( $empty_quiz_attempt );
	}

	/**
	 * Method Overwrite
	 *
	 * Overwrite export base class method
	 *
	 * @param array          $array
	 * @param resource|false $fp
	 * @return void
	 */
	public function write_nested_csv( $array, $fp ) {
		foreach ( $array as $row ) {
			$flattenRow = $this->flatten_array( $row );
			if ( isset( $flattenRow['quiz_title'] ) ) {
				$row_header = array_keys( $flattenRow );
				fputcsv( $fp, $row_header );
			}
			fputcsv( $fp, $flattenRow );
			fputcsv( $fp, array() );
		}
	}
}
