<?php
// send.php
require 'config.php';
$data = json_decode(file_get_contents('php://input'), true);
$user_id = intval($data['user_id'] ?? 0);
$user_name = trim($data['user_name'] ?? 'Guest');
$msg = trim($data['message'] ?? '');
if($msg === '') { http_response_code(400); echo json_encode(['error'=>'empty']); exit; }

// insert user message
$stmt = $pdo->prepare("INSERT INTO messages (user_id,user_name,message) VALUES (?,?,?)");
$stmt->execute([$user_id,$user_name,$msg]);
$insertId = $pdo->lastInsertId();

// run auto-reply synchronously
require 'bot_reply.php';
$botReply = get_auto_reply($msg, $pdo, $site_root); // function returns string or null

if($botReply){
  $stmt = $pdo->prepare("INSERT INTO messages (user_id,user_name,message) VALUES (?,?,?)");
  $stmt->execute([0,'Bot',$botReply]);
}

header('Content-Type: application/json');
echo json_encode(['status'=>'ok','id'=>$insertId, 'bot_reply'=> (bool)$botReply]);
