<?php
// app/hooks/internal-links.php

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

/**
 * Setup WordPress hooks for handling post status changes
 */
function content_craft_ai_setup_internal_link_hooks()
{
  // When a post is published or status changes, update internal links
  add_action('transition_post_status', function ($new_status, $old_status, $post) {
    // Only handle post type 'post'
    if ($post->post_type !== 'post') {
      return;
    }

    // Handle internal links based on post status change
    if (
      function_exists('content_craft_ai_update_internal_link') &&
      function_exists('content_craft_ai_remove_internal_link')
    ) {

      // When a post is published, add it to internal links
      if ($new_status === 'publish') {
        $focus_keyword = '';
        $tags = [];

        // Get focus keyword from SEO plugin if available
        $user_settings = get_option('content_craft_ai_user_settings', []);
        $seo_plugin = $user_settings['seoPlugin'] ?? '';

        if ($seo_plugin === 'yoast') {
          $focus_keyword = get_post_meta($post->ID, '_yoast_wpseo_focuskw', true);
        } elseif ($seo_plugin === 'rankmath') {
          $focus_keyword = get_post_meta($post->ID, 'rank_math_focus_keyword', true);
        }

        // Get post categories for tags
        $categories = get_the_category($post->ID);
        if (!empty($categories)) {
          foreach ($categories as $category) {
            $tags[] = $category->slug;
          }
        }

        content_craft_ai_update_internal_link($post->ID, $focus_keyword, $tags);
      }

      // When a post is trashed or moved to draft, remove it from internal links
      if (($old_status === 'publish') && ($new_status !== 'publish')) {
        content_craft_ai_remove_internal_link($post->ID);
      }
    }
  }, 10, 3);

  // Handle the post published action from Content Craft AI
  add_action('content_craft_ai_post_published', 'content_craft_ai_update_internal_link', 10, 3);
}

// Initialize hooks
add_action('init', 'content_craft_ai_setup_internal_link_hooks');
