<?php
/**
 * Uninstall script for Rentals & Bookings for WooCommerce & Dokan
 *
 * This file runs when the plugin is deleted through the WordPress admin.
 * It cleans up all plugin data including database tables and options.
 *
 * @package WahraRentalsBookings
 */

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

// Check if user has permission
if (!current_user_can('activate_plugins')) {
    return;
}

// Check if this is the correct plugin being uninstalled
if (WP_UNINSTALL_PLUGIN !== 'wahra-rentals-bookings/wahra-rentals-bookings.php') {
    return;
}

global $wpdb;

// Check if we should preserve data (can be set by admin in settings)
$preserve_data = get_option('wahrb_preserve_data_on_uninstall', false);

if (!$preserve_data) {
    // Drop custom tables
    $tables = [
        $wpdb->prefix . 'wahrb_bookings',
        $wpdb->prefix . 'wahrb_availability_index',
        $wpdb->prefix . 'wahrb_daily_availability',
        $wpdb->prefix . 'wahrb_price_rules',
        $wpdb->prefix . 'wahrb_wizard_drafts',
        $wpdb->prefix . 'wahrb_holds',
        $wpdb->prefix . 'wahrb_blackout_dates',
        $wpdb->prefix . 'wahrb_logs',
        $wpdb->prefix . 'wahrb_payment_schedule',
        $wpdb->prefix . 'wahrb_booking_notes',
        $wpdb->prefix . 'wahrb_email_logs',
        $wpdb->prefix . 'wahrb_sms_logs',
        $wpdb->prefix . 'wahrb_form_templates',
        $wpdb->prefix . 'wahrb_coupons',
        $wpdb->prefix . 'wahrb_coupon_usage',
    ];

    foreach ($tables as $table) {
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.DirectDatabaseQuery.SchemaChange, PluginCheck.Security.DirectDB.UnescapedDBParameter
        $wpdb->query(
            $wpdb->prepare(
                'DROP TABLE IF EXISTS %i',
                $table
            )
        );
    }

    // Delete plugin options
    $options = [
        'wahrb_db_version',
        'wahrb_activated_at',
        'wahrb_deposit_product_id',
        'wahrb_balance_product_id',
        'wahrb_security_product_id',
        'wahrb_settings_general',
        'wahrb_settings_booking',
        'wahrb_settings_payment',
        'wahrb_settings_cancellation',
        'wahrb_settings_emails',
        'wahrb_settings_categories',
        'wahrb_settings_custom_categories',
        'wahrb_settings_platform_categories',
        'wahrb_settings_pricing_rules',
        'wahrb_settings_service_types',
        'wahrb_settings_notifications',
        'wahrb_settings_vendor_permissions',
        'wahrb_settings_form_builder',
        'wahrb_settings_coupons',
        'wahrb_flush_rewrite_rules',
        'wahrb_preserve_data_on_uninstall',
        'wahrb_setup_wizard_completed',
        'wahrb_setup_wizard_dismissed',
    ];

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

    // Delete virtual products
    $product_ids = [
        get_option('wahrb_deposit_product_id'),
        get_option('wahrb_balance_product_id'),
        get_option('wahrb_security_product_id'),
    ];

    foreach ($product_ids as $product_id) {
        if ($product_id) {
            wp_delete_post($product_id, true);
        }
    }

    // Delete all post meta related to plugin
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching, PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
    $wpdb->query(
        $wpdb->prepare("DELETE FROM {$wpdb->postmeta} WHERE meta_key LIKE %s", $wpdb->esc_like('_wahrb_') . '%')
    );

    // Delete all user meta related to plugin
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching, PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
    $wpdb->query(
        $wpdb->prepare("DELETE FROM {$wpdb->usermeta} WHERE meta_key LIKE %s OR meta_key LIKE %s", $wpdb->esc_like('_wahrb_') . '%', $wpdb->esc_like('wahrb_') . '%')
    );

    // Remove capabilities from roles
    $capabilities = [
        'wahrb_manage_bookings',
        'wahrb_view_bookings',
        'wahrb_create_offers',
        'wahrb_edit_offers',
        'wahrb_manage_pricing',
        'wahrb_manage_availability',
        'wahrb_process_payments',
        'wahrb_view_analytics',
        'wahrb_manage_settings',
        'wahrb_manage_all_bookings',
        'wahrb_manage_vendors',
        'wahrb_view_all_analytics',
        'wahrb_export_data',
    ];

    $roles = ['administrator', 'shop_manager', 'seller'];

    foreach ($roles as $role_name) {
        $role = get_role($role_name);
        if ($role) {
            foreach ($capabilities as $cap) {
                $role->remove_cap($cap);
            }
        }
    }

    // Clear scheduled cron events
    $cron_hooks = [
        'wahrb_cleanup_expired_holds',
        'wahrb_process_balance_orders',
        'wahrb_daily_cron_event',
    ];

    foreach ($cron_hooks as $hook) {
        $timestamp = wp_next_scheduled($hook);
        if ($timestamp) {
            wp_unschedule_event($timestamp, $hook);
        }
    }

    // Clear any transients
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching, PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
    $wpdb->query(
        $wpdb->prepare("DELETE FROM {$wpdb->options} WHERE option_name LIKE %s OR option_name LIKE %s", $wpdb->esc_like('_transient_wahrb_') . '%', $wpdb->esc_like('_transient_timeout_wahrb_') . '%')
    );
}

// Flush rewrite rules
flush_rewrite_rules();
