<?php
declare(strict_types=1);

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

ensure_schema();
$pdo = db();

header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $input = json_decode(file_get_contents('php://input') ?: '', true);
    $conversationId = (int)($input['conversation_id'] ?? 0);
    $body = trim((string)($input['body'] ?? ''));

    if ($conversationId <= 0 || $body === '') {
        http_response_code(422);
        echo json_encode(['success' => false, 'error' => 'Conversation and message body are required.']);
        exit;
    }

    $stmt = $pdo->prepare("SELECT channel FROM conversations WHERE id = ?");
    $stmt->execute([$conversationId]);
    $channel = (string)($stmt->fetchColumn() ?: 'twilio');

    $pdo->beginTransaction();
    try {
        $msgStmt = $pdo->prepare("INSERT INTO messages (conversation_id, direction, body, status, created_at) VALUES (?, 'outbound', ?, 'queued', NOW())");
        $msgStmt->execute([$conversationId, $body]);
        $messageId = (int)$pdo->lastInsertId();

        $payload = json_encode([
            'conversation_id' => $conversationId,
            'message_id' => $messageId,
            'body' => $body
        ], JSON_UNESCAPED_UNICODE);

        $queueStmt = $pdo->prepare("INSERT INTO sms_queue (message_id, provider, payload, status, attempts, created_at, updated_at) VALUES (?, ?, ?, 'queued', 0, NOW(), NOW())");
        $queueStmt->execute([$messageId, $channel, $payload]);

        $pdo->commit();
    } catch (Throwable $e) {
        $pdo->rollBack();
        http_response_code(500);
        echo json_encode(['success' => false, 'error' => 'Failed to queue message.']);
        exit;
    }

    echo json_encode(['success' => true, 'message_id' => $messageId]);
    exit;
}

$conversationId = isset($_GET['conversation_id']) ? (int)$_GET['conversation_id'] : 0;
if ($conversationId <= 0) {
    http_response_code(422);
    echo json_encode(['success' => false, 'error' => 'conversation_id is required.']);
    exit;
}

$stmt = $pdo->prepare("SELECT * FROM messages WHERE conversation_id = ? ORDER BY created_at ASC");
$stmt->execute([$conversationId]);
$rows = $stmt->fetchAll();

echo json_encode(['success' => true, 'messages' => $rows]);
