<?php
/**
 * DZQCOD Uninstall Handler
 *
 * Fired when the plugin is deleted (NOT deactivated) from WordPress admin.
 *
 * @package DZQCOD
 * @since 4.1.0
 */

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

if (!current_user_can('manage_options')) {
    return;
}

global $wpdb;

// ═══ 1. Read references BEFORE deleting options ═══
$account_page_id = get_option('dzqcod_account_page_id', 0);
$generated_pages = get_posts([
    'post_type'   => 'page',
    'meta_key'    => '_dzqcod_page',
    'numberposts' => 100,
    'fields'      => 'ids',
]);

// ═══ 2. Delete generated pages ═══
if ($account_page_id) {
    wp_delete_post((int) $account_page_id, true);
}
foreach ($generated_pages as $pid) {
    wp_delete_post((int) $pid, true);
}

// ═══ 3. Clear scheduled cron events ═══
foreach (['dzqcod_license_check', 'dzqcod_daily_cleanup', 'dzqcod_telemetry', 'dzqcod_check_delays'] as $cron) {
    wp_clear_scheduled_hook($cron);
}

// ═══ 4. Remove all plugin options ═══
$options = $wpdb->get_col("SELECT option_name FROM {$wpdb->options} WHERE option_name LIKE 'dzqcod_%'");
foreach ($options as $opt) {
    delete_option($opt);
}

// ═══ 5. Remove transients ═══
$wpdb->query("DELETE FROM {$wpdb->options} WHERE option_name LIKE '_transient_dzqcod_%' OR option_name LIKE '_transient_timeout_dzqcod_%' OR option_name LIKE '_transient_nibra_update_%' OR option_name LIKE '_transient_timeout_nibra_update_%'");

// ═══ 6. Remove custom database tables ═══
$prefix = $wpdb->prefix . 'dz_';
$tables = ['wilayas','communes','call_logs','fraud_scores','blacklist','touchpoints','campaign_stats','offers','ab_tests','shipping_labels','message_logs','license','audit_log','addons','abandoned_carts','loyalty','referrals','reviews','heatmap','rbac','stores','workflows','notifications','acc_invoices','acc_inv_items','acc_expenses','acc_journal','acc_tax_returns','acc_customers'];
foreach ($tables as $t) {
    $wpdb->query("DROP TABLE IF EXISTS {$prefix}{$t}");
}

// ═══ 7. Remove user meta ═══
$wpdb->query("DELETE FROM {$wpdb->usermeta} WHERE meta_key LIKE 'dzqcod_%'");

// ═══ 8. Remove order meta ═══
$wpdb->query("DELETE FROM {$wpdb->postmeta} WHERE meta_key LIKE '_dzqcod_%'");

// ═══ 9. Clear update transients ═══
delete_site_transient('update_plugins');
