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

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

/**
 * Get available smart link templates
 * 
 * @return array Array of template data
 */
function content_craft_ai_get_smart_link_templates()
{
  return [
    'default' => [
      'name' => 'Default',
      'description' => 'A simple left-border style for recommended links',
      'preview' => 'Read more: <a href="#">Example Article Title</a>'
    ],
    'bordered' => [
      'name' => 'Bordered',
      'description' => 'A fully bordered box with hover effect',
      'preview' => 'Read more: <a href="#">Example Article Title</a>'
    ],
    'minimal' => [
      'name' => 'Minimal',
      'description' => 'A clean, minimalist style with top and bottom borders',
      'preview' => 'Read more: <a href="#">Example Article Title</a>'
    ],
    'card' => [
      'name' => 'Card',
      'description' => 'A modern card style with shadow and hover effect',
      'preview' => 'Read more: <a href="#">Example Article Title</a>'
    ]
  ];
}

/**
 * Get the current smart link template setting
 * 
 * @return string The template ID
 */
function content_craft_ai_get_smart_link_template()
{
  $user_settings = get_option('content_craft_ai_user_settings', []);
  $template = $user_settings['smartLinkTemplate'] ?? 'default';

  // Validate that the template exists
  $templates = content_craft_ai_get_smart_link_templates();
  if (!isset($templates[$template])) {
    $template = 'default';
  }

  return $template;
}

/**
 * Creates a smart link HTML for insertion in content
 * 
 * @param string $url The URL for the link
 * @param string $title The link text/title
 * @param string $type The link type (internal or external)
 * @param string $language The content language (for read more text)
 * @return string The formatted HTML
 */
function content_craft_ai_create_smart_link($url, $title, $type = 'internal', $language = 'en')
{
  if (empty($url) || empty($title)) {
    return '';
  }

  // Get current template
  $template = content_craft_ai_get_smart_link_template();

  // Normalize language code (convert to lowercase and trim)
  $language = strtolower(trim($language));

  // Get language-specific read more text
  $read_more_text = 'Read more:';
  switch ($language) {
    case 'fr':
      $read_more_text = 'Lire plus:';
      break;
    case 'es':
      $read_more_text = 'Leer más:';
      break;
    case 'de':
      $read_more_text = 'Weiterlesen:';
      break;
    default:
      // Default to English for unknown languages
      $read_more_text = 'Read more:';
  }

  // Set rel attribute based on link type
  $rel_attribute = 'dofollow';

  // Create the HTML
  return sprintf(
    '<div class="content-craft-ai-smart-link content-craft-ai-smart-link-%s" data-cc-template="%s" data-cc-type="%s" data-cc-url="%s">%s <a href="%s" target="_blank" rel="%s">%s</a></div>',
    esc_attr($type),
    esc_attr($template),
    esc_attr($type),
    esc_url($url),
    $read_more_text,
    esc_url($url),
    esc_attr($rel_attribute),
    esc_html($title)
  );
}

/**
 * Extract link information from HTML
 * 
 * @param string $link_html The HTML link tag
 * @return array|false Array with url and title, or false if invalid
 */
function content_craft_ai_extract_link_data($link_html)
{
  if (empty($link_html)) {
    return false;
  }

  // Extract href and link text using regex
  if (preg_match('/<a href="([^"]+)">([^<]+)<\/a>/i', $link_html, $matches)) {
    return [
      'url' => $matches[1],
      'title' => $matches[2]
    ];
  }

  return false;
}

/**
 * Insert smart links into the article content at strategic positions
 * 
 * @param string $content The article content
 * @param array $links Array with 'internalLink' and 'externalLink' HTML
 * @param string $language The article language
 * @return string The content with inserted smart links
 */
function content_craft_ai_insert_smart_links($content, $links, $language = 'en')
{
  // Skip if smart linking is disabled
  $user_settings = get_option('content_craft_ai_user_settings', []);
  $smart_linking_enabled = $user_settings['smartLinkingEnabled'] ?? false;

  if (!$smart_linking_enabled || (empty($links['internalLink']) && empty($links['externalLink']))) {
    return $content;
  }

  // If language is the default 'en', check user settings for default language
  if ($language === 'en') {
    $user_default_language = $user_settings['defaultLanguage'] ?? 'en';
    $language = $user_default_language;
  }

  // Find all headings in the content
  preg_match_all('/<h[2-6][^>]*>.*?<\/h[2-6]>/is', $content, $headings, PREG_OFFSET_CAPTURE);
  $heading_count = count($headings[0]);

  // Prepare smart links HTML
  $internal_link_html = '';
  $external_link_html = '';

  // Process internal link
  if (!empty($links['internalLink'])) {
    $internal_link_data = content_craft_ai_extract_link_data($links['internalLink']);
    if ($internal_link_data) {
      $internal_link_html = content_craft_ai_create_smart_link(
        $internal_link_data['url'],
        $internal_link_data['title'],
        'internal',
        $language
      );
    }
  }

  // Process external link
  if (!empty($links['externalLink'])) {
    $external_link_data = content_craft_ai_extract_link_data($links['externalLink']);
    if ($external_link_data) {
      $external_link_html = content_craft_ai_create_smart_link(
        $external_link_data['url'],
        $external_link_data['title'],
        'external',
        $language
      );
    }
  }

  // Insert links at optimal positions
  if ($heading_count >= 1) {
    // For internal links - place based on heading count
    if (!empty($internal_link_html)) {
      if ($heading_count >= 4) {
        // Place internal link before 2nd heading if we have 4+ headings
        $internal_link_position = $headings[0][1][1];
      } else {
        // Place internal link before 1st heading if we have fewer headings
        $internal_link_position = $headings[0][0][1];
      }

      $content = substr($content, 0, $internal_link_position) .
        "\n\n" . $internal_link_html . "\n\n" .
        substr($content, $internal_link_position);
    }

    // For external links - always place before the last heading
    if (!empty($external_link_html)) {
      // Re-find headings after inserting internal link (if any)
      if (!empty($internal_link_html)) {
        preg_match_all('/<h[2-6][^>]*>.*?<\/h[2-6]>/is', $content, $updated_headings, PREG_OFFSET_CAPTURE);
        $last_heading_index = count($updated_headings[0]) - 1;
        $external_link_position = $updated_headings[0][$last_heading_index][1];
      } else {
        // Use original headings if no internal link was inserted
        $last_heading_index = $heading_count - 1;
        $external_link_position = $headings[0][$last_heading_index][1];
      }

      $content = substr($content, 0, $external_link_position) .
        "\n\n" . $external_link_html . "\n\n" .
        substr($content, $external_link_position);
    }
  } else {
    // If we have no headings, append links at the end
    if (!empty($internal_link_html)) {
      $content .= "\n\n" . $internal_link_html;
    }

    if (!empty($external_link_html)) {
      $content .= "\n\n" . $external_link_html;
    }
  }

  return $content;
}
