<?php

include "../config/database.php";
include_once "../resources/assessment.php";
header('Content-Type: application/json');
$assessment = new Assessment();

// === INPUT ===
$testId = $_POST['testId'];
$email = $_POST['email'];
$name = $_POST['name'];
$startDate = $_POST['startDate'];
$endDate = $_POST['endDate'];
$current_attempt = $_POST['current_attempt'];

$assessment->passing_score = 0;
$assessment->weightage = "";
$assessment->total_score = 0;
$assessment->score = 0;
$assessment->last_updated_ts = $date_time;
$assessment->offering_id = $_POST['offering_id'];
$assessment->assessment_id = $_POST['assmt_id'];
$assessment->user_id = $_POST['user_id'];

$oid=$_POST['offering_id'];

if (!$testId || !$email || !$name) {
    echo json_encode(['success' => false, 'error' => 'Missing required fields.']);
    exit;
}

// === DATE LOGIC ===
function toUtcIso8601($localTime) {
    $date = new DateTime($localTime, new DateTimeZone('Asia/Kolkata'));
    $date->setTimezone(new DateTimeZone('UTC'));
    return $date->format('Y-m-d\TH:i:s\Z');
}

$startDateTime = $startDate ? toUtcIso8601($startDate) : gmdate("Y-m-d\TH:i:s\Z", strtotime("-1 hour"));
$endDateTime = $endDate ? toUtcIso8601($endDate) : gmdate("Y-m-d\TH:i:s\Z", strtotime("+2 days"));

// === DYNAMIC URL BUILD ===
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? "https://" : "http://";
$host = $_SERVER['HTTP_HOST'];
$basePath = "/client_imocha"; // STATIC since you know your structure

$callbackUrl = $protocol . $host . $basePath . '/assessment/imocha-callback.php';
$redirectUrl = $protocol . $host . $basePath . '/courseview.php?offering='.$oid;

// === CURL CALL ===
$headers = [
    "Content-Type: application/json",
    "x-api-key: $iMocha_apiKey"
];

if ($current_attempt == 1) {
    $payload = [
        'email' => $email,
        'name' => $name,
        'callbackUrl' => $callbackUrl,
        'redirectUrl' => $redirectUrl
//    'sendEmail' => 'no',
//    'stakeholderEmails' => 'disable',
//    'startDateTime' => $startDateTime,
//    'endDateTime' => $endDateTime,
//    'timeZoneId' => 1720, // IST
//    'proctoringMode' => 'disabled'
    ];
    $apiUrl = "https://apiv3.imocha.io/v3/tests/$testId/invite";
} else {
    // === PAYLOAD ===
    $payload = [
        'startDateTime' => $startDateTime,
        'endDateTime' => $endDateTime,
        'timeZoneId' => 1720, // IST
        'callbackUrl' => $callbackUrl,
        'redirectUrl' => $redirectUrl
    ];
    $testInvitationId = $assessment->get_testId($current_attempt-1);
    $apiUrl = "https://apiv3.imocha.io/v3/invitations/{$testInvitationId}/reattempt";
}

$ch = curl_init($apiUrl);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

$data = json_decode($response, true);

if ($httpCode === 200 && isset($data['testUrl'])) {

    $assessment->test_url = $data['testUrl'];
    $assessment->test_invitation_id = $data['testInvitationId'];
   
    $assessment->attempt_no = $current_attempt;
    if ($assessment->quiz_score_initial_insert()) {
        
    }
    echo json_encode(['success' => true, 'testUrl' => $data['testUrl'], 'testInvitationId' => $data['testInvitationId']]);
} else {
    echo json_encode(['success' => false, 'error' => $data]);
}
?>
