<?php
/**
 * Uninstall script for Wayl Checkout Payment Plugin
 *
 * This file is executed when the plugin is uninstalled.
 * It removes all plugin data from the database and filesystem.
 *
 * @package Wayl_Checkout
 * @since 1.2.0
 */

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

// Check user capabilities
if ( ! current_user_can( 'activate_plugins' ) ) {
	return;
}

// Delete plugin options
$waylchp_options_to_delete = array(
	'waylchp_webhook_secret',
	'waylchp_api_key',
	'waylchp_logging_enabled',
	'waylchp_activation_email_sent',
);

foreach ( $waylchp_options_to_delete as $waylchp_option ) {
	delete_option( $waylchp_option );
}

// Delete WooCommerce payment gateway settings
$waylchp_gateway_settings = get_option( 'woocommerce_wayl_settings', array() );
if ( ! empty( $waylchp_gateway_settings ) ) {
	delete_option( 'woocommerce_wayl_settings' );
}

// Delete transients
delete_transient( 'waylchp_payment_channels' );

// Remove log files and directory using WP_Filesystem
$upload_dir = wp_upload_dir();
$waylchp_log_directory = $upload_dir['basedir'] . '/wayl-checkout/';
if ( is_dir( $waylchp_log_directory ) ) {
	// Initialize WP_Filesystem
	global $wp_filesystem;
	if ( empty( $wp_filesystem ) ) {
		require_once ABSPATH . '/wp-admin/includes/file.php';
		WP_Filesystem();
	}

	if ( $wp_filesystem && $wp_filesystem->is_dir( $waylchp_log_directory ) ) {
		// Remove all log files
		$waylchp_log_files = glob( $waylchp_log_directory . '*.log' );
		if ( is_array( $waylchp_log_files ) ) {
			foreach ( $waylchp_log_files as $waylchp_log_file ) {
				if ( $wp_filesystem->is_file( $waylchp_log_file ) ) {
					$wp_filesystem->delete( $waylchp_log_file );
				} elseif ( function_exists( 'wp_delete_file' ) ) {
					wp_delete_file( $waylchp_log_file );
				}
			}
		}

		// Remove .htaccess and index.php
		$waylchp_htaccess_file = $waylchp_log_directory . '.htaccess';
		$waylchp_index_file    = $waylchp_log_directory . 'index.php';

		if ( $wp_filesystem->is_file( $waylchp_htaccess_file ) ) {
			$wp_filesystem->delete( $waylchp_htaccess_file );
		} elseif ( function_exists( 'wp_delete_file' ) && file_exists( $waylchp_htaccess_file ) ) {
			wp_delete_file( $waylchp_htaccess_file );
		}

		if ( $wp_filesystem->is_file( $waylchp_index_file ) ) {
			$wp_filesystem->delete( $waylchp_index_file );
		} elseif ( function_exists( 'wp_delete_file' ) && file_exists( $waylchp_index_file ) ) {
			wp_delete_file( $waylchp_index_file );
		}

		// Remove the directory itself if empty
		if ( $wp_filesystem->is_dir( $waylchp_log_directory ) ) {
			$wp_filesystem->rmdir( $waylchp_log_directory, true );
		}
	}
}

// Clear any cached data
wp_cache_flush();
