<?php
/**
 * Plugin Uninstall Handler
 *
 * This file is called automatically when the plugin is deleted from the WordPress admin.
 * It drops custom database tables and clears configuration options if the administrator
 * enabled the "Uninstall Clean Up" setting.
 *
 * @package TeknoTokAiTranslatorPro
 */

// If uninstall not called from WordPress, exit.
if ( ! defined( 'WP_UNINSTALL_PLUGIN' ) ) {
	exit;
}

$settings = get_option( 'teknotok_ait_settings', array() );
$delete_data = $settings['delete_data_on_uninstall'] ?? '0';

if ( '1' === $delete_data ) {
	global $wpdb;

	// 1. Drop Custom Tables
	$translations_table = $wpdb->prefix . 'teknotok_translations';
	$jobs_table = $wpdb->prefix . 'teknotok_jobs';

	$wpdb->query( "DROP TABLE IF EXISTS {$translations_table}" ); // phpcs:ignore WordPress.DB.PreparedSQL.Variables
	$wpdb->query( "DROP TABLE IF EXISTS {$jobs_table}" );         // phpcs:ignore WordPress.DB.PreparedSQL.Variables

	// 2. Clear Scheduled Crons
	$cron_hooks = array(
		'teknotok_ait_queue_worker',
		'teknotok_ait_daily_license_check',
	);
	foreach ( $cron_hooks as $hook ) {
		$timestamp = wp_next_scheduled( $hook );
		if ( $timestamp ) {
			wp_unschedule_event( $timestamp, $hook );
		}
	}

	// 3. Delete Option Records
	$options_to_delete = array(
		'teknotok_ait_settings',
		'teknotok_ait_license_status',
		'teknotok_ait_db_version',
		'teknotok_ait_activation_notice',
		'teknotok_ait_queue_paused',
		'teknotok_ait_queue_token',
	);
	foreach ( $options_to_delete as $option ) {
		delete_option( $option );
	}

	// 4. Delete Custom Uploads Log Folder
	$upload_dir = wp_upload_dir();
	if ( empty( $upload_dir['error'] ) ) {
		$custom_dir = $upload_dir['basedir'] . '/teknotok-ait';
		if ( file_exists( $custom_dir ) && is_dir( $custom_dir ) ) {
			$files = glob( $custom_dir . '/*' );
			if ( $files ) {
				foreach ( $files as $file ) {
					if ( is_file( $file ) ) {
						@unlink( $file );
					}
				}
			}
			@rmdir( $custom_dir );
		}
	}
}
