<?php
/**
 * BrewmyApp Uninstall
 *
 * Removes all plugin data when the plugin is uninstalled via WordPress.
 * This file is executed when the user deletes the plugin from WP admin.
 *
 * @package BrewmyApp
 */

// Exit if not called by WordPress.
if (!defined('WP_UNINSTALL_PLUGIN')) {
    exit;
}

// ── Remove plugin options (v2.0 names) ──────
$options_to_delete = array(
    // v2.0 option names.
    'brewmyapp_jwt_secret',
    'brewmyapp_jwt_expiry',
    'brewmyapp_wa_token',
    'brewmyapp_wa_otp_template',
    'brewmyapp_wa_template_lang',
    'brewmyapp_wa_send_url',
    'brewmyapp_order_notification_settings',
    'brewmyapp_app_url',
    'brewmyapp_push_notification_logs',
    'brewmyapp_api_logs',
    'brewmyapp_plugin_activated_before',
    'brewmyapp_show_credit',
    // Legacy v1.x option names (in case migration didn't run).
    'app_jwt_secret',
    'app_jwt_expiry',
    'WA_TOKEN',
    'app_whatsapp_otp_template',
    'app_whatsapp_template_lang',
    'wa_message_send_url',
);

foreach ($options_to_delete as $option) {
    delete_option($option);
}

// ── Remove user meta (push tokens & back-in-stock subs) ──────────
$users = get_users(array('meta_key' => 'brewmyapp_expo_push_tokens')); // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key
foreach ($users as $user) {
    delete_user_meta($user->ID, 'brewmyapp_expo_push_tokens');
    delete_user_meta($user->ID, 'brewmyapp_back_in_stock_subs');
}

// ── Remove transients (OTP data) ────────────
global $wpdb;

// Remove v2.0 transients (brewmyapp_otp_*).
$wpdb->query( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.NoCaching
    $wpdb->prepare(
        "DELETE FROM {$wpdb->options} WHERE option_name LIKE %s OR option_name LIKE %s",
        '_transient_brewmyapp_otp_%',
        '_transient_timeout_brewmyapp_otp_%'
    )
);

// Remove legacy v1.x transients (app_otp_*).
$wpdb->query( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.NoCaching
    $wpdb->prepare(
        "DELETE FROM {$wpdb->options} WHERE option_name LIKE %s OR option_name LIKE %s",
        '_transient_app_otp_%',
        '_transient_timeout_app_otp_%'
    )
);



// ── Flush rewrite rules ─────────────────────
flush_rewrite_rules();
