<?php

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

/**
 * Handle logout request
 * 
 * @param WP_REST_Request $request Request object
 * @return WP_REST_Response Response object
 */
function content_craft_ai_handle_logout($request)
{
  try {
    // Clear all authentication data
    content_craft_ai_clear_auth();

    // Set a transient flag to indicate manual logout
    set_transient('content_craft_ai_manual_logout', true, 30); // Keep for 30 seconds

    return rest_ensure_response(array(
      'success' => true,
      'message' => 'Logged out successfully',
      'redirectUrl' => add_query_arg('manual_logout', '1', content_craft_ai_get_page_url())
    ));
  } catch (Exception $e) {
    return new WP_Error(
      'logout_error',
      'An error occurred during logout.',
      array('status' => 500)
    );
  }
}
