<?php
/**
 * Plugin activation handler.
 *
 * @package MasterQuiz
 * @since   1.0.0
 */

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

/**
 * Class MasterQuiz_Activator
 *
 * Handles tasks that run on plugin activation.
 *
 * @since 1.0.0
 */
class MasterQuiz_Activator {

	/**
	 * Run activation tasks.
	 *
	 * Sets default options, schedules cron events, and creates temp upload directory.
	 *
	 * @since 1.0.0
	 */
	public static function activate() {
		// Set default options if they don't exist.
		$defaults = array(
			'masterquiz_default_num_questions'  => 5,
			'masterquiz_default_quiz_mode'      => 'fast',
			'masterquiz_default_question_types' => array( 'mcq', 'true_false', 'essay' ),
			'masterquiz_max_pdf_size'           => 10,
			'masterquiz_temperature'            => 0.7,
			'masterquiz_rag_service_enabled'    => 0,
			'masterquiz_rag_service_timeout'    => 30,
			'masterquiz_auto_create_quiz'       => 1,
			'masterquiz_quiz_passing_percentage' => 80,
			'masterquiz_essay_grading'          => 'not-graded',
			'masterquiz_minimum_capability'     => 'edit_posts',
		);

		foreach ( $defaults as $key => $value ) {
			if ( false === get_option( $key ) ) {
				update_option( $key, $value );
			}
		}

		// Store plugin version for future upgrade checks.
		update_option( 'masterquiz_version', MASTERQUIZ_VERSION );

		// Schedule upload cleanup cron (every hour).
		if ( ! wp_next_scheduled( 'masterquiz_cleanup_uploads' ) ) {
			wp_schedule_event( time(), 'hourly', 'masterquiz_cleanup_uploads' );
		}

		// Create temp upload directory with .htaccess protection.
		$upload_dir = wp_upload_dir();
		$temp_dir   = trailingslashit( $upload_dir['basedir'] ) . 'masterquiz-temp';

		if ( ! is_dir( $temp_dir ) ) {
			wp_mkdir_p( $temp_dir );
		}

		// Initialize WP_Filesystem for file writes.
		global $wp_filesystem;
		if ( empty( $wp_filesystem ) ) {
			require_once ABSPATH . 'wp-admin/includes/file.php';
			WP_Filesystem();
		}

		// Create .htaccess and index.php only if WP_Filesystem initialized successfully.
		if ( $wp_filesystem ) {
			$htaccess = $temp_dir . '/.htaccess';
			if ( ! $wp_filesystem->exists( $htaccess ) ) {
				$rules = "Order deny,allow\nDeny from all\n";
				$wp_filesystem->put_contents( $htaccess, $rules, FS_CHMOD_FILE );
			}

			$index = $temp_dir . '/index.php';
			if ( ! $wp_filesystem->exists( $index ) ) {
				$wp_filesystem->put_contents( $index, '<?php // Silence is golden.', FS_CHMOD_FILE );
			}
		}

		// Flush rewrite rules.
		flush_rewrite_rules();
	}
}
