<?php
// /IAMarketing/api-db/ia-ads-generator-fetch.php
ob_start();
require_once __DIR__ . '/../client-information.php'; 
ob_clean();

header('Content-Type: application/json');

if (!isset($pdo)) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Database connection error.']);
    exit;
}

$business_id = 1;

try {
    // Select all fields needed for the panel, ordered by creation date
    $sql = "SELECT id, ad_type, title_ad, gancho_es, solucion_es, cta_es, gancho_en, solucion_en, cta_en, service_input, problem_input, desire_input, created_at FROM ia_ads_generator_results WHERE business_info_id = ? ORDER BY created_at DESC";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$business_id]);
    $ads_data = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Aquí podrías procesar problem_input y desire_input si fueran JSON, pero los dejamos como texto.
    
    echo json_encode(['success' => true, 'ads' => $ads_data, 'message' => 'Ads fetched successfully.']);
    
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Database error while fetching ads: ' . $e->getMessage()]);
}
?>