<?php
// app/controllers/article-generator/postCreation/internal-link-handler.php

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

/**
 * Add/update an article's entry in the internal links database
 * 
 * @param int $post_id The post ID
 * @param string $focus_keyword Focus keyword for the post
 * @param array $tags Tags associated with the post
 * @return bool True on success, false on failure
 */
function content_craft_ai_update_internal_link($post_id, $focus_keyword = '', $tags = [])
{
  // Skip if the post ID is not valid
  if (!$post_id) {
    return false;
  }

  // Get the internal links manager
  if (class_exists('ContentCraftAI_InternalLinksManager')) {
    $internal_links_manager = ContentCraftAI_InternalLinksManager::get_instance();
    return $internal_links_manager->store_post_links($post_id, $focus_keyword, $tags);
  }

  return false;
}

/**
 * Remove an article's entry from the internal links database
 * 
 * @param int $post_id The post ID
 * @return bool True on success, false on failure
 */
function content_craft_ai_remove_internal_link($post_id)
{
  // Skip if the post ID is not valid
  if (!$post_id) {
    return false;
  }

  // Get the internal links manager
  if (class_exists('ContentCraftAI_InternalLinksManager')) {
    $internal_links_manager = ContentCraftAI_InternalLinksManager::get_instance();
    return $internal_links_manager->remove_post_links($post_id);
  }

  return false;
}

/**
 * Get internal links data for API
 * 
 * @param string $focus_keyword The focus keyword to find relevant links for
 * @param int|null $category_id Optional category ID to filter by
 * @return array Array of internal links with url, title and summary
 */
function content_craft_ai_get_internal_links_for_api($focus_keyword, $category_id = null)
{
  if (empty($focus_keyword)) {
    return [];
  }

  // Get the internal links manager
  if (class_exists('ContentCraftAI_InternalLinksManager')) {
    $internal_links_manager = ContentCraftAI_InternalLinksManager::get_instance();
    return $internal_links_manager->get_internal_links_for_api($focus_keyword, $category_id);
  }

  return [];
}
