<?php
// /IAMarketing/api-db/ia-offers-promotions-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;
}

try {
    $business_id = 1; // Assuming business_info_id = 1

    // Obtener todas las ofertas guardadas
    $sql = "SELECT 
                id, 
                offer_name, 
                offer_description, 
                promo_text_es, 
                promo_text_en, 
                service_input,
                objective_input,
                created_at 
            FROM ia_offers_promotions_results 
            WHERE business_info_id = ? 
            ORDER BY created_at DESC";
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$business_id]);
    
    $results = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Reemplazar saltos de línea (\n) por <br> para visualización en el panel
    $processed_offers = array_map(function($offer) {
        $offer['promo_text_es'] = str_replace("\n", "<br>", $offer['promo_text_es']);
        $offer['promo_text_en'] = str_replace("\n", "<br>", $offer['promo_text_en']);
        return $offer;
    }, $results);

    
    echo json_encode(['success' => true, 'offers' => $processed_offers]);

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Database error while fetching offers: ' . $e->getMessage()]);
}
?>