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

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

/**
 * Applies SEO metadata to a post based on plugin settings.
 *
 * @param int $post_id The ID of the post to update.
 * @param string $article_full_content The full content of the article for meta description.
 * @param string $focus_keyword The focus keyword for the article.
 * @return void
 */
function content_craft_ai_apply_seo_metadata($post_id, $article_full_content, $focus_keyword)
{
  $user_settings = get_option('content_craft_ai_user_settings', []); // Corrected option name
  $seo_plugin = $user_settings['seoPlugin'] ?? 'none'; // Corrected: Access directly from user_settings

  if ($seo_plugin === 'none') {
    // error_log("Content Craft AI: SEO Meta Handler - SEO plugin set to 'none'. Skipping meta for post ID {$post_id}.");
    return;
  }

  $meta_desc = wp_trim_words(wp_strip_all_tags($article_full_content), 55, '...'); // Common recommendation is ~155-160 chars, 55 words is a guideline

  if ($seo_plugin === 'yoast') {
    update_post_meta($post_id, '_yoast_wpseo_metadesc', $meta_desc);
    update_post_meta($post_id, '_yoast_wpseo_focuskw', $focus_keyword);
    // error_log("Content Craft AI: SEO Meta Handler - Applied Yoast SEO metadata for post ID {$post_id}. Focus: {$focus_keyword}");
  } elseif ($seo_plugin === 'rankmath') {
    update_post_meta($post_id, 'rank_math_description', $meta_desc);
    update_post_meta($post_id, 'rank_math_focus_keyword', $focus_keyword);
    // error_log("Content Craft AI: SEO Meta Handler - Applied Rank Math SEO metadata for post ID {$post_id}. Focus: {$focus_keyword}");
  } else {
    // error_log("Content Craft AI: SEO Meta Handler - Unknown SEO plugin '{$seo_plugin}' configured. Skipping meta for post ID {$post_id}.");
  }
}
