<?php
/**
 * Fired when the plugin is uninstalled.
 * 
 * This file strictly complies with WordPress.org guidelines to remove 
 * all custom database tables and options when a user deletes the plugin.
 */

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

global $wpdb;

// 1. Drop all custom database tables
$pexemail_tables = [
    $wpdb->prefix . 'pexemail_lists',
    $wpdb->prefix . 'pexemail_contacts',
    $wpdb->prefix . 'pexemail_campaigns',
    $wpdb->prefix . 'pexemail_recipients'
];

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

// 2. Delete all plugin options from the wp_options table
$pexemail_options = [
    'pexemail_settings',
    'pexemail_license_key',
    'pexemail_input_email',
    'pexemail_license_status',
    'pexemail_license_details',
    'pexemail_license_error',
    'pex_campaign_daily_limit'
];

foreach ( $pexemail_options as $pexemail_option ) {
    delete_option( $pexemail_option );
}

// 3. Clear scheduled cron jobs
$pexemail_license_timestamp = wp_next_scheduled( 'pexemail_15min_license_check' );
if ( $pexemail_license_timestamp ) {
    wp_unschedule_event( $pexemail_license_timestamp, 'pexemail_15min_license_check' );
}

$pexemail_worker_timestamp = wp_next_scheduled( 'pexemail_cron_worker' );
if ( $pexemail_worker_timestamp ) {
    wp_unschedule_event( $pexemail_worker_timestamp, 'pexemail_cron_worker' );
}