<?php

/**
 * Initialize Internal Linking Feature
 * 
 * Ensures all internal linking components are properly initialized
 * 
 * @package ProRank\SEO
 * @since 1.0.0
 */

declare(strict_types=1);

namespace ProRank\SEO\Modules\Content\InternalLinking;

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


/**
 * Initialize internal linking feature
 */


function init_internal_linking(): void {
    static $initialized = false;
    if ($initialized) {
        return;
    }
    $initialized = true;

    // Ensure database tables exist
    ensure_database_tables();
    
    // Enable auto-linking by default if not set
    ensure_default_settings();
    
    // Initialize click tracking
    if (!has_action('wp_ajax_prorank_track_link_click')) {
        $click_tracker = new Tracking\ClickTracker();
        $click_tracker->init();
    }
}

/**
 * Ensure database tables exist
 */
function ensure_database_tables(): void {
    $result = TableRegistry::ensure_tables(true);
    if (!$result['ready'] && function_exists('prorank_log')) {
        prorank_log(
            sprintf(
                '[InternalLinking] Schema readiness failed in init path. Missing: %1$s',
                implode(',', $result['missing_tables'])
            ),
            'error'
        );
    }
}

/**
 * Ensure default settings are in place
 */
function ensure_default_settings(): void {
    $defaults = [
        'auto_linking_enabled' => true,
        'auto_linking_max_per_post' => 5,
        'auto_linking_scan_enabled' => true,
        'auto_linking_scan_frequency' => 'weekly',
        'enable_click_tracking' => false,
        'enable_orphan_detection' => true,
        'enable_broken_link_detection' => true,
    ];
    
    foreach ($defaults as $key => $value) {
        if (get_option("prorank_seo_$key") === false) {
            update_option("prorank_seo_$key", $value);
        }
    }
}

// Initialize on admin_init and init
add_action('admin_init', __NAMESPACE__ . '\init_internal_linking');
add_action('init', __NAMESPACE__ . '\init_internal_linking');
