<?php
/**
 * Uninstall KDS & Report for Orderable
 * 
 * Fired when the plugin is uninstalled.
 */

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

// Check if user has permission to delete plugins
if (!current_user_can('delete_plugins')) {
    exit;
}

// Clean up plugin data
kdsamref_cleanup_plugin_data();

/**
 * Clean up all plugin data
 */
function kdsamref_cleanup_plugin_data() {
    global $wpdb;

    // Remove plugin options
    $plugin_options = array(
        'kdsamref_auto_refresh_interval',
        'kdsamref_default_delivery_type',
        'kdsamref_enable_sound_notifications',
    
        'kdsamref_max_orders_display',
        'kdsamref_setup_complete',
        'kdsamref_version',
        'kdsamref_db_version'
    );

    foreach ($plugin_options as $option) {
        delete_option($option);
        delete_site_option($option); // For multisite
    }

    // Remove custom post meta
    $custom_meta_keys = array(
        '_kdsamref_delivery_type',
        '_kdsamref_table_number',
        '_kdsamref_pickup_time',
        '_kdsamref_special_instructions'
    );

    foreach ($custom_meta_keys as $meta_key) {
        // Use WordPress functions where possible, direct query for uninstall cleanup
        delete_metadata('post', 0, $meta_key, '', true);
    }

    // Remove custom order statuses (optional - comment out if you want to keep them)
    /*
    wp_delete_post_status('wc-ready-pickup');
    wp_delete_post_status('wc-preparing');
    */

    // Clear any cached data
    wp_cache_flush();

    // Remove any scheduled events
    wp_clear_scheduled_hook('kdsamref_cleanup_old_orders');
    wp_clear_scheduled_hook('kdsamref_daily_stats_update');
    // (No license schedules in core)

    // Remove user meta related to plugin
    $user_meta_keys = array(
        'kdsamref_dashboard_preferences',
        'kdsamref_last_login',
        'kdsamref_notification_settings'
    );

    foreach ($user_meta_keys as $meta_key) {
        // Use WordPress functions where possible, direct query for uninstall cleanup
        delete_metadata('user', 0, $meta_key, '', true);
    }

    // (No license options in core)

    // Remove transients
    $transients = array(
        'kdsamref_order_stats',
        'kdsamref_dashboard_data',
        'kdsamref_system_status'
    );

    foreach ($transients as $transient) {
        delete_transient($transient);
        delete_site_transient($transient);
    }

    // Log cleanup for debugging (if WP_DEBUG is enabled)
    if (defined('WP_DEBUG') && WP_DEBUG) {
        error_log('KDS & Report for Orderable: Plugin data cleaned up during uninstall');
    }

    // Optional: Create backup of settings before deletion
    // This allows users to restore settings if they reinstall
    $backup_data = array(
        'timestamp' => current_time('timestamp'),
        'options' => array(),
        'meta_count' => 0
    );

    foreach ($plugin_options as $option) {
        $value = get_option($option);
        if ($value !== false) {
            $backup_data['options'][$option] = $value;
        }
    }

    // Count how many order meta entries were removed
    foreach ($custom_meta_keys as $meta_key) {
        // Use WordPress functions where possible for counting
        $count = $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM {$wpdb->postmeta} WHERE meta_key = %s",
            $meta_key
        ));
        $backup_data['meta_count'] += intval($count);
    }

    // Save backup (expires in 30 days)
    set_transient('kdsamref_uninstall_backup', $backup_data, 30 * DAY_IN_SECONDS);
}

/**
 * Remove custom database tables (if any were created)
 * Currently this plugin doesn't create custom tables, but this is here for future use
 */
function kdsamref_remove_custom_tables() {
    global $wpdb;

    // Example custom table removal (uncomment if you add custom tables)
    /*
    $table_name = $wpdb->prefix . 'kdsamref_order_logs';
    $wpdb->query("DROP TABLE IF EXISTS {$table_name}");
    
    $table_name = $wpdb->prefix . 'kdsamref_statistics';
    $wpdb->query("DROP TABLE IF EXISTS {$table_name}");
    */
}

/**
 * Remove capabilities from custom roles (if any were created)
 */
function kdsamref_remove_custom_capabilities() {
    // Remove custom capabilities from Administrator role
    $admin_role = get_role('administrator');
    if ($admin_role) {
        $admin_role->remove_cap('manage_kdsamref_orders');
        $admin_role->remove_cap('view_kdsamref_dashboard');
    }

    // Remove custom capabilities from Shop Manager role
    $manager_role = get_role('shop_manager');
    if ($manager_role) {
        $manager_role->remove_cap('manage_kdsamref_orders');
        $manager_role->remove_cap('view_kdsamref_dashboard');
    }

    // Remove custom role if it was created
    // remove_role('restaurant_manager');
}

/**
 * Clean up uploaded files (if any)
 */
function kdsamref_cleanup_uploaded_files() {
    $upload_dir = wp_upload_dir();
    $plugin_upload_dir = $upload_dir['basedir'] . '/kds-report-for-orderable/';

    if (is_dir($plugin_upload_dir)) {
        // Remove all files in plugin upload directory using WordPress filesystem
        $files = glob($plugin_upload_dir . '*');
        foreach ($files as $file) {
            if (is_file($file)) {
                wp_delete_file($file);
            }
        }
        
        // Remove the directory using WordPress filesystem
        if (is_dir($plugin_upload_dir)) {
            // Use WP_Filesystem for directory removal
            global $wp_filesystem;
            if (!$wp_filesystem) {
                require_once(ABSPATH . 'wp-admin/includes/file.php');
                WP_Filesystem();
            }
            $wp_filesystem->rmdir($plugin_upload_dir, true);
        }
    }
}

// Execute cleanup functions
kdsamref_remove_custom_tables();
kdsamref_remove_custom_capabilities();
kdsamref_cleanup_uploaded_files();

// Final cleanup verification
if (defined('WP_DEBUG') && WP_DEBUG) {
    error_log('KDS & Report for Orderable: Uninstall process completed successfully');
}
