<?php
// /IAMarketing/api-db/ia-first-contact-message-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['message_es'], $data['message_en'], $data['context_input'])) {
    $business_id = 1; // Assuming business_info_id = 1
    $message_es = $data['message_es'];
    $message_en = $data['message_en'];
    $context_input = $data['context_input'];

    try {
        // 1. Check message limit (MAX_MESSAGES = 10)
        $check_limit_sql = "SELECT COUNT(id) AS total FROM ia_first_contact_message_results WHERE business_info_id = ?";
        $check_limit_stmt = $pdo->prepare($check_limit_sql);
        $check_limit_stmt->execute([$business_id]);
        $result = $check_limit_stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($result['total'] >= 10) {
            http_response_code(403); // Forbidden
            echo json_encode(['success' => false, 'message' => 'Límite de 10 mensajes de primer contacto guardados alcanzado. Elimina uno para guardar el nuevo.']);
            exit;
        }

        // 2. Insert the new record
        $sql = "INSERT INTO ia_first_contact_message_results (business_info_id, message_es, message_en, context_input) VALUES (?, ?, ?, ?)";
        
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$business_id, $message_es, $message_en, $context_input]);
        
        echo json_encode(['success' => true, 'message' => 'Mensaje de contacto guardado con éxito.']);
    } catch (Exception $e) {
        http_response_code(500);
        $message = strpos($e->getMessage(), '1366 Incorrect string value') !== false ? 'Error de codificación (utf8mb4 requerido). Ejecuta el comando SQL de corrección.' : 'Database error while creating message: ' . $e->getMessage();
        echo json_encode(['success' => false, 'message' => $message]);
    }
} else {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Required message data (message_es, message_en, context_input) not received.']);
}
?>