<?php
// uninstall.php

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

// Get credentials before cleanup
$site_id = get_option('wordchat_site_id');
$api_key = get_option('wordchat_api_key');

// If credentials exist, call backend to reset data
if ($site_id && $api_key) {
    $api_url = defined('WORDCHAT_API_URL') ? WORDCHAT_API_URL : 'https://chat.word.chat';

    $response = wp_remote_post($api_url . '/reset', [
        'headers' => ['Content-Type' => 'application/json'],
        'body' => json_encode([
            'site_id' => $site_id,
            'api_key' => $api_key,
            'url' => '', // Not used for reset, but required by UnsyncRequest model
            'domain' => get_site_url() // Add domain for validation
        ]),
        'timeout' => 30,
        'blocking' => true
    ]);

    if (is_wp_error($response)) {
        error_log('WordChat uninstall: Backend reset failed - ' . $response->get_error_message());
    } else {
        $status_code = wp_remote_retrieve_response_code($response);
        if ($status_code === 200) {
            error_log('WordChat uninstall: Backend data reset successfully');
        } else {
            error_log('WordChat uninstall: Backend reset returned HTTP ' . $status_code);
        }
    }
}

// Clean up plugin options
delete_option('wordchat_site_id');
delete_option('wordchat_api_key');
delete_option('wordchat_is_paid');
delete_option('wordchat_registration_status');
delete_option('wordchat_registration_error');
delete_option('wordchat_registration_retry_count');
delete_option('wordchat_header_text');
delete_option('wordchat_site_name');
delete_option('wordchat_intro_message');
delete_option('wordchat_navigate_to_response');
delete_option('wordchat_primary_color');
delete_option('wordchat_start_open');
delete_option('wordchat_position');
delete_option('wordchat_placeholder');
delete_option('wordchat_button_text');

// Clean up Pro-specific options
delete_option('wordchat_license_key');
delete_option('wordchat_license_status');
delete_option('wordchat_license_data');
delete_option('wordchat_current_version');
delete_option('wordchat_version_last_reported');

// Clean up all post meta
global $wpdb;
$wpdb->query($wpdb->prepare("DELETE FROM {$wpdb->postmeta} WHERE meta_key LIKE %s", 'wordchat_%'));
