<?php
// Client polls job status to drive reward animations.

require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/session_bootstrap.php';

require_once __DIR__ . '/internal/respond.php';
require_once __DIR__ . '/../../../administration/includes/config.php';

if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true) {
    og_respond(['success' => false, 'error' => 'Unauthorized'], 401);
}

if (!isset($pdo) || !($pdo instanceof PDO)) {
    og_respond(['success' => false, 'error' => 'Database connection not initialized'], 500);
}

$jobId = isset($_GET['jobId']) ? (int) $_GET['jobId'] : 0;
if ($jobId <= 0) {
    og_respond(['success' => false, 'error' => 'Missing jobId'], 400);
}

$stmt = $pdo->prepare('SELECT id, status, payload_json, result_json, last_error, created_at, updated_at FROM rewards_jobs WHERE id = :id');
$stmt->execute([':id' => $jobId]);
$row = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$row) {
    og_respond(['success' => false, 'error' => 'Not found'], 404);
}

$payload = null;
if (!empty($row['payload_json'])) {
    $payload = json_decode($row['payload_json'], true);
}

$sessionUserId = (int)($_SESSION['user_id'] ?? 0);
if ($sessionUserId <= 0) {
    og_respond(['success' => false, 'error' => 'Unauthorized'], 401);
}

// Only participants may poll
$winnerId = (int)($payload['winnerUserId'] ?? 0);
$loserId = (int)($payload['loserUserId'] ?? 0);
if ($winnerId && $loserId && $sessionUserId !== $winnerId && $sessionUserId !== $loserId) {
    og_respond(['success' => false, 'error' => 'Forbidden'], 403);
}

$result = null;
if (!empty($row['result_json'])) {
    $result = json_decode($row['result_json'], true);
}

og_respond([
    'success' => true,
    'job' => [
        'id' => (int) $row['id'],
        'status' => $row['status'],
        'result' => $result,
        'last_error' => $row['last_error'],
        'created_at' => $row['created_at'],
        'updated_at' => $row['updated_at'],
    ]
]);
