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

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

/**
 * This file depends on WordPress core functionality.
 * The following functions are defined by WordPress and will be available at runtime:
 * - esc_attr: Function to escape HTML attributes
 * - esc_html: Function to escape HTML
 * - wp_strip_all_tags: Function to strip all HTML and PHP tags
 * - wp_kses_post: Function to allow only post-related HTML tags
 */

/**
 * Generates HTML for an FAQ section.
 *
 * @param array|null $faq_data The FAQ data containing items and optional metadata.
 * @param string $article_language The primary language of the article.
 * @return string The HTML for the FAQ section, or an empty string if no FAQ is generated.
 */
function content_craft_ai_generate_faq_html($faq_data, $article_language = 'en')
{
  if (empty($faq_data) || empty($faq_data['items'])) {
    return ''; // No FAQ data or no items
  }

  // Determine language for FAQ heading (article language -> faq metadata language -> default 'en')
  $faq_lang = $article_language;
  if (empty($faq_lang) && !empty($faq_data['metadata']['language'])) {
    $faq_lang = $faq_data['metadata']['language'];
  }
  $faq_lang = strtolower($faq_lang ?: 'en'); // Ensure lowercase and default

  // Set the FAQ heading based on language
  $faq_heading_text = 'Frequently Asked Questions'; // Default
  switch ($faq_lang) {
    case 'fr':
      $faq_heading_text = 'Questions Fréquemment Posées';
      break;
    case 'es':
      $faq_heading_text = 'Preguntas Frecuentes';
      break;
    case 'de':
      $faq_heading_text = 'Häufig Gestellte Fragen';
      break;
      // Add more languages as needed
  }

  $faq_html = "\n\n<h2 class=" . esc_attr('content-craft-faq-heading') . ">" . esc_html($faq_heading_text) . "</h2>\n";
  $faq_html .= "<div class=\"" . esc_attr('content-craft-faq-container content-craft-faq-' . $faq_lang) . "\">\n";

  foreach ($faq_data['items'] as $item) {
    if (empty($item['question']) || empty($item['answer'])) {
      continue; // Skip items with missing question or answer
    }
    $faq_html .= "  <div class=\"" . esc_attr('content-craft-faq-item') . "\">\n";
    $faq_html .= "    <h3 class=\"" . esc_attr('content-craft-faq-question') . "\">" . esc_html(wp_strip_all_tags($item['question'])) . "</h3>\n";
    $faq_html .= "    <div class=\"" . esc_attr('content-craft-faq-answer') . "\">\n";
    // Assuming answer can contain HTML, so not stripping tags here, but ensure it's properly formatted from API.
    // If answers are plain text, use esc_html(wp_strip_all_tags($item['answer'])) as well.
    $faq_html .= "      <p>" . wp_kses_post($item['answer']) . "</p>\n";
    $faq_html .= "    </div>\n";
    $faq_html .= "  </div>\n\n";
  }

  $faq_html .= "</div>\n\n";

  // error_log("Content Craft AI: FAQ Handler - Generated FAQ HTML for language: {$faq_lang}");
  return $faq_html;
}
