<?php
declare(strict_types=1);
// ==================================================
// Nuclear Fancy Pants Edition™ — NUCLEAR+++
// File: /home/ploi/automarketer-ai.com/public/wp-content/plugins/automarketer-ai/includes/class-instagram-disconnect.php
// Description: AJAX handler for Instagram account disconnect - NUCLEAR+++
// Last Edited: 2026-04-13
// ==================================================
namespace AutoMarketerAI;
defined('ABSPATH') || exit;
final class InstagramDisconnect
{
    public static function init(): void
    {
        add_action('wp_ajax_amai_ig_disconnect', [self::class, 'handleDisconnect']);
    }
    public static function handleDisconnect(): void
    {
        if (!current_user_can('manage_automarketer_ai')) {
            wp_send_json_error(['message' => 'Unauthorized.'], 403);
            return;
        }
        $nonce = sanitize_text_field((string) ($_POST['_wpnonce'] ?? ''));
        if (!wp_verify_nonce($nonce, 'amai_ig_disconnect')) {
            wp_send_json_error(['message' => 'Invalid security token. Please reload the page and try again.'], 403);
            return;
        }
        $account_id = FacebookAuth::getInstagramAccountId();
        if ($account_id === null) {
            wp_send_json_error(['message' => 'No active Instagram connection found.'], 404);
            return;
        }
        global $wpdb;
        $table  = $wpdb->prefix . 'amai_facebook_connection';
        $result = $wpdb->update(
            $table,
            ['instagram_account_id' => null],
            ['tenant_id' => 'default']
        );
        if ($result === false) {
            wp_send_json_error(['message' => 'Failed to disconnect. Please try again.'], 500);
            return;
        }
        wp_send_json_success([
            'message'  => 'Instagram account disconnected.',
            'redirect' => admin_url('admin.php?page=automarketer-ai-social&channel=instagram&disconnected=1'),
        ]);
    }
}