<?php
/**
 * File upload handler.
 *
 * @package MasterQuiz
 * @since   1.0.0
 */

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

/**
 * Class MasterQuiz_Upload_Handler
 *
 * Handles PDF file uploads using WordPress upload functions.
 *
 * @since 1.0.0
 */
class MasterQuiz_Upload_Handler {

	/**
	 * Process a PDF file upload.
	 *
	 * @since 1.0.0
	 *
	 * @return array|WP_Error Upload data array on success, WP_Error on failure.
	 */
	public function process_upload() {
		if ( empty( $_FILES['pdf_file'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Missing -- nonce verified in AJAX handler.
			return new WP_Error( 'no_file', esc_html__( 'No file was uploaded.', 'masterquiz-ai' ) );
		}

		// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPress.Security.NonceVerification.Missing -- nonce verified in AJAX handler; file handled by wp_handle_upload().
		$file = $_FILES['pdf_file'];

		// Validate file type.
		$file_type = wp_check_filetype( sanitize_file_name( $file['name'] ), array( 'pdf' => 'application/pdf' ) );

		if ( empty( $file_type['type'] ) ) {
			return new WP_Error( 'invalid_type', esc_html__( 'Please upload a valid PDF file.', 'masterquiz-ai' ) );
		}

		// Validate file size.
		$max_size = absint( get_option( 'masterquiz_max_pdf_size', 10 ) ) * 1024 * 1024;

		if ( $file['size'] > $max_size ) {
			return new WP_Error(
				'file_too_large',
				sprintf(
					/* translators: %d: maximum file size in megabytes */
					esc_html__( 'File is too large. Maximum size is %d MB.', 'masterquiz-ai' ),
					absint( get_option( 'masterquiz_max_pdf_size', 10 ) )
				)
			);
		}

		// Set upload directory to our temp folder.
		add_filter( 'upload_dir', array( $this, 'custom_upload_dir' ) );

		$upload_overrides = array(
			'test_form' => false,
			'mimes'     => array( 'pdf' => 'application/pdf' ),
		);

		$result = wp_handle_upload( $file, $upload_overrides );

		remove_filter( 'upload_dir', array( $this, 'custom_upload_dir' ) );

		if ( isset( $result['error'] ) ) {
			return new WP_Error( 'upload_failed', $result['error'] );
		}

		// Store upload reference in transient.
		$upload_data = array(
			'file_path' => $result['file'],
			'file_url'  => $result['url'],
			'file_name' => sanitize_file_name( $file['name'] ),
			'file_size' => $file['size'],
			'timestamp' => time(),
		);

		set_transient(
			'masterquiz_upload_' . get_current_user_id(),
			$upload_data,
			HOUR_IN_SECONDS
		);

		return array(
			'file_id'   => md5( $result['file'] ),
			'file_name' => sanitize_file_name( $file['name'] ),
			'file_size' => $file['size'],
		);
	}

	/**
	 * Override upload directory to use our temp folder.
	 *
	 * @since 1.0.0
	 *
	 * @param array $dirs Upload directory data.
	 * @return array Modified upload directory data.
	 */
	public function custom_upload_dir( $dirs ) {
		$dirs['subdir'] = '/masterquiz-temp/' . get_current_user_id();
		$dirs['path']   = $dirs['basedir'] . $dirs['subdir'];
		$dirs['url']    = $dirs['baseurl'] . $dirs['subdir'];

		// Ensure directory exists.
		if ( ! is_dir( $dirs['path'] ) ) {
			wp_mkdir_p( $dirs['path'] );
		}

		return $dirs;
	}

	/**
	 * Clean up old uploaded files (older than 1 hour).
	 *
	 * Called via WP Cron hook: masterquiz_cleanup_uploads.
	 *
	 * @since 1.0.0
	 */
	public static function cleanup_old_uploads() {
		$upload_dir = wp_upload_dir();
		$temp_dir   = trailingslashit( $upload_dir['basedir'] ) . 'masterquiz-temp';

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

		$max_age = HOUR_IN_SECONDS;
		$now     = time();

		$iterator = new RecursiveIteratorIterator(
			new RecursiveDirectoryIterator( $temp_dir, RecursiveDirectoryIterator::SKIP_DOTS ),
			RecursiveIteratorIterator::CHILD_FIRST
		);

		foreach ( $iterator as $file ) {
			if ( $file->isFile() && ( $now - $file->getMTime() ) > $max_age ) {
				$filename = $file->getFilename();
				// Only delete PDF files and temp files, not .htaccess or index.php.
				if ( '.htaccess' !== $filename && 'index.php' !== $filename ) {
					wp_delete_file( $file->getRealPath() );
				}
			}
		}
	}
}
