<?php
if ( ! defined( 'ABSPATH' ) ) exit;

function rank_get_api_key() {
    return get_option( 'rank_api_key', '' );
}

// Define health check categories recognized by the plugin
function rank_get_health_check_categories() {
    return array(
        'missing_meta_description' => 'Missing Meta Description',
        'short_meta_description'   => 'Short Meta Description',
        'long_meta_description'    => 'Long Meta Description',
        'missing_title_tag'        => 'Missing Title Tag',
        'short_title_tag'          => 'Short Title Tag',
        'long_title_tag'           => 'Long Title Tag',
        'missing_alt_tags'         => 'Missing Alt Tag',
        'broken_links_external'    => 'Broken External Link',
        'broken_links_internal'    => 'Broken Internal Link',
        // Add more categories as needed, matching API expectations
    );
}

// Map issue types to their processing requirements and display information
function rank_get_issue_type_config($issue_type = null) {
    $configs = array(
        'missing_meta_description' => array(
            'label' => 'Missing Meta Descriptions',
            'display_text' => 'Missing meta description',
            'content_type' => 'text',
            'solution_label' => 'Meta Description',
            'identifier_is_url' => false,
            'handler_type' => 'database_override',
        ),
        'short_meta_description' => array(
            'label' => 'Short Meta Descriptions',
            'display_text' => 'Meta description too short',
            'content_type' => 'text',
            'solution_label' => 'Suggested Meta Description',
            'identifier_is_url' => false,
            'handler_type' => 'database_override',
        ),
        'long_meta_description' => array(
            'label' => 'Long Meta Descriptions',
            'display_text' => 'Meta description too long',
            'content_type' => 'text',
            'solution_label' => 'Suggested Meta Description',
            'identifier_is_url' => false,
            'handler_type' => 'database_override',
        ),
        'missing_title_tag' => array(
            'label' => 'Missing Title Tags',
            'display_text' => 'Missing title tag',
            'content_type' => 'text',
            'solution_label' => 'Title',
            'identifier_is_url' => false,
            'handler_type' => 'database_override',
        ),
        'short_title_tag' => array(
            'label' => 'Short Title Tags',
            'display_text' => 'Title tag too short',
            'content_type' => 'text',
            'solution_label' => 'Suggested Title',
            'identifier_is_url' => false,
            'handler_type' => 'database_override',
        ),
        'long_title_tag' => array(
            'label' => 'Long Title Tags',
            'display_text' => 'Title tag too long',
            'content_type' => 'text',
            'solution_label' => 'Suggested Title',
            'identifier_is_url' => false,
            'handler_type' => 'database_override',
        ),
        'missing_alt_tags' => array(
            'label' => 'Missing Alt Tags',
            'display_text' => 'Missing alt text',
            'content_type' => 'text',
            'solution_label' => 'Alt Text',
            'identifier_is_url' => true,
            'handler_type' => 'database_override',
        ),
        'broken_links_external' => array(
            'label' => 'Broken External Links',
            'display_text' => 'Broken external link',
            'content_type' => 'url',
            'solution_label' => 'Suggested Fixed URL',
            'identifier_is_url' => true,
            'handler_type' => 'option_suggestion',
        ),
        'broken_links_internal' => array(
            'label' => 'Broken Internal Links',
            'display_text' => 'Broken internal link',
            'content_type' => 'url',
            'solution_label' => 'Suggested Fixed URL',
            'identifier_is_url' => true,
            'handler_type' => 'option_suggestion',
        ),
    );
    
    if ($issue_type !== null) {
        return isset($configs[$issue_type]) ? $configs[$issue_type] : null;
    }
    
    return $configs;
}

/**
 * Normalize URL for consistent comparison across the system.
 * Handles URL encoding and trailing slashes.
 * Used by both frontend filters and admin/processor code.
 *
 * @param string $url The URL to normalize
 * @return string The normalized URL
 */
if ( ! function_exists('rank_normalize_url') ) {
    function rank_normalize_url($url) {
        if (empty($url)) {
            return '';
        }
        
        // Get the current WordPress site domain
        $wp_host = parse_url(home_url(), PHP_URL_HOST);
        $url_host = parse_url($url, PHP_URL_HOST);
        
        // Skip normalization for external URLs (different domain)
        if ($url_host && $wp_host && $url_host !== $wp_host) {
            return $url;
        }
        
        // Only normalize internal URLs (same domain)
        $normalized = urldecode($url);
        
        // Remove trailing slash for consistency (except for root URLs)
        $normalized = rtrim($normalized, '/');
        
        // If it's just the protocol and domain, keep it as is
        if (preg_match('#^https?://[^/]+$#', $normalized)) {
            return $normalized;
        }
        
        return $normalized;
    }
}

/**
 * Lightweight debug logging that works in all contexts.
 * - Admin/AJAX/Cron: delegates to Rank_Processor::add_debug_log() if loaded.
 * - Frontend (logged-in admin): logs directly to the same debug log file.
 * - Frontend (regular visitor): does nothing (debug is off or user not admin).
 *
 * @param string $message The debug message.
 * @param string $level   Log level (default 'info').
 */
function rank_debug_log($message, $level = 'info') {
    // If the processor class is loaded (admin/ajax/cron), delegate to it
    if ( class_exists('Rank_Processor', false) ) {
        Rank_Processor::add_debug_log($message, $level);
        return;
    }
    
    // Frontend: only log for logged-in admins with debug enabled
    if ( ! is_user_logged_in() || ! current_user_can('manage_options') ) {
        return;
    }
    
    if ( ! get_option('rank_debug_enabled', false) ) {
        return;
    }
    
    // Write directly to the same log file the processor uses
    $logs_dir = RANK_PLUGIN_DIR . 'logs/';
    $log_file = $logs_dir . 'rank-debug.log';
    
    if ( ! file_exists($logs_dir) ) {
        wp_mkdir_p($logs_dir);
    }
    
    $timestamp = current_time('Y-m-d H:i:s');
    $formatted = "[{$timestamp}] [{$level}] {$message}" . PHP_EOL;
    file_put_contents($log_file, $formatted, FILE_APPEND | LOCK_EX);
}