<?php
namespace AcademyPro\Classes;

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

use Academy\Classes\ExportBase;


class AnalyticsExport extends ExportBase {

	public function student_analytics_data_export( $student_id ) {
		$response = [];
		$Analytics    = new \Academy\Classes\Analytics();
		$complete_course            = (int) $Analytics->get_total_number_of_completed_courses_by_student_id( $student_id );
		$course_taken               = (int) $Analytics->get_total_number_of_enrolled_courses( $student_id );
		$query = \Academy\Helper::get_enrolled_courses_by_user( $student_id, 'publish' );
		$response[] = array(
			'Enrolled Course'         => (int) $course_taken,
			'Complete Course'         => (int) $complete_course,
			'Inprogress Course'       => (int) $course_taken - $complete_course,
			'Total Reviews'           => (int) $Analytics->get_total_number_of_reviews( $student_id ),
		);
		$student_data = array(
			'Course Title'            => '',
			'Enroll Date'             => '',
			'Lessons'                 => 0,
			'Complete Lessons'        => 0,
			'Quizzes'                 => 0,
			'Complete Quizzes'        => 0,
			'Assignments'             => 0,
			'Complete Assignments'    => 0,
			'Bookings'                => 0,
			'Complete Bookings'       => 0,
			'Meetings'                => 0,
			'Complete Meetings'       => 0,
			'Progress'                => '0%'
		);
		if ( $query && $query->have_posts() ) {
			while ( $query->have_posts() ) :
				$query->the_post();
				$course_id = get_the_ID();
				$enrolled = \Academy\Helper::is_enrolled( $course_id, $student_id );
				$course_curriculums = \Academy\Helper::get_course_curriculums_number_of_counts( $course_id );
				$total_completed_topics = \Academy\Helper::get_total_number_of_completed_course_topics_by_course_and_student_id( $course_id, $student_id );
				$percentage              = \Academy\Helper::calculate_percentage( $course_curriculums['total_topics'], $total_completed_topics );
				$complete_topics = \Academy\Helper::get_completed_course_topics_by_course_and_student_id( $course_id, $student_id );
				$response[] = [
					'Course Title'                  => html_entity_decode( get_the_title() ),
					'Enroll Date'             => $enrolled->post_date,
					'Lessons'                 => (int) $course_curriculums['total_lessons'],
					'Complete Lessons'        => (int) isset( $complete_course['lesson'] ) ? count( $complete_topics['lesson'] ) : 0,
					'Quizzes'                 => (int) $course_curriculums['total_quizzes'],
					'Complete Quizzes'        => (int) isset( $complete_course['quiz'] ) ? count( $complete_topics['quiz'] ) : 0,
					'Assignments'             => (int) $course_curriculums['total_assignments'],
					'Complete Assignments'    => (int) isset( $complete_course['assignment'] ) ? count( $complete_topics['assignment'] ) : 0,
					'Bookings'                => (int) $course_curriculums['total_tutor_bookings'],
					'Complete Bookings'       => (int) isset( $complete_course['booking'] ) ? count( $complete_topics['booking'] ) : 0,
					'Meetings'                => (int) $course_curriculums['total_zoom_meetings'],
					'Complete Meetings'       => (int) isset( $complete_course['zoom'] ) ? count( $complete_topics['zoom'] ) : 0,
					'Progress'                => (int) $percentage . '%',
				];
			endwhile;
		} else {
			$response[] = $student_data;
		}//end if

		return $response;
	}

	public function course_analytics_data_export( $course_id ) {
		$analytics_data = array();
		$Analytics = new \Academy\Classes\Analytics();
		$course_curriculums = \Academy\Helper::get_course_curriculums_number_of_counts( $course_id );
		$analytics_data[] = array(
			'Total Questions'     => (int) $Analytics->get_number_of_questions_by_course_id( $course_id ),
			'Total Instructors'   => (int) $Analytics->get_total_number_of_instructors( $course_id ),
			'Total Enrolled'      => (int) $Analytics->get_total_number_of_enrolled_by_course_id( $course_id ),
			'Total Lessons'       => (int) $course_curriculums['total_lessons'],
			'Total Quizzes'       => (int) $course_curriculums['total_quizzes'],
			'Total Assignments'   => (int) $course_curriculums['total_assignments'],
			'Total Bookings'      => (int) $course_curriculums['total_tutor_bookings'],
			'Total Meetings'      => (int) $course_curriculums['total_zoom_meetings'],
			'Total Reviews'       => (int) $Analytics->get_total_number_of_reviews_by_course_id( $course_id ),
		);

		$instructors = get_users( array(
			// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key 
			'meta_key' => 'academy_instructor_course_id',
			// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_value
			'meta_value' => $course_id,
		) );
		foreach ( $instructors as $ins ) {
			$review = \Academy\Helper::get_instructor_ratings( $ins->ID );
			$analytics_data[] = array(
				'Instructor Name'    => $ins->display_name,
				'Total Courses'      => (int) count_user_posts( $ins->ID, 'academy_courses' ),
				'Total Students'     => (int) \Academy\Helper::get_total_number_of_students_by_instructor( $ins->ID ),
				'Total Rating'       => $review->rating_avg . '(Reviews' . $review->rating_count . ')',
			);
		}
		$course_data = array(
			'Student Name'         => '',
			'Email Address'        => '',
			'Enroll Date'          => '',
			'Complete Lessons'     => 0,
			'Complete Quizzes'     => 0,
			'Complete Assignments' => 0,
			'Complete Bookings'    => 0,
			'Complete Meetings'    => 0,
			'Progress'             => '0%',
		);
		$enroll_courses = get_posts( array(
			'post_parent' => $course_id,
			'numberposts' => -1,
			'post_status' => 'completed',
			'post_type'   => 'academy_enrolled',
		) );
		if ( $enroll_courses ) {
			foreach ( $enroll_courses as $enroll_course ) {
				$user_id = $enroll_course->post_author;
				$completed_topics = \Academy\Helper::get_total_number_of_completed_course_topics_by_course_and_student_id( $course_id, $user_id );
				$student_complete_topics = \Academy\Helper::get_completed_course_topics_by_course_and_student_id( $course_id, $user_id );
				$user = get_userdata( $user_id );
				$timestamp = strtotime( $enroll_course->post_date );
				$date = gmdate( 'Y-m-d', $timestamp );

				$analytics_data[] = array(
					'Student Name'         => $user->display_name,
					'Email Address'        => $user->user_email,
					'Enroll Date'          => $date,
					'Complete Lessons'     => (int) count( $student_complete_topics['lesson'] ?? [] ),
					'Complete Quizzes'     => (int) count( $student_complete_topics['quiz'] ?? [] ),
					'Complete Assignments' => (int) count( $student_complete_topics['assignment'] ?? [] ),
					'Complete Bookings'    => (int) count( $student_complete_topics['booking'] ?? [] ),
					'Complete Meetings'    => (int) count( $student_complete_topics['zoom'] ?? [] ),
					'Progress'             => \Academy\Helper::calculate_percentage( $course_curriculums['total_topics'], $completed_topics ) . '%',
				);
			}
		} else {
			$analytics_data[] = $course_data;
		}//end if

		return $analytics_data;
	}

	/**
	 * Method Overwrite
	 *
	 * Overwrite export base class method
	 *
	 * @param array          $array
	 * @param resource|false $fp
	 * @return void
	 */
	public function write_nested_csv( $array, $fp ) {
		$previousItem = array();
		foreach ( $array as $row ) {
			$flattenRow = $this->flatten_array( $row );
			if ( isset( $flattenRow['Total Questions'] ) || ( isset( $flattenRow['Student Name'] ) && ! isset( $previousItem['Student Name'] ) ) || ( isset( $flattenRow['Instructor Name'] ) && ! isset( $previousItem['Instructor Name'] ) ) ) {
				$row_header = array_keys( $flattenRow );

				if ( isset( $flattenRow['Student Name'] ) || isset( $flattenRow['Instructor Name'] ) ) {
					fputcsv( $fp, array() );
					fputcsv( $fp, array() );
					fputcsv( $fp, array() );
				}
				fputcsv( $fp, $row_header );

			} elseif ( isset( $flattenRow['Enrolled Course'] ) || ( isset( $flattenRow['Course Title'] ) && ! isset( $previousItem['Course Title'] ) ) ) {
				$row_header = array_keys( $flattenRow );

				if ( isset( $flattenRow['Course Title'] ) ) {
					fputcsv( $fp, array() );
				}

				fputcsv( $fp, $row_header );
			}

			fputcsv( $fp, $row );
			$previousItem = $row;
		}//end foreach
	}
}
