<?php

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

/**
 * Handle upgrade plan request
 * 
 * @return WP_REST_Response Response with payment link or error
 */
function content_craft_ai_upgrade_plan($request)
{
  // Prevent caching on subscription changes
  header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
  header('Cache-Control: post-check=0, pre-check=0', false);
  header('Pragma: no-cache');
  header('Expires: 0');

  // Get plan type from request
  $plan_type = $request->get_param('planType');

  if (empty($plan_type)) {
    return new WP_REST_Response(
      array(
        'success' => false,
        'message' => 'Plan type is required',
      ),
      400
    );
  }

  // Check if we've already processed a subscription recently (anti-duplication)
  $last_subscription_time = get_transient('content_craft_ai_last_subscription_request');
  $current_time = time();

  if ($last_subscription_time && ($current_time - $last_subscription_time) < 30) {
    return new WP_REST_Response(
      array(
        'success' => false,
        'message' => 'Please wait a moment before trying again.',
      ),
      429
    );
  }

  // Get API key
  $api_key = get_option('content_craft_ai_api_key');
  if (empty($api_key)) {
    return new WP_REST_Response(
      array(
        'success' => false,
        'message' => 'Authentication required',
      ),
      401
    );
  }

  // Check if billing information exists
  $billing_response = wp_remote_get(
    CONTENT_CRAFT_AI_EXTERNAL_API . '/user/billing',
    array(
      'headers' => array(
        'x-api-key' => $api_key,
        'x-wp-domain' => wp_parse_url(get_site_url(), PHP_URL_HOST),
        'Content-Type' => 'application/json',
      ),
      'timeout' => 120,
    )
  );

  // Check for error in billing info request
  if (is_wp_error($billing_response)) {
    return new WP_REST_Response(
      array(
        'success' => false,
        'message' => 'Failed to verify billing information: ' . $billing_response->get_error_message(),
      ),
      500
    );
  }

  $billing_body = json_decode(wp_remote_retrieve_body($billing_response), true);
  $billing_status = wp_remote_retrieve_response_code($billing_response);

  // If billing check was successful, verify billing info exists
  if ($billing_status === 200 && isset($billing_body['success']) && $billing_body['success'] === true) {
    if (!isset($billing_body['data']['billing']) || !isset($billing_body['data']['billing']['updatedAt']) || $billing_body['data']['billing']['updatedAt'] === null) {
      // No billing info exists, return a response indicating billing info is required
      return new WP_REST_Response(
        array(
          'success' => false,
          'requiresBilling' => true,
          'message' => 'Billing information required before proceeding',
        ),
        200
      );
    }
  }

  // Prepare request data
  $request_data = array(
    'planType' => $plan_type
  );

  // Add custom success and cancel URLs to request
  $admin_url = admin_url('admin.php');
  $success_url = add_query_arg(
    array(
      'page' => 'content-craft-ai-dashboard',
      'subscription_success' => 'true',
      'include_subscription_id' => 'true'
    ),
    $admin_url
  );

  $cancel_url = add_query_arg(
    array(
      'page' => 'content-craft-ai-dashboard',
      'subscription_cancelled' => 'true'
    ),
    $admin_url
  );

  // Add URLs to request data
  $request_data['successUrl'] = $success_url;
  $request_data['cancelUrl'] = $cancel_url;

  // Make request to external API
  $response = wp_remote_post(
    CONTENT_CRAFT_AI_EXTERNAL_API . '/payments/create-subscription',
    array(
      'method' => 'POST',
      'headers' => array(
        'Content-Type' => 'application/json',
        'x-api-key' => $api_key,
        'x-wp-domain' => wp_parse_url(get_site_url(), PHP_URL_HOST)
      ),
      'body' => json_encode($request_data),
      'timeout' => 120
    )
  );

  // Check for error
  if (is_wp_error($response)) {
    return new WP_REST_Response(
      array(
        'success' => false,
        'message' => 'API Connection Error: ' . $response->get_error_message(),
      ),
      500
    );
  }

  $body = json_decode(wp_remote_retrieve_body($response), true);
  $status = wp_remote_retrieve_response_code($response);

  // If API call was successful and contains payment link
  if ($status === 200 && isset($body['success']) && $body['success'] === true) {
    if (isset($body['data']['payment_link']) && filter_var($body['data']['payment_link'], FILTER_VALIDATE_URL)) {
      // Set a transient to prevent creating multiple subscriptions in a short time period
      set_transient('content_craft_ai_last_subscription_request', time(), 5 * MINUTE_IN_SECONDS);

      // Store the plan type for later verification
      update_option('content_craft_ai_pending_plan_type', $body['data']['plan_type'] ?? $plan_type);

      // Store the subscription ID if available in the response
      if (isset($body['data']['subscription_id'])) {
        update_option('content_craft_ai_active_subscription', $body['data']['subscription_id']);
      }

      // Return checkout URL for client-side redirect
      return new WP_REST_Response(
        array(
          'success' => true,
          'requiresPayment' => true,
          'checkoutUrl' => esc_url_raw($body['data']['payment_link']),
          'planType' => $body['data']['plan_type'] ?? $plan_type,
          'message' => 'Redirecting to payment page...'
        ),
        200
      );
    }
  }

  // Return the original response if no payment link was found or another error occurred
  return new WP_REST_Response($body, $status);
}

/**
 * Handle cancel subscription request
 * 
 * @return WP_REST_Response Response with status
 */
function content_craft_ai_cancel_subscription()
{
  // Prevent caching on subscription changes
  header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
  header('Cache-Control: post-check=0, pre-check=0', false);
  header('Pragma: no-cache');
  header('Expires: 0');

  // Get API key
  $api_key = get_option('content_craft_ai_api_key');
  if (empty($api_key)) {
    return new WP_REST_Response(
      array(
        'success' => false,
        'message' => 'Authentication required',
      ),
      401
    );
  }

  // Get the active subscription ID
  $subscription_id = get_option('content_craft_ai_active_subscription', '');

  if (empty($subscription_id)) {
    // Try to get current subscriptions and find an active one
    $subscriptions = content_craft_ai_get_active_subscriptions($api_key);

    if (is_wp_error($subscriptions)) {
      return new WP_REST_Response(
        array(
          'success' => false,
          'message' => $subscriptions->get_error_message(),
        ),
        500
      );
    }

    if (empty($subscriptions)) {
      return new WP_REST_Response(
        array(
          'success' => false,
          'message' => 'No active subscription found.',
        ),
        400
      );
    }

    $subscription_id = $subscriptions[0]['subscriptionId'];
    update_option('content_craft_ai_active_subscription', $subscription_id);
  }

  // Prepare request data
  $request_data = array(
    'subscriptionId' => $subscription_id
  );

  // Make request to external API
  $response = wp_remote_post(
    CONTENT_CRAFT_AI_EXTERNAL_API . '/payments/cancel-subscription',
    array(
      'method' => 'POST',
      'headers' => array(
        'Content-Type' => 'application/json',
        'x-api-key' => $api_key,
        'x-wp-domain' => wp_parse_url(get_site_url(), PHP_URL_HOST)
      ),
      'body' => json_encode($request_data),
      'timeout' => 120
    )
  );

  // Check for error
  if (is_wp_error($response)) {
    return new WP_REST_Response(
      array(
        'success' => false,
        'message' => 'API Connection Error: ' . $response->get_error_message(),
      ),
      500
    );
  }

  $body = json_decode(wp_remote_retrieve_body($response), true);
  $status = wp_remote_retrieve_response_code($response);

  // If API call was successful
  if ($status === 200 && isset($body['success']) && $body['success'] === true) {
    // Clear subscription data from WordPress options
    delete_option('content_craft_ai_active_subscription');

    // Return success response
    return new WP_REST_Response(
      array(
        'success' => true,
        'message' => 'Subscription cancelled successfully.'
      ),
      200
    );
  }

  // Return the original response
  return new WP_REST_Response($body, $status);
}

/**
 * Handle change plan request
 * 
 * @return WP_REST_Response Response with status
 */
function content_craft_ai_change_plan($request)
{
  // Prevent caching on subscription changes
  header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
  header('Cache-Control: post-check=0, pre-check=0', false);
  header('Pragma: no-cache');
  header('Expires: 0');

  // Get plan type from request
  $plan_type = $request->get_param('planType');

  if (empty($plan_type)) {
    return new WP_REST_Response(
      array(
        'success' => false,
        'message' => 'Plan type is required',
      ),
      400
    );
  }

  // Get API key
  $api_key = get_option('content_craft_ai_api_key');
  if (empty($api_key)) {
    return new WP_REST_Response(
      array(
        'success' => false,
        'message' => 'Authentication required',
      ),
      401
    );
  }

  // Get the active subscription ID
  $subscription_id = get_option('content_craft_ai_active_subscription', '');

  if (empty($subscription_id)) {
    // Try to get current subscriptions and find an active one
    $subscriptions = content_craft_ai_get_active_subscriptions($api_key);

    if (is_wp_error($subscriptions)) {
      return new WP_REST_Response(
        array(
          'success' => false,
          'message' => $subscriptions->get_error_message(),
        ),
        500
      );
    }

    if (empty($subscriptions)) {
      return new WP_REST_Response(
        array(
          'success' => false,
          'message' => 'No active subscription found. Please subscribe first before changing plans.',
        ),
        400
      );
    }

    $subscription_id = $subscriptions[0]['subscriptionId'];
    update_option('content_craft_ai_active_subscription', $subscription_id);
  }

  // Prepare request data
  $request_data = array(
    'subscriptionId' => $subscription_id,
    'planType' => $plan_type
  );

  // Make request to external API
  $response = wp_remote_post(
    CONTENT_CRAFT_AI_EXTERNAL_API . '/payments/change-plan',
    array(
      'method' => 'POST',
      'headers' => array(
        'Content-Type' => 'application/json',
        'x-api-key' => $api_key,
        'x-wp-domain' => wp_parse_url(get_site_url(), PHP_URL_HOST)
      ),
      'body' => json_encode($request_data),
      'timeout' => 120
    )
  );

  // Check for error
  if (is_wp_error($response)) {
    return new WP_REST_Response(
      array(
        'success' => false,
        'message' => 'API Connection Error: ' . $response->get_error_message(),
      ),
      500
    );
  }

  $body = json_decode(wp_remote_retrieve_body($response), true);
  $status = wp_remote_retrieve_response_code($response);

  // Return the original response
  return new WP_REST_Response($body, $status);
}

/**
 * Helper function to get active subscriptions
 * 
 * @param string $api_key API key
 * @return array|WP_Error Array of active subscriptions or error
 */
function content_craft_ai_get_active_subscriptions($api_key)
{
  // Make request to external API
  $response = wp_remote_get(
    CONTENT_CRAFT_AI_EXTERNAL_API . '/payments/subscriptions',
    array(
      'headers' => array(
        'Content-Type' => 'application/json',
        'x-api-key' => $api_key,
        'x-wp-domain' => wp_parse_url(get_site_url(), PHP_URL_HOST)
      ),
      'timeout' => 120
    )
  );

  // Check for error
  if (is_wp_error($response)) {
    return new WP_Error('api_error', 'Failed to get subscription details: ' . $response->get_error_message());
  }

  $body = json_decode(wp_remote_retrieve_body($response), true);
  $status = wp_remote_retrieve_response_code($response);

  // If successful, filter for active subscriptions
  if ($status === 200 && isset($body['success']) && $body['success'] === true && isset($body['data']) && is_array($body['data'])) {
    $active_subscriptions = array_filter($body['data'], function ($subscription) {
      return isset($subscription['status']) && $subscription['status'] === 'active';
    });

    return array_values($active_subscriptions); // Reset array keys
  }

  return array();
}

/**
 * Handle subscription success redirect and notifications
 */
function content_craft_ai_handle_subscription_success()
{
  // Add JavaScript to force refresh data after subscription changes
  if (isset($_GET['subscription_success']) || isset($_GET['subscription_cancelled'])) {
    add_action('admin_footer', 'content_craft_ai_add_refresh_script');
  }

  // Verify nonce for subscription operations
  $nonce_verified = false;
  if (isset($_GET['_wpnonce'])) {
    $nonce_verified = wp_verify_nonce(sanitize_text_field(wp_unslash($_GET['_wpnonce'])), 'content_craft_ai_subscription_action');
  }

  // Check for subscription success parameter with nonce verification
  if ($nonce_verified && isset($_GET['subscription_success']) && $_GET['subscription_success'] === 'true') {
    // Check if status is explicitly set to failed in the URL
    if (isset($_GET['status']) && $_GET['status'] === 'failed') {
      // Clear the pending plan type option
      delete_option('content_craft_ai_pending_plan_type');

      // The React app will display the error notification
      return;
    }

    // Check if we have a subscription ID directly in the URL
    if (isset($_GET['subscription_id'])) {
      $subscription_id = sanitize_text_field($_GET['subscription_id']);
      update_option('content_craft_ai_active_subscription', $subscription_id);
      error_log('Content Craft AI: Updated subscription ID from URL parameter: ' . $subscription_id);
    }

    // Get API key
    $api_key = get_option('content_craft_ai_api_key');
    if (!empty($api_key)) {
      // Fetch latest subscription data from API to get the new subscription ID
      $subscriptions = content_craft_ai_get_active_subscriptions($api_key);

      if (!is_wp_error($subscriptions) && !empty($subscriptions)) {
        // Update the active subscription ID with the latest one
        $subscription_id = $subscriptions[0]['subscriptionId'];
        update_option('content_craft_ai_active_subscription', $subscription_id);
        error_log('Content Craft AI: Updated subscription ID from API: ' . $subscription_id);
      } else {
        error_log('Content Craft AI: Failed to retrieve subscription data after payment');

        // If API call fails but we didn't already get ID from URL, try user profile
        if (!isset($_GET['subscription_id'])) {
          // Try to get subscription ID from user profile as fallback
          $user_data = content_craft_ai_check_auth();
          if ($user_data && !empty($user_data['subscriptionId'])) {
            update_option('content_craft_ai_active_subscription', $user_data['subscriptionId']);
            error_log('Content Craft AI: Updated subscription ID from user profile: ' . $user_data['subscriptionId']);
          }
        }
      }
    }

    // Clear the pending plan type option
    delete_option('content_craft_ai_pending_plan_type');

    // The React app will display the success notification
  }

  // Check for subscription cancelled parameter with nonce verification
  if ($nonce_verified && isset($_GET['subscription_cancelled']) && $_GET['subscription_cancelled'] === 'true') {
    // Clear the pending plan type
    delete_option('content_craft_ai_pending_plan_type');

    // The React app will display the cancellation notification
  }
}

/**
 * Add JavaScript to force refresh subscription data
 */
function content_craft_ai_add_refresh_script()
{
?>
  <script type="text/javascript">
    document.addEventListener('DOMContentLoaded', function() {
      // If we're on the dashboard page and this is a return from subscription flow
      if (window.location.href.includes('content-craft-ai-dashboard') &&
        (window.location.href.includes('subscription_success') ||
          window.location.href.includes('subscription_cancelled'))) {

        console.log('Content Craft AI: Detected subscription change');

        // Clean up URL
        var cleanUrl = window.location.href.split('?')[0];

        // Wait a moment to allow the user to see the success message
        setTimeout(function() {
          // Simple page reload to get fresh data
          window.location.href = cleanUrl;
        }, 2000);
      }
    });
  </script>
<?php
}

// Register the subscription success handler to run on admin_init
add_action('admin_init', 'content_craft_ai_handle_subscription_success');
