<?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');

$stmt = $pdo->prepare("SELECT value FROM settings WHERE name = ?");
$stmt->execute(['sms_unit_price']);
$unitPrice = (float)($stmt->fetchColumn() ?: 0.05);

$queueItems = $pdo->query("SELECT q.id, q.message_id FROM sms_queue q WHERE q.status = 'queued' ORDER BY q.id ASC LIMIT 20")->fetchAll();
if (!$queueItems) {
    echo json_encode(['success' => true, 'processed' => 0]);
    exit;
}

$processed = 0;
$pdo->beginTransaction();
try {
    $updateQueue = $pdo->prepare("UPDATE sms_queue SET status = 'sent', attempts = attempts + 1 WHERE id = ?");
    $updateMessage = $pdo->prepare("UPDATE messages SET status = 'sent' WHERE id = ?");
    $getDirection = $pdo->prepare("SELECT direction FROM messages WHERE id = ?");
    $billStmt = $pdo->prepare("INSERT INTO billing_events (message_id, units, unit_price, total_cost, created_at) VALUES (?, 1, ?, ?, NOW())");

    foreach ($queueItems as $item) {
        $updateQueue->execute([$item['id']]);
        $updateMessage->execute([$item['message_id']]);
        $getDirection->execute([$item['message_id']]);
        $direction = (string)($getDirection->fetchColumn() ?: '');
        if ($direction === 'outbound') {
            $billStmt->execute([$item['message_id'], $unitPrice, $unitPrice]);
        }
        $processed++;
    }
    $pdo->commit();
} catch (Throwable $e) {
    $pdo->rollBack();
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => 'Queue processing failed.']);
    exit;
}

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