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

declare(strict_types=1);

// Quick manual test script: fetches a course directory entry directly from
// SWDA (GET /courses/directory/{courseReferenceNumber}) and prints the JSON
// response.
//
// Usage: php scripts/course_details <courseReferenceNumber>

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();

$courseReferenceNumber = $argv[1] ?? null;

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

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

echo "========================================\n";
echo "[GET /courses/directory/{$courseReferenceNumber}]\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',
    ],
    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";

$decoded = json_decode((string) $body, true);
if (json_last_error() === JSON_ERROR_NONE) {
    echo json_encode($decoded, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)."\n";
} else {
    if ($curlError !== '') {
        echo json_encode(['curl_error' => $curlError], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)."\n";
    }
    echo (string) $body."\n";
}
