<?php
// /IAMarketing/api-db/ia-first-contact-message-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['message_es'], $data['message_en'], $data['context_input'])) {
    $message_id = $data['id'];
    $message_es = $data['message_es'];
    $message_en = $data['message_en'];
    $context_input = $data['context_input'];
    $business_id = 1; // Assuming business_info_id = 1
    
    try {
        $sql = "UPDATE ia_first_contact_message_results 
                SET message_es = ?, message_en = ?, context_input = ?
                WHERE id = ? AND business_info_id = ?";
        
        $params = [$message_es, $message_en, $context_input, $message_id, $business_id];
        
        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);
        
        if ($stmt->rowCount() > 0) {
            echo json_encode(['success' => true, 'message' => 'Mensaje de contacto actualizado con éxito.']);
        } else {
            echo json_encode(['success' => true, 'message' => 'Mensaje actualizado (sin cambios detectados o ID no encontrado).']);
        }
        
    } catch (Exception $e) {
        http_response_code(500);
        echo json_encode(['success' => false, 'message' => 'Database error while updating message: ' . $e->getMessage()]);
    }
} else {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Required update data not received.']);
}
?>