<?php
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPress.Security.NonceVerification.Missing, WordPress.Security.NonceVerification.Recommended, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare, WordPress.DB.SlowDBQuery.slow_db_query_meta_key, WordPress.DB.DirectDatabaseQuery.SchemaChange
/**
 * Uninstall — UAE VAT Invoice for WooCommerce
 *
 * Runs when the plugin is deleted from WordPress admin.
 * Only removes data if the user has opted in via the settings checkbox.
 *
 * @package UAE_VAT_Invoice
 */

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

global $wpdb;

// Only wipe data if user opted in
if ( get_option( 'pbuaiv_delete_data_on_uninstall' ) ) {

    // Drop custom tables
    $wpdb->query( "DROP TABLE IF EXISTS {$wpdb->prefix}pbuaiv_documents" );
    $wpdb->query( "DROP TABLE IF EXISTS {$wpdb->prefix}pbuaiv_sequences" );

    // Remove all plugin options
    $options = [
        'pbuaiv_company_name', 'pbuaiv_company_address', 'pbuaiv_company_city',
        'pbuaiv_company_emirate', 'pbuaiv_company_phone', 'pbuaiv_company_email',
        'pbuaiv_company_website', 'pbuaiv_logo_id',
        'pbuaiv_trn', 'pbuaiv_vat_rate', 'pbuaiv_currency_aed_rate', 'pbuaiv_doc_language',
        'pbuaiv_bank_name', 'pbuaiv_bank_account', 'pbuaiv_bank_iban', 'pbuaiv_bank_swift',
        'pbuaiv_brand_primary', 'pbuaiv_brand_secondary',
        'pbuaiv_default_template', 'pbuaiv_paper_size',
        'pbuaiv_invoice_prefix', 'pbuaiv_invoice_suffix', 'pbuaiv_invoice_padding', 'pbuaiv_invoice_reset',
        'pbuaiv_receipt_prefix', 'pbuaiv_receipt_suffix', 'pbuaiv_receipt_padding', 'pbuaiv_receipt_reset',
        'pbuaiv_credit_note_prefix', 'pbuaiv_credit_note_suffix', 'pbuaiv_credit_note_padding', 'pbuaiv_credit_note_reset',
        'pbuaiv_proforma_prefix', 'pbuaiv_proforma_suffix', 'pbuaiv_proforma_padding', 'pbuaiv_proforma_reset',
        'pbuaiv_packing_slip_prefix', 'pbuaiv_packing_slip_suffix', 'pbuaiv_packing_slip_padding', 'pbuaiv_packing_slip_reset',
        'pbuaiv_delivery_note_prefix', 'pbuaiv_delivery_note_suffix', 'pbuaiv_delivery_note_padding', 'pbuaiv_delivery_note_reset',
        'pbuaiv_auto_invoice_status', 'pbuaiv_auto_receipt_status', 'pbuaiv_auto_credit_note_status',
        'pbuaiv_send_invoice_email', 'pbuaiv_send_receipt_email',
    'pbuaiv_attach_invoice_emails', 'pbuaiv_attach_receipt_emails', 'pbuaiv_attach_credit_note_emails', 'pbuaiv_attach_proforma_emails',
        'pbuaiv_customer_download', 'pbuaiv_guest_download',
        'pbuaiv_invoice_notes', 'pbuaiv_payment_terms',
        'pbuaiv_onboarding_done', 'pbuaiv_db_version',
        'pbuaiv_delete_data_on_uninstall',
    ];

    foreach ( $options as $opt ) {
        delete_option( $opt );
    }

    // Remove order meta added by the plugin
    $meta_keys = [
        '_pbuaiv_invoice_number', '_pbuaiv_invoice_date', '_pbuaiv_invoice_id',
        '_pbuaiv_receipt_number', '_pbuaiv_receipt_date', '_pbuaiv_receipt_id',
        '_pbuaiv_credit_note_number', '_pbuaiv_credit_note_date', '_pbuaiv_credit_note_id',
        '_pbuaiv_proforma_number', '_pbuaiv_proforma_date', '_pbuaiv_proforma_id',
        '_pbuaiv_packing_slip_number', '_pbuaiv_packing_slip_date',
        '_pbuaiv_delivery_note_number', '_pbuaiv_delivery_note_date',
        '_billing_trn', '_reverse_charge',
    ];

    foreach ( $meta_keys as $key ) {
        $wpdb->delete( $wpdb->postmeta, [ 'meta_key' => $key ] );
        // HPOS order meta
        if ( $wpdb->get_var( "SHOW TABLES LIKE '{$wpdb->prefix}wc_orders_meta'" ) ) {
            $wpdb->delete( $wpdb->prefix . 'wc_orders_meta', [ 'meta_key' => $key ] );
        }
    }

    // Remove generated PDF directory
    $upload_dir = wp_upload_dir();
    $pdf_dir    = $upload_dir['basedir'] . '/pbuaiv-documents';
    if ( is_dir( $pdf_dir ) ) {
        $files = glob( $pdf_dir . '/*' );
        if ( $files ) {
            foreach ( $files as $file ) {
                wp_delete_file( $file );
            }
        }
        if ( ! function_exists( 'WP_Filesystem' ) ) {
            require_once ABSPATH . 'wp-admin/includes/file.php';
        }
        WP_Filesystem();
        global $wp_filesystem;
        if ( $wp_filesystem ) {
            $wp_filesystem->rmdir( $pdf_dir );
        }
    }

    // Remove temp dir
    $upload_dir = wp_upload_dir();
    $tmp_dir    = trailingslashit( $upload_dir['basedir'] ) . 'pb-invoicing-system/pbuaiv-tmp';
    if ( is_dir( $tmp_dir ) ) {
        $files = glob( $tmp_dir . '/*' );
        if ( $files ) {
            foreach ( $files as $file ) {
                wp_delete_file( $file );
            }
        }
        if ( ! isset( $wp_filesystem ) || ! $wp_filesystem ) {
            if ( ! function_exists( 'WP_Filesystem' ) ) {
                require_once ABSPATH . 'wp-admin/includes/file.php';
            }
            WP_Filesystem();
            global $wp_filesystem;
        }
        if ( $wp_filesystem ) {
            $wp_filesystem->rmdir( $tmp_dir );
        }
    }
}
