<?php
/**
 * Uninstall script for REEID Translation (Universal)
 *
 * Safe by default:
 * - Always removes plugin settings
 * - Deletes content ONLY if user explicitly opted in
 */

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

/* ---------------------------------------------------------------------------
 * SECTION 1: Read deletion preference BEFORE deleting options
 * ------------------------------------------------------------------------- */
$reeid_delete_data = (bool) get_option( 'reeid_delete_data_on_uninstall', false );

/* ---------------------------------------------------------------------------
 * SECTION 2: Always delete plugin options
 * ------------------------------------------------------------------------- */
$reeid_options = array(
    'reeid_openai_api_key',
    'reeid_openai_model',
    'reeid_translation_tones',
    'reeid_translation_source_lang',
    'reeid_delete_data_on_uninstall',
    'reeid_openai_status',
);

foreach ( $reeid_options as $reeid_option ) {
    delete_option( $reeid_option );
}

/* ---------------------------------------------------------------------------
 * SECTION 3: Stop here unless user explicitly allowed data removal
 * ------------------------------------------------------------------------- */
if ( ! $reeid_delete_data ) {
    return;
}

/* ---------------------------------------------------------------------------
 * SECTION 4: Delete REEID translation metadata ONLY
 * ------------------------------------------------------------------------- */
delete_post_meta_by_key( '_reeid_translation_lang' );
delete_post_meta_by_key( '_reeid_translation_source' );
delete_post_meta_by_key( '_reeid_translation_map' );
delete_post_meta_by_key( '_reeid_wc_inline_langs' );

/* ---------------------------------------------------------------------------
 * SECTION 5: Pattern-based cleanup (REEID only)
 * ------------------------------------------------------------------------- */
global $wpdb;

$reeid_like = $wpdb->esc_like( '_reeid_' ) . '%';

// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
$wpdb->query(
    $wpdb->prepare(
        "DELETE FROM {$wpdb->postmeta}
         WHERE meta_key LIKE %s",
        $reeid_like
    )
);

/*
 * IMPORTANT:
 * - Builder-specific core meta is NOT touched
 * - Posts are NOT deleted
 * - Users must delete translations manually if desired
 */