<?php

declare(strict_types=1);


if ( ! defined( 'ABSPATH' ) ) {
    exit;
}
/**
 * PageSpeed Insights API Configuration
 * 
 * Users MUST configure their own API key in WordPress Admin
 * 
 * @package ProRank\SEO\Config
 */

/**
 * Get the PageSpeed Insights API key
 * 
 * @return string|false Returns API key if configured, false otherwise
 */
function prorank_get_psi_api_key() {
    // Method 1: Check prorank_settings option directly (most reliable)
    $settings = get_option("prorank_settings", []);
    if (is_array($settings) && !empty($settings["psi_api_key"])) {
        return $settings["psi_api_key"];
    }
    
    // Method 2: Try SettingsManager if plugin is initialized
    try {
        $plugin = \ProRank\SEO\Plugin::get_instance();
        if ($plugin && $plugin->is_initialized()) {
            $settings_manager = $plugin->settings();
            if ($settings_manager) {
                // Try direct key
                $psi_key = $settings_manager->get("psi_api_key");
                if (!empty($psi_key)) {
                    return $psi_key;
                }
                
                // Try group settings
                $psi_settings = $settings_manager->get_settings("psi");
                if (!empty($psi_settings["api_key"])) {
                    return $psi_settings["api_key"];
                }
            }
        }
    } catch (\Exception $e) {
        // Plugin not initialized
    }
    
    // Method 3: Check standalone option (legacy)
    $legacy_key = get_option("prorank_seo_psi_api_key");
    if (!empty($legacy_key)) {
        return $legacy_key;
    }
    
    // No API key configured
    return false;
}

/**
 * Check if PSI API is configured
 * 
 * @return bool
 */
function prorank_has_psi_api_key() {
    $key = prorank_get_psi_api_key();
    return !empty($key) && $key !== false;
}
