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

// Se verifica que todos los campos principales (ES + EN) vengan en el payload
if (isset($data['ad_type'], $data['title_ad'], $data['gancho_es'], $data['solucion_es'], $data['cta_es'], $data['gancho_en'], $data['solucion_en'], $data['cta_en'])) {
    $business_id = 1; // Assuming business_info_id = 1
    $ad_type = $data['ad_type'];
    $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'];      
    
    // Inputs usados en la generación (ahora desde el objeto inputs del frontend)
    $service_input = $data['service_input'] ?? 'N/A';
    $problem_input = $data['problem_input'] ?? 'N/A'; 
    $desire_input = $data['desire_input'] ?? 'N/A'; 

    try {
        // 1. Check if a record already exists for this business_info_id and ad_type (UNIQUE constraint)
        $check_sql = "SELECT id FROM ia_ads_generator_results WHERE business_info_id = ? AND ad_type = ?";
        $check_stmt = $pdo->prepare($check_sql);
        $check_stmt->execute([$business_id, $ad_type]);
        
        if ($check_stmt->fetch(PDO::FETCH_ASSOC)) {
            // Error 409: Conflicto (solo se permite UN registro por tipo de anuncio)
            http_response_code(409); 
            echo json_encode(['success' => false, 'message' => 'Ya existe un anuncio de tipo "' . htmlspecialchars($ad_type) . '" guardado. Edita o elimina el anterior.']);
            exit;
        }
        
        // 2. Insert the new record (con todos los campos ES + EN)
        $sql = "INSERT INTO ia_ads_generator_results (business_info_id, ad_type, title_ad, gancho_es, solucion_es, cta_es, gancho_en, solucion_en, cta_en, service_input, problem_input, desire_input) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        
        $stmt = $pdo->prepare($sql);
        $stmt->execute([
            $business_id, 
            $ad_type, 
            $title_ad, 
            $gancho_es, 
            $solucion_es, 
            $cta_es, 
            $gancho_en, 
            $solucion_en, 
            $cta_en, 
            $service_input, 
            $problem_input, 
            $desire_input
        ]);
        
        echo json_encode(['success' => true, 'message' => 'Anuncio publicitario guardado con éxito.']);
    } catch (Exception $e) {
        http_response_code(500);
        $message = strpos($e->getMessage(), '1366 Incorrect string value') !== false ? 'Error de codificación de la base de datos. Ejecuta: ALTER TABLE ia_ads_generator_results CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;' : 'Database error while creating ad: ' . $e->getMessage();
        echo json_encode(['success' => false, 'message' => $message]);
    }
} else {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Required ad data (ES or EN version missing) not received.']);
}
?>