<?php
// CARGA MAESTRA DE CONFIGURACIÓN Y BRANDING
require_once(__DIR__ . '/core/init.php');

// 2. Inicializar el array de resultados de IA
$ia_results = [
    'value_proposition' => '',
    'current_swot_analysis' => '',
    'business_diagnostic_radar' => null,
    'local_market_analysis' => null,
    'ideal_client_profiles' => [],
    'marketing_goal_plan' => null,
    'social_post_creations' => [],
    'post_title_sets' => [] 
];

// Asegurarse de que $pdo está disponible y $client_info tiene un ID
if (isset($pdo) && !empty($client_info['id'])) {
    
    $business_id = $client_info['id'];

    try {
        // ... (consultas 3 a 8 - VP, FODA, Radar, Market, Profiles, Plan, Social Posts) ...
        
        // 3. Consultar la Propuesta de Valor guardada (1-a-1)
        $vp_sql = "SELECT value_proposition FROM ia_value_propositions WHERE business_info_id = ?";
        $vp_stmt = $pdo->prepare($vp_sql);
        $vp_stmt->execute([$business_id]);
        $value_proposition = $vp_stmt->fetchColumn();
        if ($value_proposition !== false) {
            $ia_results['value_proposition'] = $value_proposition;
        }

        // 4. Consultar el Análisis FODA guardado (1-a-1)
        $swot_sql = "SELECT swot_content FROM ia_swot_analysis_results WHERE business_info_id = ?";
        $swot_stmt = $pdo->prepare($swot_sql);
        $swot_stmt->execute([$business_id]);
        $swot_content = $swot_stmt->fetchColumn();
        if ($swot_content !== false) {
            $ia_results['current_swot_analysis'] = $swot_content;
        }

        // 5. Consultar el Radar de Diagnóstico guardado (1-a-1)
        $radar_sql = "SELECT * FROM ia_business_diagnostic_radar_results WHERE business_info_id = ?";
        $radar_stmt = $pdo->prepare($radar_sql);
        $radar_stmt->execute([$business_id]);
        $radar_data = $radar_stmt->fetch(PDO::FETCH_ASSOC);
        if ($radar_data) {
            $radar_data['plan_de_accion'] = json_decode($radar_data['plan_de_accion'] ?? '[]', true);
            $ia_results['business_diagnostic_radar'] = $radar_data;
        }

        // 6. Consultar el Análisis de Mercado Local guardado (1-a-1)
        $market_sql = "SELECT * FROM ia_local_market_analsyis_results WHERE business_info_id = ?";
        $market_stmt = $pdo->prepare($market_sql);
        $market_stmt->execute([$business_id]);
        $market_data = $market_stmt->fetch(PDO::FETCH_ASSOC);
        if ($market_data) {
            $market_data['plan_estrategico'] = json_decode($market_data['plan_estrategico'] ?? '[]', true);
            $ia_results['local_market_analysis'] = $market_data;
        }
        
        // 7. Consultar Perfiles de Cliente Ideal (1-a-Muchos, Límite 3)
        $profiles_sql = "SELECT * FROM ia_ideal_client_generator_results WHERE business_info_id = ? ORDER BY created_at DESC";
        $profiles_stmt = $pdo->prepare($profiles_sql);
        $profiles_stmt->execute([$business_id]);
        $profiles_data = $profiles_stmt->fetchAll(PDO::FETCH_ASSOC);
        if ($profiles_data) {
            foreach ($profiles_data as &$profile) {
                $profile['sugerencias'] = json_decode($profile['sugerencias'] ?? '[]', true);
            }
            $ia_results['ideal_client_profiles'] = $profiles_data;
        }
        
        // 8. Consultar Plan de Objetivos de Marketing (1-a-1)
        $plan_sql = "SELECT * FROM ia_marketing_goal_planner_results WHERE business_info_id = ?";
        $plan_stmt = $pdo->prepare($plan_sql);
        $plan_stmt->execute([$business_id]);
        $plan_data = $plan_stmt->fetch(PDO::FETCH_ASSOC);
        if ($plan_data) {
            $plan_data['plan_de_accion'] = json_decode($plan_data['plan_de_accion'] ?? '{}', true);
            $ia_results['marketing_goal_plan'] = $plan_data;
        }

        // 9. Consultar Publicaciones Sociales (1-a-Muchos, Límite 5)
        $posts_sql = "SELECT * FROM ia_social_post_creator_results WHERE business_info_id = ? ORDER BY created_at DESC";
        $posts_stmt = $pdo->prepare($posts_sql);
        $posts_stmt->execute([$business_id]);
        $posts_data = $posts_stmt->fetchAll(PDO::FETCH_ASSOC);
        if ($posts_data) {
            $ia_results['social_post_creations'] = $posts_data;
        }

        // 10. Consultar Sets de Títulos de Publicación (1-a-Muchos, Límite 5) <-- NUEVA CONSULTA
        $titles_sql = "SELECT * FROM ia_post_title_generator_results WHERE business_info_id = ? ORDER BY created_at DESC";
        $titles_stmt = $pdo->prepare($titles_sql);
        $titles_stmt->execute([$business_id]);
        $titles_data = $titles_stmt->fetchAll(PDO::FETCH_ASSOC);
        if ($titles_data) {
            $ia_results['post_title_sets'] = $titles_data;
        }


    } catch (Throwable $e) {
        // En caso de error de BBDD en las consultas de IA, no detener la página.
        error_log("Error al cargar ia-marketing-results: " . $e->getMessage());
    }
}
?>