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

declare(strict_types=1);

// Quick manual test script: searches enrolments directly on SWDA
// (POST /tpg/enrolments/search) and prints the JSON response.
//
// Usage: php scripts/enrolment_search <courseRunId> <courseReferenceNumber> [status]

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

$courseRunId = $argv[1] ?? null;
$courseReferenceNumber = $argv[2] ?? null;
$status = $argv[3] ?? 'Confirmed';

if (! $courseRunId || ! $courseReferenceNumber) {
    fwrite(STDERR, "Usage: php scripts/enrolment_search <courseRunId> <courseReferenceNumber> [status]\n");
    exit(1);
}

$payload = [
    // 'meta' => [
    //     'lastUpdateDateTo' => '2026-08-19',
    //     'lastUpdateDateFrom' => '2026-01-01',
    // ],
    // 'sortBy' => [
    //     'field' => 'updatedOn',
    //     'order' => 'asc',
    // ],
    'enrolment' => [
        'course' => [
            'run' => [
                'id' => $courseRunId,
            ],
            'referenceNumber' => $courseReferenceNumber,
        ],
        // 'status' => $status,
        'trainingPartner' => [
            'uen' => config('swda.training_provider_uen'),
            'code' => config('swda.training_provider_code'),
        ],
    ],
    'parameters' => [
        'page' => 0,
        'pageSize' => 100,
    ],
];

$url = rtrim((string) config('swda.base_url'), '/').'/tpg/enrolments/search';
$timestampSgt = (new DateTime('now', new DateTimeZone('Asia/Singapore')))->format('Y-m-d H:i:s').' SGT';

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

echo "========================================\n";
echo "[POST /tpg/enrolments/search]\n";
echo "Timestamp: {$timestampSgt}\n";
echo "URL: {$url}\n";
echo "Request Body (plaintext):\n";
echo json_encode($payload, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)."\n";
echo "Request Body (encrypted, base64):\n";
echo $encryptedBody."\n";
echo "========================================\n";

$ch = curl_init();
curl_setopt_array($ch, [
    CURLOPT_URL => $url,
    CURLOPT_CUSTOMREQUEST => 'POST',
    CURLOPT_POSTFIELDS => $encryptedBody,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => [
        'Accept: application/json',
        'Content-Type: 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";

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

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