<?php
/**
 * Fired when the plugin is uninstalled.
 *
 * @package    VMO_Web_Business_Consultant
 * @subpackage VMO_Web_Business_Consultant/includes
 * @author     Virtual Media Office
 */

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

// Check if the user has chosen to preserve data
// The default is false (delete data) if the option doesn't exist, 
// unless we want to be safe and default to true. 
// User request: "give then the options to either delete or reserve the database".
// Implies default might be destruction but with a warning.
// We will look for 'vmo_preserve_data' option.
$preserve_data = get_option( 'vmo_preserve_data', true );

if ( ! $preserve_data ) {
	global $wpdb;

	// List of tables to drop (without prefix)
	$tables = array(
		'vmo_consultations',
		'vmo_consultation_media',
		'vmo_emails',
		'vmo_website_drafts',
		'vmo_website_versions',
		'vmo_business_roadmaps',
		'vmo_roadmap_milestones',
		'vmo_daily_activities',
		'vmo_business_kpis',
		'vmo_kpi_history',
		'vmo_deep_research_results',
		'vmo_manager_activations',
		'vmo_projects',
		'vmo_user_phone_numbers',
		'vmo_bookings',
		'vmo_usage_tracking',
		'vmo_users',
		'vmo_transactions',
		'vmo_affiliates',
		'vmo_commissions',
		'vmo_support_tickets',
		'vmo_api_usage',
		'vmo_conversations',
		'vmo_messages',
		'vmo_call_recordings',
		'vmo_campaigns',
		'vmo_email_sends',
		'vmo_email_signatures'
	);

	foreach ( $tables as $table ) {
		$table_name = $wpdb->prefix . $table;
		$wpdb->query( "DROP TABLE IF EXISTS {$table_name}" );
	}

	// Delete all options starting with 'vmo_'
	// phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
	$wpdb->query( "DELETE FROM {$wpdb->options} WHERE option_name LIKE 'vmo_%'" );
	
	// Delete user meta
    // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
    $wpdb->query( "DELETE FROM {$wpdb->usermeta} WHERE meta_key LIKE 'vmo_%'" );
    
    // Clear scheduled cron events
    $timestamp = wp_next_scheduled( 'vmo_daily_cron_event' );
    wp_unschedule_event( $timestamp, 'vmo_daily_cron_event' );
}
