<?php
// /IAMarketing/api-db/ia-ads-generator-update.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;
}

$data = json_decode(file_get_contents('php://input'), true);

if (isset($data['id'], $data['title_ad'], $data['gancho_es'], $data['solucion_es'], $data['cta_es'])) {
    $ad_id = $data['id'];
    $title_ad = $data['title_ad'];
    $gancho_es = $data['gancho_es'];
    $solucion_es = $data['solucion_es'];
    $cta_es = $data['cta_es'];
    $gancho_en = $data['gancho_en'] ?? '';
    $solucion_en = $data['solucion_en'] ?? '';
    $cta_en = $data['cta_en'] ?? '';
    $business_id = 1; // Assuming business_info_id = 1
    
    try {
        $sql = "UPDATE ia_ads_generator_results 
                SET title_ad = ?, gancho_es = ?, solucion_es = ?, cta_es = ?, gancho_en = ?, solucion_en = ?, cta_en = ?
                WHERE id = ? AND business_info_id = ?";
        
        $params = [
            $title_ad, 
            $gancho_es, 
            $solucion_es, 
            $cta_es, 
            $gancho_en, 
            $solucion_en, 
            $cta_en, 
            $ad_id, 
            $business_id
        ];
        
        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);
        
        if ($stmt->rowCount() > 0) {
            echo json_encode(['success' => true, 'message' => 'Anuncio publicitario actualizado con éxito.']);
        } else {
            echo json_encode(['success' => true, 'message' => 'Anuncio actualizado (no cambios detectados o ID no encontrado).']);
        }
        
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['success' => false, 'message' => 'Database error while updating ad: ' . $e->getMessage()]);
    }
} else {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Required update data not received.']);
}
?>