<?php
/**
 * ST_Ielts_lms_Admin setup
 *
 * @package Ielts_lms
 * @since   1.0.0
 */

defined( 'ABSPATH' ) || exit;

/**
 *
 * @class Ielts_Lms
 */
class ST_ProQyz_Admin {

	/**
	 * Ielts_Lms version.
	 *
	 * @var string
	 */
	public $version = ST_VERSION;
    private static $instance;

    public static $page_title = 'ProQyz';

	/**
	 * Plugin slug
	 *
	 * @since 4.0.0
	 * @var string $plugin_slug
	 */
	public static $plugin_slug = ST_PROQYZ_SLUG;
	public $menu_items = [];

    /**
	 * Main Ielts_Lms Instance.
	 *
	 * Ensures only one instance of Ielts_Lms is loaded or can be loaded.
	 *
	 * @since 1.0
	 * @static
	 * @see ST()
	 * @return Ielts_Lms - Main instance.
	 */
	public static function get_instance() {
		if ( ! isset( self::$instance ) ) {
			/** @psalm-suppress InvalidPropertyAssignmentValue */ // phpcs:ignore Generic.Commenting.DocComment.MissingShort
			self::$instance = new self();
			/** @psalm-suppress InvalidPropertyAssignmentValue */ // phpcs:ignore Generic.Commenting.DocComment.MissingShort
		}
		return self::$instance;
	}

    /**
	 * Ielts_Lms Constructor.
	 */
	public function __construct() {
		$this->init_sample_data();
		$this->init_hooks(); // pending
		$this->includes(); // done
		// admin notice for speaking ai evaluation staus
		add_action('admin_notices', [$this, 'admin_notice_speaking_ai_evaluation_status']);
	}


	public function admin_notice_speaking_ai_evaluation_status(){
		if(defined('ST_PROQYZ_SPEAKING_AI_EVALUAION') && ST_PROQYZ_SPEAKING_AI_EVALUAION == 'true'){
			
		} else {
			echo '<div class="notice notice-error is-dismissible"><p><b>ProQyz:</b> AI Speaking Evaluation is disabled (due to its under development).</p></div>';
		}
	}

	/**
	 * init sample data
	 */
	public function init_sample_data(){
		$plugin_dir = plugin_dir_url(ST_PROQYZ_PLUGIN_FILE);
		$astra_icon = $plugin_dir . '/includes/admin/dist/svg/proqyz.svg';

		$this->menu_items = (array) [
			(object) [
				"page_title" 	=> self::$page_title,
				"menu_title"	=> self::$page_title,
				"is_external"	=> false,
				"target"		=> [$this, 'page_home'],
				"page_slug"		=> self::$plugin_slug,
				"capability"	=> "manage_options",
				"menu_type"		=> "menu",
				"icon"			=> $astra_icon
			],
			(object) [
				"page_title" 	=> __( 'ProQyz App', self::$plugin_slug ),
				"menu_title"	=> __( '<div style="display:flex;align-items:center;">ProQyz App <span style="margin-left:5px;" class="dashicons dashicons-external"></span></div>', self::$plugin_slug ),
				"is_external"	=> true,
				"target"		=> [$this, 'page_proqyz_redirect'],
				"parent_slug"	=> self::$plugin_slug,
				"page_slug"		=> self::$plugin_slug."-proqyz-app",
				"capability"	=> "manage_options",
				"menu_type"		=> "submenu",
				"icon"			=> ""
			],
			// (object) [
			// 	"page_title" 	=> __( 'Groups', self::$plugin_slug ),
			// 	"menu_title"	=> __( 'Groups', self::$plugin_slug ),
			// 	"is_external"	=> false,
			// 	"target"		=> [$this, 'page_groups'],
			// 	"parent_slug"	=> self::$plugin_slug,
			// 	"page_slug"		=> self::$plugin_slug."-groups",
			// 	"capability"	=> "manage_options",
			// 	"menu_type"		=> "submenu",
			// 	"icon"			=> ""
			// ],
			(object) [
				"page_title" 	=> __( 'Course Access', self::$plugin_slug ),
				"menu_title"	=> __( 'Course Access', self::$plugin_slug ),
				"is_external"	=> false,
				"target"		=> [$this, 'page_course_access'],
				"parent_slug"	=> self::$plugin_slug,
				"page_slug"		=> self::$plugin_slug."-course-access",
				"capability"	=> "manage_options",
				"menu_type"		=> "submenu",
				"icon"			=> ""
			],
			(object) [
				"page_title" 	=> __( 'Evaluation', self::$plugin_slug ),
				"menu_title"	=> __( 'Evaluation', self::$plugin_slug ),
				"is_external"	=> false,
				"target"		=> [$this, 'page_evaluation'],
				"parent_slug"	=> self::$plugin_slug,
				"page_slug"		=> self::$plugin_slug."-evaluation",
				"capability"	=> "manage_options",
				"menu_type"		=> "submenu",
				"icon"			=> ""
			],
			(object) [
				"page_title" 	=> __( 'Login Settings', self::$plugin_slug ),
				"menu_title"	=> __( 'Login Settings', self::$plugin_slug ),
				"is_external"	=> false,
				"target"		=> [$this, 'page_login_settings'],
				"parent_slug"	=> self::$plugin_slug,
				"page_slug"		=> self::$plugin_slug."-login-settings",
				"capability"	=> "manage_options",
				"menu_type"		=> "submenu",
				"icon"			=> ""
			],
			(object) [
				"page_title" 	=> __( 'Emails', self::$plugin_slug ),
				"menu_title"	=> __( 'Emails', self::$plugin_slug ),
				"is_external"	=> false,
				"target"		=> [$this, 'page_emails'],
				"parent_slug"	=> self::$plugin_slug,
				"page_slug"		=> self::$plugin_slug."-emails",
				"capability"	=> "manage_options",
				"menu_type"		=> "submenu",
				"icon"			=> ""
			],
			(object) [
				"page_title" 	=> __( 'Addons', self::$plugin_slug ),
				"menu_title"	=> __( 'Addons', self::$plugin_slug ),
				"is_external"	=> false,
				"target"		=> [$this, 'page_addons'],
				"parent_slug"	=> self::$plugin_slug,
				"page_slug"		=> self::$plugin_slug."-addons",
				"capability"	=> "manage_options",
				"menu_type"		=> "submenu",
				"icon"			=> ""
			],
			(object) [
				"page_title" 	=> __( 'Settings', self::$plugin_slug ),
				"menu_title"	=> __( 'Settings', self::$plugin_slug ),
				"is_external"	=> false,
				"target"		=> [$this, 'page_settings'],
				"parent_slug"	=> self::$plugin_slug,
				"page_slug"		=> self::$plugin_slug."-settings",
				"capability"	=> "manage_options",
				"menu_type"		=> "submenu",
				"icon"			=> ""
			],
			(object) [
				"page_title" 	=> __( 'License Key', self::$plugin_slug ),
				"menu_title"	=> __( 'License Key', self::$plugin_slug ),
				"is_external"	=> false,
				"target"		=> [$this, 'page_license_key'],
				"parent_slug"	=> self::$plugin_slug,
				"page_slug"		=> self::$plugin_slug."-license-key",
				"capability"	=> "manage_options",
				"menu_type"		=> "submenu",
				"icon"			=> ""
			],
			/*
			(object) [
				"page_title" 	=> __( 'Settings', self::$plugin_slug ),
				"menu_title"	=> __( 'Settings', self::$plugin_slug ),
				"is_external"	=> false,
				"target"		=> [$this, 'page_settings'],
				"parent_slug"	=> self::$plugin_slug,
				"page_slug"		=> self::$plugin_slug."-settings",
				"capability"	=> "manage_options",
				"menu_type"		=> "submenu",
				"icon"			=> ""
			],
			
			(object) [
				"page_title" 	=> __( 'Shortcodes', self::$plugin_slug ),
				"menu_title"	=> __( 'Shortcodes', self::$plugin_slug ),
				"is_external"	=> false,
				"target"		=> [$this, 'page_shortcodes'],
				"parent_slug"	=> self::$plugin_slug,
				"page_slug"		=> self::$plugin_slug."-shortcodes",
				"capability"	=> "manage_options",
				"menu_type"		=> "submenu",
				"icon"			=> ""
			], 
			*/
			(object) [
				"page_title" 	=> __( 'Support', self::$plugin_slug ),
				"menu_title"	=> __( 'Support', self::$plugin_slug ),
				"is_external"	=> false,
				"target"		=> [$this, 'page_support'],
				"parent_slug"	=> self::$plugin_slug,
				"page_slug"		=> self::$plugin_slug."-support",
				"capability"	=> "manage_options",
				"menu_type"		=> "submenu",
				"icon"			=> ""
			]
			
		];
	}

    /**
	 * init hooks
	 */
	public function init_hooks(){
		add_action( 'admin_menu', array( $this, 'setup_menu' ) );
		add_action( 'admin_enqueue_scripts', [ $this, 'enqueue_admin_styles' ] );
		add_action( 'admin_enqueue_scripts', [ $this, 'enqueue_admin_scripts' ] );
		add_action( 'admin_footer', [$this, 'in_footer']);
		add_action( 'delete_user', [ $this, 'delete_user_submissions' ], 10, 1 );
		add_action( 'proqyz_delete_user_submissions', [ $this, 'process_user_submissions_deletion' ], 10, 1 );
	}

	
	/**
	 * Include required core files used in admin and on the frontend.
	 */
	public function includes() { 
        require_once ST_PROQYZ_ABSPATH . "/includes/admin/ajax/admin-ajax.php"; // checked
    }

    public function page_home() {
		require_once ST_PROQYZ_ABSPATH . "/includes/admin/class-st-proqyz-admin-page-home.php";
		echo ST_ProQyz_Admin_Page_Home::get_page_layout();
	}
	public function page_groups() {
		require_once ST_PROQYZ_ABSPATH . "/includes/admin/class-st-proqyz-admin-page-groups.php";
		echo ST_ProQyz_Admin_Page_Groups::get_page_layout();
	}

	public function page_course_access() {
		require_once ST_PROQYZ_ABSPATH . "/includes/admin/class-st-proqyz-admin-page-course-access.php";
		echo ST_ProQyz_Admin_Page_Course_Access::get_page_layout();
	}

	public function page_evaluation() {
		require_once ST_PROQYZ_ABSPATH . "/includes/admin/class-st-proqyz-admin-page-evaluation.php";
		echo ST_ProQyz_Admin_Page_Evaluation::get_page_layout();
	}

	public function page_login_settings() {
		require_once ST_PROQYZ_ABSPATH . "/includes/admin/class-st-proqyz-admin-page-login-settings.php";
		echo ST_ProQyz_Admin_Page_Login_Settings::get_page_layout();
	}
	public function page_license_key() {
		require_once ST_PROQYZ_ABSPATH . "/includes/admin/class-st-proqyz-admin-page-license-key.php";
		echo ST_ProQyz_Admin_Page_License_key::get_page_layout();
	}
	public function page_addons() {
		require_once ST_PROQYZ_ABSPATH . "/includes/admin/class-st-proqyz-admin-page-addons.php";
		echo ST_ProQyz_Admin_Page_Addons::get_page_layout();
	}
	public function page_support() {
		require_once ST_PROQYZ_ABSPATH . "/includes/admin/class-st-proqyz-admin-page-support.php";
		echo ST_ProQyz_Admin_Page_Support::get_page_layout();
	}

	public function page_settings() {
		require_once ST_PROQYZ_ABSPATH . "/includes/admin/class-st-proqyz-admin-page-settings.php";
		echo ST_ProQyz_Admin_Page_Settings::get_page_layout();
	}

	public function page_shortcodes() {
		require_once ST_PROQYZ_ABSPATH . "/includes/admin/class-st-proqyz-admin-page-shortcodes.php";
		echo ST_ProQyz_Admin_Page_Shortcodes::get_page_layout();
	}

	public function page_proqyz_redirect() {
		wp_redirect('https://app.proqyz.com');
		exit;
	}

	public function page_emails() {
		require_once ST_PROQYZ_ABSPATH . "/includes/admin/class-st-proqyz-admin-page-emails.php";
		echo ST_ProQyz_Admin_Page_Emails::get_page_layout();
	}


	public static function admin_page_plans(){
		require_once ST_PROQYZ_ABSPATH . "/includes/admin/class-st-proqyz-admin-page-plans.php"; // checked
		$plans = new ST_ProQyz_Admin_Page_Plans(ST_ProQyz_Admin::$plugin_slug);
		$plans->get_page_layout();
	}

	public function setup_menu() {
		global $submenu;
		$capability = 'manage_options';
		if ( ! current_user_can( $capability ) ) {
			return;
		}

		$priority   = apply_filters( 'st_menu_priority', 40 );
		if( count($this->menu_items) > 0 ) {
			foreach( $this->menu_items as $mkey => $menu_item ) {
				if( $menu_item->menu_type == "menu" ) {
					add_menu_page( // phpcs:ignore WPThemeReview.PluginTerritory.NoAddAdminPages.add_menu_pages_add_menu_page -- Taken the menu on top level
						$menu_item->page_title,
						$menu_item->menu_title,
						$menu_item->capability,
						$menu_item->page_slug,
						$menu_item->target,
						$menu_item->icon,
						$priority
					);
				} else if( $menu_item->menu_type == "submenu" ) {
					add_submenu_page( // phpcs:ignore WPThemeReview.PluginTerritory.NoAddAdminPages.add_menu_pages_add_submenu_page -- Taken the menu on top level
						$menu_item->parent_slug,
						$menu_item->page_title,
						$menu_item->menu_title,
						$menu_item->capability,
						$menu_item->page_slug,
						$menu_item->target,
					);
				}
			}
		}

		// Rename to Home menu.
		$submenu[ self::$plugin_slug ][0][0] = __( 'Home', self::$plugin_slug ); // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited -- Required to rename the home menu.
	}


	public function enqueue_admin_styles(){
		$plugin_dir = plugin_dir_url(ST_PROQYZ_PLUGIN_FILE);
		wp_enqueue_style('proqyz-admin-css', $plugin_dir . '/includes/admin/dist/css/proqyz-admin.css', array(), $this->version );
		if( isset($_GET['page']) && !empty($_GET['page']) ) {
			
			if( $_GET['page'] === "st-proqyz-groups" || $_GET['page'] === "st-proqyz-course-access"){
				wp_enqueue_style('proqyz-admin-manage-css', $plugin_dir . '/includes/admin/dist/css/proqyz-admin-manage.css', array(), $this->version );
				wp_enqueue_style('proqyz-admin-toastr-css', 'https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.css', array(), '1.0');
				wp_enqueue_style('proqyz-admin-bootstrap-css', 'https://cdn.jsdelivr.net/npm/bootstrap@3.4.1/dist/css/bootstrap.min.css', array(), '3.4');
			} else if ( $_GET['page'] === "st-proqyz-license-key" ) {
				wp_enqueue_style('proqyz-admin-bootstrap-css', 'https://cdn.jsdelivr.net/npm/bootstrap@3.4.1/dist/css/bootstrap.min.css', array(), '3.4');
			} else if( $_GET['page'] === "st-proqyz-support" ) {
				wp_enqueue_style('proqyz-admin-bootstrap-css', 'https://cdn.jsdelivr.net/npm/bootstrap@3.4.1/dist/css/bootstrap.min.css', array(), '3.4');
			} else if( $_GET['page'] === "st-proqyz" ) {
				wp_enqueue_style('proqyz-admin-css', $plugin_dir . '/includes/admin/dist/css/proqyz-admin.css', array(), $this->version );
				wp_enqueue_style('proqyz-admin-plyr-css', 'https://cdn.plyr.io/3.6.8/plyr.css', array(), '3.6.8');
				wp_enqueue_style('proqyz-admin-bootstrap-css', 'https://cdn.jsdelivr.net/npm/bootstrap@3.4.1/dist/css/bootstrap.min.css', array(), '3.4');
			} else if( $_GET['page'] === "st-proqyz-settings") {
				// wp_enqueue_style('proqyz-admin-bootstrap-css', 'https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css', array(), '5.1.3');
			
			}
		}
	}

	public function enqueue_admin_scripts(){
		// Enqueue your plugin's stylesheet
		$plugin_dir = plugin_dir_url(ST_PROQYZ_PLUGIN_FILE);
		if( isset($_GET['page']) && !empty($_GET['page']) ) {
			if( $_GET['page'] === "st-proqyz-groups" || $_GET['page'] === "st-proqyz-course-access" ){
				wp_enqueue_script('st-proqyz-admin-bootstrap-js', 'https://cdn.jsdelivr.net/npm/bootstrap@3.4.1/dist/js/bootstrap.min.js', array('jquery'), '3.4');
				wp_enqueue_script('st-proqyz-admin-toastr-js', 'https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js', array('jquery'), '1.0');
				wp_enqueue_script('st-proqyz-admin-manage-js', $plugin_dir . '/includes/admin/dist/js/proqyz-admin-manage.js', array(), $this->version );
			} else if ( $_GET['page'] === "st-proqyz-license-key" ) {
				wp_enqueue_script('st-proqyz-admin-bootstrap-js', 'https://cdn.jsdelivr.net/npm/bootstrap@3.4.1/dist/js/bootstrap.min.js', array('jquery'), '3.4');
				wp_enqueue_script('st-proqyz-admin-main-js', $plugin_dir . '/includes/admin/dist/js/proqyz-admin.js', array(), $this->version );
			} else if( $_GET['page'] === "st-proqyz" ) {
				wp_enqueue_script('st-proqyz-admin-plyr-js', 'https://cdn.plyr.io/3.6.8/plyr.js', array('jquery'), '3.6.8');
				wp_enqueue_script('st-proqyz-admin-main-js', $plugin_dir . '/includes/admin/dist/js/proqyz-admin.js', array(), $this->version );
			} else if( $_GET['page'] === "st-proqyz-emails") {
				/* wp_enqueue_script(
					'proqyz-tinymce-email-templates',
					$plugin_dir . '/includes/admin/dist/js/tinymce-email-templates-plugin.js',
					array('jquery', 'wp-tinymce'),
					'1.0',
					true
				);
		
				wp_localize_script('proqyz-tinymce-email-templates', 'proqyz_tinymce_email_templates', array(
					'ajax_url' => admin_url('admin-ajax.php')
				)); */
			}
		}
	}

	public function in_footer(){
		if(isset($_GET['page']) && $_GET['page'] == "st-proqyz-support"){ ?>
		<!--Start of Tawk.to Script-->
		<script type="text/javascript">
			var Tawk_API=Tawk_API||{}, Tawk_LoadStart=new Date();
			(function(){
			var s1=document.createElement("script"),s0=document.getElementsByTagName("script")[0];
			s1.async=true;
			s1.src='https://embed.tawk.to/66030865a0c6737bd1251ab2/1hptthjv5';
			s1.charset='UTF-8';
			s1.setAttribute('crossorigin','*');
			s0.parentNode.insertBefore(s1,s0);
			})();
		</script>
		<!--End of Tawk.to Script-->
		<?php }
		?>
		<script>
			document.addEventListener('DOMContentLoaded', function() {
				var menuItem = document.querySelector('a[href="admin.php?page=st-proqyz-proqyz-app"]');
				if (menuItem) {
					menuItem.setAttribute('target', '_blank');
					menuItem.setAttribute('href', 'https://app.proqyz.com');
					console.log(menuItem);
				}
			});
		</script>
		<?php 
	}

	/**
	 * Delete all submissions for a user when user is deleted from WordPress
	 * 
	 * This hook fires when a user is deleted from WordPress admin.
	 * It checks the number of submissions and either processes immediately
	 * (for small amounts) or schedules background deletion via WP Cron.
	 * 
	 * @param int $user_id The ID of the user being deleted
	 */
	public function delete_user_submissions( $user_id ) {
		global $wpdb, $table_proqyz_v3_progress_submissions;

		if ( ! $user_id || ! is_numeric( $user_id ) ) {
			return;
		}

		$user_id = absint( $user_id );

		// Define table names (use v3 tables with fallback)
		$submissions_table = !empty($table_proqyz_v3_progress_submissions) 
			? $table_proqyz_v3_progress_submissions 
			: $wpdb->prefix . 'st_proqyz_progress_submissions';

		// Get count of submissions for this user
		$submission_count = $wpdb->get_var( $wpdb->prepare(
			"SELECT COUNT(*) FROM {$submissions_table} WHERE user_id = %d AND status = 1",
			$user_id
		) );

		if ( empty( $submission_count ) ) {
			return; // No submissions to delete
		}

		// If there are many submissions, schedule background deletion
		// Otherwise, process immediately (faster for small amounts)
		$batch_threshold = 50; // Process immediately if less than 50 submissions
		
		if ( $submission_count > $batch_threshold ) {
			// Schedule background deletion via WP Cron
			$this->schedule_user_submissions_deletion( $user_id );
		} else {
			// Process immediately for small amounts
			$this->process_user_submissions_deletion( $user_id );
		}
	}

	/**
	 * Schedule background deletion of user submissions
	 * 
	 * @param int $user_id The user ID
	 */
	private function schedule_user_submissions_deletion( $user_id ) {
		// Store user_id in transient for the cron job (expires in 1 day)
		// This allows us to verify the deletion is still needed when cron runs
		$transient_key = 'proqyz_delete_user_' . $user_id;
		set_transient( $transient_key, $user_id, DAY_IN_SECONDS );
		
		// Schedule immediate cron job (runs on next page load)
		// WP Cron will execute this in the background
		wp_schedule_single_event( time(), 'proqyz_delete_user_submissions', array( $user_id ) );
	}

	/**
	 * Process deletion of user submissions (with batching support)
	 * 
	 * This method handles the actual deletion in batches to avoid memory/timeout issues.
	 * It can be called directly or via WP Cron.
	 * 
	 * @param int $user_id The user ID
	 */
	public function process_user_submissions_deletion( $user_id ) {
		global $wpdb,
			$table_proqyz_v3_progress_submissions,
			$table_proqyz_v3_progress_submissions_meta,
			$table_proqyz_v3_progress_meta_submissions,
			$table_proqyz_v3_submissions_review,
			$table_proqyz_v3_submissions_review_meta,
			$table_proqyz_v3_submissions_versioning,
			$table_proqyz_v3_progress_submissions_user_response,
			$table_proqyz_v3_progress_submissions_session,
			$table_proqyz_v3_progress_submissions_score,
			$table_proqyz_v3_submissions_evaluation_meta,
			$table_proqyz_fullmock_tests_progress;

		if ( ! $user_id || ! is_numeric( $user_id ) ) {
			return;
		}

		$user_id = absint( $user_id );

		// Increase execution time for this operation
		@set_time_limit( 300 ); // 5 minutes
		@ini_set( 'max_execution_time', 300 );

		// Define table names (use v3 tables with fallback to v2)
		$submissions_table = !empty($table_proqyz_v3_progress_submissions) 
			? $table_proqyz_v3_progress_submissions 
			: $wpdb->prefix . 'st_proqyz_progress_submissions';
		$meta_table = !empty($table_proqyz_v3_progress_submissions_meta) 
			? $table_proqyz_v3_progress_submissions_meta 
			: $wpdb->prefix . 'st_proqyz_progress_submissions_meta';
		$review_table = !empty($table_proqyz_v3_submissions_review) 
			? $table_proqyz_v3_submissions_review 
			: $wpdb->prefix . 'st_proqyz_quiz_progress_review';
		$review_meta_table = !empty($table_proqyz_v3_submissions_review_meta) 
			? $table_proqyz_v3_submissions_review_meta 
			: $wpdb->prefix . 'st_proqyz_quiz_progress_review_meta';
		$progress_meta_submissions_table = !empty($table_proqyz_v3_progress_meta_submissions) 
			? $table_proqyz_v3_progress_meta_submissions 
			: $wpdb->prefix . 'st_proqyz_progress_meta_submissions';
		$score_table = !empty($table_proqyz_v3_progress_submissions_score) 
			? $table_proqyz_v3_progress_submissions_score 
			: null; // v3 only table
		$user_response_table = !empty($table_proqyz_v3_progress_submissions_user_response) 
			? $table_proqyz_v3_progress_submissions_user_response 
			: null; // v3 only table
		$session_table = !empty($table_proqyz_v3_progress_submissions_session) 
			? $table_proqyz_v3_progress_submissions_session 
			: null; // v3 only table
		$evaluation_meta_table = !empty($table_proqyz_v3_submissions_evaluation_meta) 
			? $table_proqyz_v3_submissions_evaluation_meta 
			: null; // v3 only table
		$versioning_table = !empty($table_proqyz_v3_submissions_versioning) 
			? $table_proqyz_v3_submissions_versioning 
			: null; // v3 only table

		// Process in batches to avoid memory issues
		$batch_size = 20;
		$offset = 0;
		
		while ( true ) {
			// Get batch of submission IDs
			// Note: LIMIT and OFFSET must be integers, not placeholders
			$result_ids = $wpdb->get_col( $wpdb->prepare(
				"SELECT ID FROM {$submissions_table} 
				WHERE user_id = %d AND status = 1 
				LIMIT %d OFFSET %d",
				$user_id,
				absint( $batch_size ),
				absint( $offset )
			) );

			if ( empty( $result_ids ) ) {
				break; // No more submissions
			}

			// Process each submission in batch
			foreach ( $result_ids as $result_id ) {
				$this->delete_single_submission( 
					$result_id, 
					$submissions_table, 
					$meta_table, 
					$review_table, 
					$review_meta_table, 
					$progress_meta_submissions_table,
					$score_table,
					$user_response_table,
					$session_table,
					$evaluation_meta_table,
					$versioning_table
				);
			}

			$offset += $batch_size;
			
			// Small delay to prevent overwhelming the server
			if ( count( $result_ids ) === $batch_size ) {
				usleep( 100000 ); // 0.1 seconds
			}
		}

		// Delete fullmock tests progress
		if ( $table_proqyz_fullmock_tests_progress ) {
			$wpdb->delete( $table_proqyz_fullmock_tests_progress, array( 'user_id' => $user_id ) );
		}

		// Clean up transient
		delete_transient( 'proqyz_delete_user_' . $user_id );
	}

	/**
	 * Delete a single submission and all its associated data
	 * 
	 * This method contains the core deletion logic for v3 tables with versioning support.
	 * Based on proqyz_dashboard_ajax_delete_result approach.
	 * 
	 * @param int $result_id The submission/result ID to delete
	 * @param string $submissions_table Table name for submissions
	 * @param string $meta_table Table name for submission meta
	 * @param string $review_table Table name for reviews
	 * @param string $review_meta_table Table name for review meta
	 * @param string $progress_meta_submissions_table Table name for progress meta submissions
	 * @param string|null $score_table Table name for score (v3 only, null if not available)
	 * @param string|null $user_response_table Table name for user response (v3 only, null if not available)
	 * @param string|null $session_table Table name for session (v3 only, null if not available)
	 * @param string|null $evaluation_meta_table Table name for evaluation meta (v3 only, null if not available)
	 * @param string|null $versioning_table Table name for versioning (v3 only, null if not available)
	 */
	private function delete_single_submission( 
		$result_id, 
		$submissions_table, 
		$meta_table, 
		$review_table, 
		$review_meta_table, 
		$progress_meta_submissions_table,
		$score_table = null,
		$user_response_table = null,
		$session_table = null,
		$evaluation_meta_table = null,
		$versioning_table = null
	) {
		global $wpdb;

		$result_id = absint( $result_id );

		// Get submission to check if it exists and get category
		$submission = $wpdb->get_row( $wpdb->prepare(
			"SELECT * FROM {$submissions_table} WHERE ID = %d AND status = 1",
			$result_id
		), ARRAY_A );

		if ( ! $submission ) {
			return; // Submission doesn't exist or already deleted
		}

		// STEP 3-5: Delete associated files for speaking tests
		if ( $submission['quiz_category'] === 'ielts-speaking' && $progress_meta_submissions_table ) {
			// Use quiz_progress_meta table for speaking audio files (permanent table)
			// STEP 3: Use result_id to search progress_meta
			$meta_records = $wpdb->get_results( $wpdb->prepare(
				"SELECT `json` FROM {$progress_meta_submissions_table} 
				WHERE session_id = %d",
				$result_id
			) );
			
			if ( ! empty( $meta_records ) ) {
				// STEP 4: Find and safe remove file from uploads directory
				foreach ( $meta_records as $meta ) {
					$json_data = @unserialize( $meta->json );
					if ( is_array( $json_data ) || is_object( $json_data ) ) {
						$json_data = (object) $json_data;
						
						// Check if type is 'cpanel' (audio file uploaded)
						if ( isset( $json_data->type ) && $json_data->type === 'cpanel' ) {
							if ( isset( $json_data->location ) && isset( $json_data->filename ) ) {
								$file_path = ABSPATH . $json_data->location . '/' . $json_data->filename;
								
								// Silently delete file (no error if doesn't exist)
								if ( file_exists( $file_path ) ) {
									@unlink( $file_path ); // Silent fail - don't block deletion
								}
							}
						}
					}
				}
				// STEP 5: Remove progress_meta records after files are removed
				$wpdb->delete( $progress_meta_submissions_table, array( 'session_id' => $result_id ) );
			}
		}

		// Delete reviews (for writing/speaking evaluated tests)
		if ( $review_table ) {
			$review_ids = $wpdb->get_col( $wpdb->prepare(
				"SELECT ID FROM {$review_table} WHERE result_id = %d",
				$result_id
			) );
			
			if ( ! empty( $review_ids ) ) {
				foreach ( $review_ids as $review_id ) {
					if ( $review_meta_table ) {
						$wpdb->delete( $review_meta_table, array( 'review_id' => $review_id ) );
					}
				}
				$wpdb->delete( $review_table, array( 'result_id' => $result_id ) );
			}
		}

		// V3: Handle quiz versioning - decrement usage_count if quiz_version_id exists
		if ( $versioning_table && $meta_table ) {
			// Get quiz_version_id from the submissions meta table
			$quiz_version_id = $wpdb->get_var( $wpdb->prepare(
				"SELECT meta_value FROM {$meta_table} 
				WHERE submission_id = %d AND meta_key = 'quiz_version_id' LIMIT 1",
				$result_id
			) );
			
			if ( $quiz_version_id ) {
				// Get current usage_count
				$current_count = $wpdb->get_var($wpdb->prepare(
					"SELECT usage_count FROM {$versioning_table} WHERE version_id = %d",
					$quiz_version_id
				));
				
				// Calculate new value in PHP
				$new_count = max((int)$current_count - 1, 0);
				
				// Update both values using $wpdb->update()
				$wpdb->update(
					$versioning_table,
					array(
						'usage_count' => $new_count,
						'updated_at' => time()
					),
					array('version_id' => $quiz_version_id),
					array('%d', '%d'),
					array('%d')
				);
			}
		}

		// V3: Delete user_response table entry (if v3 table exists)
		if ( $user_response_table ) {
			$wpdb->delete( $user_response_table, array( 'submission_id' => $result_id ) );
		}

		// V3: Delete session table entry (if v3 table exists)
		if ( $session_table ) {
			$wpdb->delete( $session_table, array( 'submission_id' => $result_id ) );
		}

		// V3: Delete score table entry (if v3 table exists)
		if ( $score_table ) {
			$wpdb->delete( $score_table, array( 'submission_id' => $result_id ) );
		}

		// V3: Delete evaluation meta table entry (if v3 table exists)
		if ( $evaluation_meta_table ) {
			$wpdb->delete( $evaluation_meta_table, array( 'session_id' => $result_id ) );
		}
		
		// STEP 6: Delete submission_meta entries
		if ( $meta_table ) {
			$wpdb->delete( $meta_table, array( 'submission_id' => $result_id ) );
		}
		
		// STEP 7: Delete submission (only if previous steps succeeded or failed gracefully)
		$wpdb->delete( $submissions_table, array( 'ID' => $result_id ) );
	}



}

return ST_ProQyz_Admin::get_instance();