<?php
// /IAMarketing/api-db/ia-services-descriptions-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['purpose_description'], $data['text_es'], $data['text_en'])) {
    $desc_id = $data['id'];
    $purpose_description = $data['purpose_description'];
    $text_es = $data['text_es'];
    $text_en = $data['text_en'];
    $business_id = 1; // Assuming business_info_id = 1
    
    try {
        $sql = "UPDATE ia_services_descriptions_results 
                SET purpose_description = ?, text_es = ?, text_en = ?
                WHERE id = ? AND business_info_id = ?";
        
        $params = [$purpose_description, $text_es, $text_en, $desc_id, $business_id];
        
        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);
        
        if ($stmt->rowCount() > 0) {
            echo json_encode(['success' => true, 'message' => 'Descripción de servicio actualizada con éxito.']);
        } else {
            echo json_encode(['success' => true, 'message' => 'Descripción actualizada (no cambios detectados o ID no encontrado).']);
        }
        
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['success' => false, 'message' => 'Database error while updating description: ' . $e->getMessage()]);
    }
} else {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Required update data not received.']);
}
?>