<?php
declare(strict_types=1);
define('ACC_BASE_PATH', __DIR__);
require __DIR__ . '/standalone/bootstrap.php';

$base = 'http://127.0.0.1/acc-engine/api.php/acc/v1';
$ch = curl_init("$base/public/auth/login");
curl_setopt_array($ch, [
    CURLOPT_POST => true, CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
    CURLOPT_POSTFIELDS => json_encode(['username' => 'edu_student_skill', 'password' => 'Edu@1404']),
]);
$j = json_decode((string) curl_exec($ch), true);
curl_close($ch);
$token = $j['token'] ?? '';
$hdr = ["Authorization: Bearer $token", 'Content-Type: application/json'];

foreach ([
    ['session_type' => 'academic', 'track' => 'konkur', 'domain' => 'math'],
    ['session_type' => 'skill', 'track' => 'skill', 'domain' => 'music'],
] as $case) {
    $body = json_encode(array_merge([
        'full_name' => 'تست', 'grade_level' => '10',
        'goals' => [$case['session_type'] === 'skill' ? 'skill_hobby' : 'konkur_exam'],
        'delivery_mode' => 'virtual', 'venue_type' => 'online', 'consent_privacy' => true,
    ], $case));
    $ch = curl_init("$base/education/requests");
    curl_setopt_array($ch, [CURLOPT_POST => true, CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => $hdr, CURLOPT_POSTFIELDS => $body]);
    $req = json_decode((string) curl_exec($ch), true);
    curl_close($ch);
    $rid = (int) ($req['request_id'] ?? 0);
    $ch = curl_init("$base/education/requests/$rid/test");
    curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => [$hdr[0]]]);
    $test = json_decode((string) curl_exec($ch), true);
    curl_close($ch);
    $answers = [];
    foreach ($test['phases'] ?? [] as $phase) {
        foreach ($phase['questions'] ?? [] as $q) {
            if (isset($q['correct'])) {
                $answers[$q['id']] = $q['correct'];
            } else {
                $answers[$q['id']] = 4;
            }
        }
    }
    $ch = curl_init("$base/education/requests/$rid/submit");
    curl_setopt_array($ch, [CURLOPT_POST => true, CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => $hdr, CURLOPT_POSTFIELDS => json_encode(['answers' => $answers])]);
    $sub = json_decode((string) curl_exec($ch), true);
    curl_close($ch);
    echo $case['session_type'] . ': ref=' . ($req['ref_code'] ?? '') . ' phases=' . count($test['phases'] ?? []) . ' submit=' . ($sub['success'] ? 'ok' : 'fail') . PHP_EOL;
}
