<?php
// /IAMarketing/api-db/ia-services-descriptions-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);

if (isset($data['type'], $data['purpose_description'], $data['text_es'], $data['text_en'])) {
    $business_id = 1; // Assuming business_info_id = 1
    $type = $data['type'];
    $purpose_description = $data['purpose_description'];
    $text_es = $data['text_es'];
    $text_en = $data['text_en'];
    
    // Inputs de referencia (vienen del frontend)
    $service_name_input = $data['service_name_input'] ?? 'N/A';
    $features_input = $data['features_input'] ?? 'N/A';

    try {
        // 1. Check if a record already exists for this business_info_id and type (UNIQUE constraint)
        $check_sql = "SELECT id FROM ia_services_descriptions_results WHERE business_info_id = ? AND type = ?";
        $check_stmt = $pdo->prepare($check_sql);
        $check_stmt->execute([$business_id, $type]);
        
        if ($check_stmt->fetch(PDO::FETCH_ASSOC)) {
            // Error 409: Conflicto (ya existe un registro de este tipo)
            http_response_code(409); 
            echo json_encode(['success' => false, 'message' => 'Ya existe una descripción de tipo "' . htmlspecialchars($type) . '" guardada. Elimina la anterior para guardar esta nueva versión.']);
            exit;
        }
        
        // 2. Insert the new record
        $sql = "INSERT INTO ia_services_descriptions_results (business_info_id, type, purpose_description, text_es, text_en, service_name_input, features_input) VALUES (?, ?, ?, ?, ?, ?, ?)";
        
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$business_id, $type, $purpose_description, $text_es, $text_en, $service_name_input, $features_input]);
        
        echo json_encode(['success' => true, 'message' => 'Descripción de servicio guardada 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 (utf8mb4 requerido). Ejecuta el comando SQL de corrección.' : 'Database error while creating description: ' . $e->getMessage();
        echo json_encode(['success' => false, 'message' => $message]);
    }
} else {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Required description data (type, text_es, text_en) not received.']);
}
?>