<?php
/**
 * GET /api/tasks/status?reservation_id=RES_...
 * Check the status of a reservation.
 *
 * Response:
 *   { reservation_id, status, tasks_completed, tasks_failed,
 *     reserved_sdg, actual_sdg, refunded_sdg,
 *     expires_at, plan:{...}, results:[...] }
 */
require_once __DIR__ . '/../../config.php';
require_once __DIR__ . '/../../engine/Kernel.php';
require_once __DIR__ . '/../../engine/ReservationEngine.php';

$ctx = Kernel::handle(['auth' => true, 'rate' => 'api']);
$user = $ctx['user'];

$reservationId = preg_replace('/[^A-Za-z0-9_]/', '', $_GET['reservation_id'] ?? '');
if (!$reservationId) Kernel::fail('missing_reservation_id', 'معرّف الحجز مطلوب', 400);

$res = ReservationEngine::getById($reservationId);
if (!$res) Kernel::fail('not_found', 'الحجز غير موجود', 404);

// Ownership check — user can only see their own reservations
if ((int)$res['user_id'] !== (int)$user['id']) {
    Kernel::fail('forbidden', 'ليس لديك صلاحية لهذا الحجز', 403);
}

$plan = json_decode($res['estimated_plan'], true);

Kernel::respond([
    'reservation_id'   => $res['reservation_id'],
    'status'           => $res['status'],
    'tasks_total'      => (int)$res['tasks_total'],
    'tasks_completed'  => (int)$res['tasks_completed'],
    'tasks_failed'     => (int)$res['tasks_failed'],
    'reserved_sdg'     => (int)$res['reserved_sdg'],
    'actual_sdg'       => $res['actual_sdg'] !== null ? (int)$res['actual_sdg'] : null,
    'refunded_sdg'     => (int)$res['refunded_sdg'],
    'expires_at'       => $res['expires_at'],
    'reserved_at'      => $res['reserved_at'],
    'completed_at'     => $res['completed_at'],
    'plan'             => $plan,
    'results'          => $res['execution_log'] ? json_decode($res['execution_log'], true) : null,
]);
