<?php

include "../config/database.php";
header('Content-Type: application/json');

//$testId = 1315084;
$testId = $_POST['testId'];
$email = $_POST['email'];
$name = $_POST['name'];
$startDate = $_POST['startDate'];
$endDate = $_POST['endDate'];
//$startDate='2025-07-07 00:00:00';
//$endDate='2025-07-08 00:00:00';
if ($startDate == "" || $endDate == "") {
    $startDateTime = gmdate("Y-m-d\TH:i:s\Z", strtotime("-1 hour")); // 1 hour ago
    $endDateTime = gmdate("Y-m-d\TH:i:s\Z", strtotime("+2 days"));   // 2 days from now
} else {
    $startDateTime = toUtcIso8601($startDate);
    $endDateTime = toUtcIso8601($endDate);
}
// Build dynamic base URL (for callback and redirect)
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? "https://" : "http://";
$host = $_SERVER['HTTP_HOST'];
$basePath = rtrim(dirname($_SERVER['REQUEST_URI']), '/\\');

$callbackUrl = $protocol . $host . $basePath . '/imocha-callback.php';
$redirectUrl = $protocol . $host . $basePath . '/test-complete.php';

// Prepare payload
$payload = [
    'email' => $email,
    'name' => $name,
    'callbackUrl' => $callbackUrl,
    'redirectUrl' => $redirectUrl,
    'sendEmail' => 'no',
    'stakeholderEmails' => 'disable',
    'startDateTime' => $startDateTime,
    'endDateTime' => $endDateTime,
    'timeZoneId' => 1720, // Corrected IST zone for iMocha
    'proctoringMode' => 'disabled'
];

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

$apiUrl = "https://apiv3.imocha.io/v3/tests/$testId/invite";

$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'])) {
    echo json_encode(['success' => true, 'testUrl' => $data['testUrl']]);
} else {
    echo json_encode(['success' => false, 'error' => $data]);
}

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');
}

?>
