<?php
/**
 * Batch Status Endpoint
 * GET /v1/batches/status
 * 
 * Returns the processing status of a batch and its items.
 */

declare(strict_types=1);

use App\Core\Database;
use App\Middleware\AuthMiddleware;
use App\Core\Security;

$decoded = AuthMiddleware::check();
$tenantId = $decoded['tenant_id'];
$userId = $decoded['user_id'];

$data = Security::sanitize($_GET);
$batchId = $data['batch_id'] ?? null;

if (!$batchId) {
    json_error('معرّف الدفعة مطلوب', 422);
}

$db = Database::getInstance();

// 1. Get batch info
$stmt = $db->prepare("
    SELECT id, status, total_images, processed_images, failed_images, created_at, completed_at
    FROM invoice_batches 
    WHERE id = ? AND tenant_id = ?
");
$stmt->execute([$batchId, $tenantId]);
$batch = $stmt->fetch();

if (!$batch) {
    json_error('الدفعة غير موجودة', 404);
}

// 2. Get items
$stmt = $db->prepare("
    SELECT id, invoice_id, image_order, status, error_message, created_at, processed_at
    FROM invoice_processing_queue
    WHERE batch_id = ?
    ORDER BY image_order ASC
");
$stmt->execute([$batchId]);
$items = $stmt->fetchAll();

json_success([
    'batch' => $batch,
    'items' => $items
], 'تم جلب حالة الدفعة');
