#!/usr/bin/env php
<?php

declare(strict_types=1);

// Quick manual test script: fetches a session's attendance directly from
// SWDA (GET /courses/runs/{runId}/sessions/attendance) and prints the JSON
// response.
//
// Usage: php scripts/course_session_attendance_get <runId> <courseReferenceNumber> <sessionId>

error_reporting(E_ALL & ~E_DEPRECATED & ~E_NOTICE);

require __DIR__.'/../vendor/autoload.php';

$app = require __DIR__.'/../bootstrap/app.php';
$app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();

$runId = $argv[1] ?? null;
$courseReferenceNumber = $argv[2] ?? null;
$sessionId = $argv[3] ?? null;

if (! $runId || ! $courseReferenceNumber || ! $sessionId) {
    fwrite(STDERR, "Usage: php scripts/course_session_attendance_get <runId> <courseReferenceNumber> <sessionId>\n");
    exit(1);
}

$query = http_build_query([
    'uen' => config('swda.training_provider_uen'),
    'courseReferenceNumber' => $courseReferenceNumber,
    'sessionId' => $sessionId,
]);

$url = rtrim((string) config('swda.base_url'), '/')."/courses/runs/{$runId}/sessions/attendance?{$query}";
$timestampSgt = (new DateTime('now', new DateTimeZone('Asia/Singapore')))->format('Y-m-d H:i:s').' SGT';

echo "========================================\n";
echo "[GET /courses/runs/{$runId}/sessions/attendance]\n";
echo "Course Reference Number: {$courseReferenceNumber}\n";
echo "Session ID: {$sessionId}\n";
echo "Timestamp: {$timestampSgt}\n";
echo "URL: {$url}\n";
echo "========================================\n";

$ch = curl_init();
curl_setopt_array($ch, [
    CURLOPT_URL => $url,
    CURLOPT_CUSTOMREQUEST => 'GET',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => [
        'Accept: application/json',
        'x-api-version: v1.5',
    ],
    CURLOPT_SSLCERT => config('swda.client.cert_path'),
    CURLOPT_SSLKEY => config('swda.client.key_path'),
    CURLOPT_TIMEOUT => 60,
]);

$body = curl_exec($ch);
$httpCode = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
$curlError = curl_error($ch);
curl_close($ch);

echo "HTTP Status Code: {$httpCode}\n";
echo "Full JSON Response:\n";

if ($curlError !== '') {
    echo json_encode(['curl_error' => $curlError], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)."\n";
    exit(1);
}

$crypto = new App\Services\Swda\SwdaCrypto(
    config('swda.encryption.key'),
    config('swda.encryption.iv'),
);

try {
    $decoded = $crypto->decrypt((string) $body);
} catch (\Throwable $e) {
    echo 'Could not decode response as JSON or SWDA ciphertext: '.$e->getMessage()."\n";
    echo $crypto->preview((string) $body)."\n";
    exit(1);
}

echo json_encode($decoded, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)."\n";
