<?php
/**
 * Background Worker Trigger (HTTP)
 * POST /api/v1/batches/process-worker
 * 
 * This endpoint is triggered by finalize.php to start processing in the background.
 */

declare(strict_types=1);

require_once __DIR__ . '/../../../bootstrap/init.php';

use App\Services\InvoiceProcessor;
use App\Core\Database;

// 1. Ignore user abort and set no time limit
ignore_user_abort(true);
set_time_limit(0);

// 2. Get batch ID
$data = json_decode(file_get_contents('php://input'), true);
$batchId = $data['batch_id'] ?? null;

if (!$batchId) {
    exit('No batch ID');
}

// 3. Process all pending items for this batch
$db = Database::getInstance();
$stmt = $db->prepare("SELECT id FROM invoice_processing_queue WHERE batch_id = ? AND status = 'pending'");
$stmt->execute([$batchId]);
$items = $stmt->fetchAll();

foreach ($items as $item) {
    InvoiceProcessor::processQueueItem((int)$item['id']);
}

echo "Done";
