<?php

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

/**
 * Refresh all internal links
 * 
 * @param WP_REST_Request $request The request object
 * @return WP_REST_Response The response object
 */
function content_craft_ai_refresh_internal_links($request)
{
  // Check if the class exists
  if (!class_exists('ContentCraftAI_InternalLinksManager')) {
    return new WP_REST_Response([
      'success' => false,
      'message' => 'Internal links manager not available',
    ], 500);
  }

  // Get the manager instance
  $internal_links_manager = ContentCraftAI_InternalLinksManager::get_instance();

  // Refresh the links
  $result = $internal_links_manager->refresh_internal_links();

  if (isset($result['error'])) {
    return new WP_REST_Response([
      'success' => false,
      'message' => 'Error refreshing internal links: ' . $result['error'],
    ], 500);
  }

  return new WP_REST_Response([
    'success' => true,
    'message' => sprintf(
      'Internal links refreshed. Added: %d, Updated: %d, Removed: %d',
      $result['inserted_count'] ?? 0,
      $result['updated_count'] ?? 0,
      $result['deleted_count'] ?? 0
    ),
    'data' => [
      'lastUpdated' => get_option('content_craft_ai_internal_links_updated', ''),
      'stats' => content_craft_ai_get_internal_links_count(),
    ],
  ], 200);
}

/**
 * Get internal links statistics
 * 
 * @param WP_REST_Request $request The request object
 * @return WP_REST_Response The response object
 */
function content_craft_ai_get_internal_links_stats($request)
{
  return new WP_REST_Response([
    'success' => true,
    'data' => [
      'lastUpdated' => get_option('content_craft_ai_internal_links_updated', ''),
      'stats' => content_craft_ai_get_internal_links_count(),
    ],
  ], 200);
}

/**
 * Get the count of internal links in the database
 * 
 * @return array Array with count information
 */
function content_craft_ai_get_internal_links_count()
{
  global $wpdb;
  $table_name = $wpdb->prefix . 'content_craft_ai_internal_links';

  // Check if table exists
  $table_exists = $wpdb->get_var("SHOW TABLES LIKE '{$table_name}'") === $table_name;

  if (!$table_exists) {
    return [
      'total' => 0,
      'withFocusKeyword' => 0,
    ];
  }

  // Get counts
  $total_count = (int) $wpdb->get_var("SELECT COUNT(*) FROM {$table_name}");
  $with_focus_keyword = (int) $wpdb->get_var("SELECT COUNT(*) FROM {$table_name} WHERE focus_keyword IS NOT NULL AND focus_keyword != ''");

  return [
    'total' => $total_count,
    'withFocusKeyword' => $with_focus_keyword,
  ];
}

/**
 * Add AJAX action for backwards compatibility
 */
function content_craft_ai_register_internal_links_ajax()
{
  add_action('wp_ajax_content_craft_ai_refresh_internal_links', function () {
    if (!current_user_can('manage_options')) {
      wp_send_json_error('Permission denied');
    }

    // Check if the class exists
    if (!class_exists('ContentCraftAI_InternalLinksManager')) {
      wp_send_json_error('Internal links manager not available');
    }

    // Get the manager instance
    $internal_links_manager = ContentCraftAI_InternalLinksManager::get_instance();

    // Refresh the links
    $result = $internal_links_manager->refresh_internal_links();

    if (isset($result['error'])) {
      wp_send_json_error('Error refreshing internal links: ' . $result['error']);
    }

    wp_send_json_success([
      'message' => sprintf(
        'Internal links refreshed. Added: %d, Updated: %d, Removed: %d',
        $result['inserted_count'] ?? 0,
        $result['updated_count'] ?? 0,
        $result['deleted_count'] ?? 0
      ),
      'lastUpdated' => get_option('content_craft_ai_internal_links_updated', ''),
      'stats' => [
        'total' => $result['total_count'] ?? 0,
      ],
    ]);
  });
}
add_action('init', 'content_craft_ai_register_internal_links_ajax');
