<?php
declare(strict_types=1);

require_once __DIR__ . '/../db/config.php';
require_once __DIR__ . '/../includes/schema.php';

ensure_schema();
$pdo = db();

$from = trim((string)($_POST['From'] ?? ($_GET['from'] ?? '')));
$body = trim((string)($_POST['Body'] ?? ($_GET['body'] ?? '')));

if ($from === '' || $body === '') {
    http_response_code(400);
    echo 'Missing From or Body';
    exit;
}

$stmt = $pdo->prepare("SELECT id FROM conversations WHERE phone = ? LIMIT 1");
$stmt->execute([$from]);
$conversationId = (int)($stmt->fetchColumn() ?: 0);

if ($conversationId === 0) {
    $insert = $pdo->prepare("INSERT INTO conversations (contact_name, phone, channel, created_at) VALUES (?, ?, 'twilio', NOW())");
    $insert->execute([$from, $from]);
    $conversationId = (int)$pdo->lastInsertId();
}

$msgStmt = $pdo->prepare("INSERT INTO messages (conversation_id, direction, body, status, created_at) VALUES (?, 'inbound', ?, 'received', NOW())");
$msgStmt->execute([$conversationId, $body]);

header('Content-Type: text/plain');
echo "OK";
