<?php
namespace QuizPress\Admin;

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

use QuizPress\Classes\QuestionExport;

class Export {
	public static function init() {
		$self = new self();
		add_action( 'admin_init', [ $self, 'question_export_data' ], -1 );
	}

	public function question_export_data() {
		// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.MissingUnslash
		$page = isset( $_GET['page'] ) ? sanitize_text_field( $_GET['page'] ) : '';
		// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.MissingUnslash
		$exportType = isset( $_GET['exportType'] ) ? sanitize_text_field( $_GET['exportType'] ) : '';
		if ( 'quizpress-questions' !== $page || 'questions' !== $exportType || ! current_user_can( 'manage_options' ) ) {
			return false;
		}
		// Verify nonce
		check_admin_referer( 'quizpress_nonce', 'security' );

		$QuestionExport = new QuestionExport();
		// Start Exporting
		$csv_data = $QuestionExport->get_questions_for_export();
		if ( ! count( $csv_data ) ) {
			return false;
		}
		$filename = 'quizpress-' . $exportType;
		$filename .= '.' . gmdate( 'Y-m-d' ) . '.csv';
		$QuestionExport->array_to_csv_download(
			$csv_data,
			$filename,
			false
		);
		exit();
	}
}
