<?php
namespace AcademyProAdvancedAnalytics\Admin;

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

use AcademyPro\Classes\AnalyticsExport;
use Academy\Classes\ExportBase;


class Export extends ExportBase {
	public static function init() {
		$self = new self();
		add_action( 'admin_init', [ $self, 'course_export_data' ] );
		add_action( 'admin_init', [ $self, 'student_export_data' ] );
	}

	public function course_export_data() {
		$page = isset( $_GET['page'] ) ? sanitize_text_field( wp_unslash( $_GET['page'] ) ) : '';
		$exportType = isset( $_GET['exportType'] ) ? sanitize_text_field( wp_unslash( $_GET['exportType'] ) ) : '';
		if ( 'academy' !== $page || 'course' !== $exportType || ! current_user_can( 'manage_options' ) ) {
			return false;
		}
		// Verify nonce
		check_admin_referer( 'academy_nonce', 'security' );

		$course_id = isset( $_GET['id'] ) ? sanitize_text_field( wp_unslash( $_GET['id'] ) ) : '';

		// Start Exporting
		$export = new AnalyticsExport();
		$csv_data = $export->course_analytics_data_export( $course_id );
		if ( ! count( $csv_data ) ) {
			return false;
		}
		$filename = 'academy-' . $exportType;
		$filename .= '.' . gmdate( 'Y-m-d' ) . '.csv';
		$export->array_to_csv_download(
			$csv_data,
			$filename,
			false
		);
		exit();
	}

	public function student_export_data() {
		$page = isset( $_GET['page'] ) ? sanitize_text_field( wp_unslash( $_GET['page'] ) ) : '';
		$exportType = isset( $_GET['exportType'] ) ? sanitize_text_field( wp_unslash( $_GET['exportType'] ) ) : '';
		if ( 'academy' !== $page || 'students' !== $exportType || ! current_user_can( 'manage_options' ) ) {
			return false;
		}
		// Verify nonce
		check_admin_referer( 'academy_nonce', 'security' );

		$student_id = isset( $_GET['id'] ) ? sanitize_text_field( wp_unslash( $_GET['id'] ) ) : '';

		// Start Exporting
		$export = new AnalyticsExport();
		$csv_data = $export->student_analytics_data_export( $student_id );
		if ( ! count( $csv_data ) ) {
			return false;
		}
		$filename = 'academy-' . $exportType;
		$filename .= '.' . gmdate( 'Y-m-d' ) . '.csv';
		$export->array_to_csv_download(
			$csv_data,
			$filename,
			false
		);
		exit();
	}
}
