<?php
declare(strict_types=1);
// ==================================================
// Nuclear Fancy Pants Edition™ — NUCLEAR+++
// File: /includes/class-facebook-disconnect.php
// Description: AJAX handler for Facebook page disconnect with confirmation - NUCLEAR+++
// Last Edited: 2026-03-26
// ==================================================

namespace AutoMarketerAI;

// No direct access
defined('ABSPATH') || exit;

final class FacebookDisconnect
{
    public static function init(): void
    {
        add_action('wp_ajax_amai_fb_disconnect', [self::class, 'handleDisconnect']);
    }

    public static function handleDisconnect(): void
    {
        // Capability check
        if (!current_user_can('manage_automarketer_ai')) {
            wp_send_json_error(['message' => 'Unauthorized.'], 403);
            return;
        }

        // Nonce check
        $nonce = sanitize_text_field((string) ($_POST['_wpnonce'] ?? ''));
        if (!wp_verify_nonce($nonce, 'amai_fb_disconnect')) {
            wp_send_json_error(['message' => 'Invalid security token. Please reload the page and try again.'], 403);
            return;
        }

        // Verify a connection actually exists before disconnecting
        $connection = FacebookAuth::getConnection();
        if ($connection === null) {
            wp_send_json_error(['message' => 'No active Facebook connection found.'], 404);
            return;
        }

        // Perform the disconnect
        $result = FacebookAuth::disconnect();

        if (!$result) {
            wp_send_json_error(['message' => 'Failed to disconnect. Please try again.'], 500);
            return;
        }

        // Clear any cached Facebook data from wp_options
        delete_option('amai_fb_user_token_temp');
        delete_option('amai_fb_pages_temp');
        delete_option('amai_fb_oauth_state');

        wp_send_json_success([
            'message'  => 'Facebook page disconnected.',
            'redirect' => admin_url('admin.php?page=automarketer-ai-social&channel=facebook&disconnected=1'),
        ]);
    }
}