<?php
/**
 * Formipay Uninstall
 *
 * Removes all plugin data when the plugin is uninstalled via WordPress admin.
 */

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

global $wpdb;

// Drop custom tables
$tables = [
    'formipay_orders',
    'formipay_customers',
    'formipay_bank_transfer_trx',
    'formipay_paypal_trx',
    'formipay_notification_log',
    'formipay_tokens',
];

foreach ( $tables as $table_suffix ) {
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.SchemaChange, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
    $wpdb->query( "DROP TABLE IF EXISTS {$wpdb->prefix}{$table_suffix}" );
}

// Remove plugin options
delete_option( 'formipay_settings' );

// Clear scheduled cron events
$crons = _get_cron_array();
if ( ! empty( $crons ) ) {
    foreach ( $crons as $timestamp => $cron ) {
        if ( is_array( $cron ) ) {
            foreach ( $cron as $hook => $events ) {
                if ( strpos( $hook, 'formipay/' ) === 0 ) {
                    foreach ( $events as $key => $event ) {
                        wp_unschedule_event( $timestamp, $hook, $event['args'] ?? [] );
                    }
                }
            }
        }
    }
}

// Remove custom post types and their meta
$post_types = [ 'formipay-form', 'formipay-product', 'formipay-coupon', 'formipay-access', 'formipay-license' ];
foreach ( $post_types as $post_type ) {
    $posts = get_posts( [
        'post_type'   => $post_type,
        'numberposts' => -1,
        'post_status' => 'any',
    ] );
    foreach ( $posts as $post ) {
        wp_delete_post( $post->ID, true );
    }
}

// Clear any cached data
wp_cache_flush();
