<?php
/**
 * Calendar Plugin uninstall handler.
 */

declare(strict_types=1);

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

global $wpdb;
if (!isset($wpdb)) {
    return;
}

$cleanupMode = (string) get_option('calendar_plugin_uninstall_cleanup_mode', 'keep');
if ($cleanupMode !== 'remove') {
    return;
}

$stem = trim((string) get_option('calendar_plugin_table_stem', 'cs_calendar'), '_');
if ($stem === '') {
    $stem = 'cs_calendar';
}
$prefix = (string) $wpdb->prefix;

$tables = [
    $prefix . $stem . '_events',
    $prefix . $stem . '_recurrence_exceptions',
    $prefix . $stem . '_users',
    $prefix . $stem . '_user_tokens',
    $prefix . $stem . '_audit_log',
];

foreach ($tables as $table) {
    $wpdb->query("DROP TABLE IF EXISTS `{$table}`");
}

$options = [
    'calendar_plugin_caldav_calendar_name',
    'calendar_plugin_url_slug',
    'calendar_plugin_ics_access_mode',
    'calendar_plugin_diagnostics_enabled',
    'calendar_plugin_uninstall_cleanup_mode',
    'calendar_plugin_table_stem',
    'calendar_plugin_schema_version',
];
foreach ($options as $optionName) {
    delete_option($optionName);
}
