<?php
/**
 * ==========================
 * 🔐 IGNY8 FILE RULE HEADER
 * ==========================
 * @file         : kpi-tpl.php
 * @location     : /modules/components/kpi-tpl.php
 * @type         : Component
 * @scope        : Cross-Module
 * @allowed      : KPI rendering, metrics display
 * @reusability  : Shared
 * @notes        : Dynamic KPI component for all modules
 */

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

/**
 * Get KPI data for a specific submodule
 * 
 * @param string $table_id The table ID (e.g., 'planner_keywords')
 * @param array $kpi_config The KPI configuration array
 * @return array KPI data array
 */
function igny8_get_kpi_data($table_id, $kpi_config) {
    global $wpdb;
    
    $kpi_data = [];
    
    // Get table name from table_id
    $table_name = igny8_get_table_name($table_id);
    
    if (empty($table_name) || empty($kpi_config)) {
        return $kpi_data;
    }
    
    // Execute each KPI query
    foreach ($kpi_config as $kpi_key => $kpi_info) {
        if (!isset($kpi_info['query'])) {
            continue;
        }
        
        // Replace placeholders with actual values
        $query = str_replace('{table_name}', $table_name, $kpi_info['query']);
        $query = str_replace('{prefix}', $wpdb->prefix, $query);
        
        // Execute query safely
        $result = $wpdb->get_var($query);
        
        // Store result (handle null/empty results)
        $kpi_data[$kpi_key] = $result !== null ? (int) $result : 0;
    }
    
    return $kpi_data;
}

/**
 * Get actual table name from table ID
 * 
 * @param string $table_id The table ID (e.g., 'planner_keywords')
 * @return string The actual table name (e.g., 'wp_igny8_keywords')
 */
function igny8_get_table_name($table_id) {
    global $wpdb;
    
    // Map table IDs to actual table names
    $table_mapping = [
        'planner_home' => $wpdb->prefix . 'igny8_keywords', // Uses keywords table as base for home metrics
        'planner_keywords' => $wpdb->prefix . 'igny8_keywords',
        'planner_clusters' => $wpdb->prefix . 'igny8_clusters',
        'planner_ideas' => $wpdb->prefix . 'igny8_content_ideas',
        'writer_home' => $wpdb->prefix . 'igny8_content_ideas', // Uses ideas table as base for home metrics
        'writer_drafts' => $wpdb->prefix . 'igny8_tasks',
        'writer_published' => $wpdb->prefix . 'igny8_tasks',
        'writer_templates' => $wpdb->prefix . 'igny8_prompts',
        'writer_tasks' => $wpdb->prefix . 'igny8_tasks',
        'optimizer_audits' => $wpdb->prefix . 'igny8_logs',
        'optimizer_suggestions' => $wpdb->prefix . 'igny8_suggestions',
        'linker_backlinks' => $wpdb->prefix . 'igny8_backlinks',
        'linker_campaigns' => $wpdb->prefix . 'igny8_campaigns',
        'linker_links' => $wpdb->prefix . 'igny8_links',
        'personalize_rewrites' => $wpdb->prefix . 'igny8_variations',
        'personalize_tones' => $wpdb->prefix . 'igny8_sites',
        'personalize_data' => $wpdb->prefix . 'igny8_personalization',
        'personalize_variations' => $wpdb->prefix . 'igny8_variations',
        'personalize_records' => $wpdb->prefix . 'igny8_personalization',
        'thinker_prompts' => '' // No table needed for prompts submodule
    ];
    
    $table_name = $table_mapping[$table_id] ?? '';
    
    // Throw error if unknown table ID (except for special cases that don't need tables)
    if (empty($table_name) && !in_array($table_id, ['thinker_prompts'])) {
        throw new InvalidArgumentException("Unknown table ID: {$table_id}");
    }
    
    return $table_name;
}

/**
 * Check if a table exists in the database
 * 
 * @param string $table_name The table name to check
 * @return bool True if table exists, false otherwise
 */
function igny8_table_exists($table_name) {
    global $wpdb;
    
    $result = $wpdb->get_var($wpdb->prepare(
        "SHOW TABLES LIKE %s",
        $table_name
    ));
    
    return $result === $table_name;
}

/**
 * Get KPI data with fallback for missing tables
 * 
 * @param string $table_id The table ID
 * @param array $kpi_config The KPI configuration
 * @return array KPI data array with fallback values
 */
function igny8_get_kpi_data_safe($table_id, $kpi_config) {
    $table_name = igny8_get_table_name($table_id);
    
    // If table doesn't exist, return empty data
    if (!igny8_table_exists($table_name)) {
        $fallback_data = [];
        foreach ($kpi_config as $kpi_key => $kpi_info) {
            $fallback_data[$kpi_key] = 0;
        }
        return $fallback_data;
    }
    
    // Get real data
    return igny8_get_kpi_data($table_id, $kpi_config);
}
