<?php
include "../config/database.php";

// Get POSTed data
$email = $_POST['email'];
$courseId = $_POST['courseid'];
$activityModuleId = $_POST['activityModuleId'];
$username = strtolower($_POST['username']);
$firstName = $_POST['firstname'];
$lastName = 'lab'; // or make it dynamic
$password = $firstName.$lastName."@1";

// Step 1: Get or Create User
$user = getUserByEmail($email, $baseUrl, $wstoken);
if (!$user) {
    $user = createUser($email, $username, $firstName, $lastName, $password, $baseUrl, $wstoken);
    if (!$user) {
        echo "User creation failed";
        exit;
    }
}
$userId = $user['id'];

// Step 2: Check Enrollment
$enrolled = isUserEnrolled($userId, $courseId, $baseUrl, $wstoken);
if (!$enrolled) {
    $enrolled = enrollUser($userId, $courseId, $baseUrl, $wstoken);
    if (!$enrolled) {
        echo "Enrollment failed";
        exit;
    }
}

// Step 3: Get Auto-login URL
$url = getAutologinUrl($email, $courseId, $activityModuleId, $baseUrl, $wstoken);
echo $url ?: "Autologin URL generation failed";


// ---------- Helper Functions ----------
function postRequest($url, $data) {
    $curl = curl_init($url);
    curl_setopt_array($curl, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => http_build_query($data),
        CURLOPT_HTTPHEADER => ['Content-Type: application/x-www-form-urlencoded'],
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_SSL_VERIFYPEER => false, 
        CURLOPT_SSL_VERIFYHOST => false
    ]);
    $response = curl_exec($curl);
    curl_close($curl);
    return json_decode($response, true);
}

function getUserByEmail($email, $baseUrl, $token) {
    $data = [
        'wstoken' => $token,
        'wsfunction' => 'core_user_get_users_by_field',
        'field' => 'email',
        'values[0]' => $email
    ];
    $response = postRequest($baseUrl, $data);
    return isset($response[0]) ? $response[0] : null;
}

function createUser($email, $username, $first, $last, $password, $baseUrl, $token) {
    $data = [
        'wstoken' => $token,
        'wsfunction' => 'core_user_create_users',
        'users[0][username]' => $username,
        'users[0][email]' => $email,
        'users[0][firstname]' => $first,
        'users[0][lastname]' => $last,
        'users[0][password]' => $password
    ];
    $response = postRequest($baseUrl, $data);
    return isset($response[0]) ? $response[0] : null;
}

function isUserEnrolled($userId, $courseId, $baseUrl, $token) {
    $data = [
        'wstoken' => $token,
        'wsfunction' => 'core_enrol_get_enrolled_users',
        'courseid' => $courseId
    ];
    $res = postRequest($baseUrl, $data);
    foreach ($res as $u) {
        if ($u['id'] == $userId) return true;
    }
    return false;
}

function enrollUser($userId, $courseId, $baseUrl, $token) {
    $data = [
        'wstoken' => $token,
        'wsfunction' => 'enrol_manual_enrol_users',
        'enrolments[0][roleid]' => 5,
        'enrolments[0][userid]' => $userId,
        'enrolments[0][courseid]' => $courseId
    ];
    $res = postRequest($baseUrl, $data);
    return empty($res);
}

function getAutologinUrl($email, $courseId, $activityModuleId, $baseUrl, $token) {
    $data = [
        'wstoken' => $token,
        'wsfunction' => 'auth_npauth_generate_autologin_url',
        'email' => $email
    ];
    if (!empty($activityModuleId)) {
        $data['activityModuleId'] = $activityModuleId;
    }else{
        $data['courseid'] = $courseId;
    }
    $res = postRequest($baseUrl, $data);
    return $res['redirecturl'];
}
