<?php
// File: redirect_to_lms.php
date_default_timezone_set('Asia/Kolkata');
include('../config.php');
@session_start();

// ✅ Step 1: Session Check
@$user_id1 = $_SESSION['user_id1'];
if (!isset($user_id1)) {
    die("❌ ERROR: User session 'user_id1' not set. Please login.");
}
echo "✅ Logged-in Portal User: $user_id1<br>";

$timeout = 60 * 60 * 24 * 365;
$s_name = session_name();
if (isset($_COOKIE[$s_name])) {
    setcookie($s_name, $_COOKIE[$s_name], time() + $timeout, '/');
}

// ✅ Step 2: Fetch Employee Data from hr_dump
$sel1 = mysqli_query($conn, "SELECT * FROM hr_dump WHERE empid = '$user_id1'");
if (!$sel1) {
    die("❌ ERROR: hr_dump query failed - " . mysqli_error($conn));
}
$fetch1 = mysqli_fetch_array($sel1);
if (!$fetch1) {
    die("❌ ERROR: No record found in hr_dump for empid = $user_id1");
}
$empid = $fetch1['empid'];
echo "✅ Found Employee: $empid<br>";

// ✅ Step 3: Generate Token
$token = bin2hex(random_bytes(32));
$expiry = time() + 300; // 5 mins validity
echo "🔐 Token Generated: $token<br>";

// ✅ Step 4: Send Token to Moodle via API
$api_url = "http://54.157.251.46/lms/local/token_receiver.php"; // Moodle token receiver
$api_key = "3e8b4c75b21dfc1b2a7b9f2f4aa123be"; // Same as Moodle-side script

$data = [
    'apikey' => $api_key,
    'empid' => $empid,
    'token' => $token,
    'expiry' => $expiry
];

$options = [
    'http' => [
        'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
        'method'  => 'POST',
        'content' => http_build_query($data),
        'timeout' => 10
    ]
];

$context = stream_context_create($options);
$result = @file_get_contents($api_url, false, $context);
$response = json_decode($result, true);

// ✅ Step 5: Check API Response
if (!$response || $response['status'] !== 'success') {
    $error = $response['message'] ?? 'Unknown error';
    die("❌ Moodle token API error: " . $error);
}
echo "✅ Token successfully inserted into Moodle<br>";

// ✅ Step 6: Redirect Button to Moodle
$lms_url = "http://54.157.251.46/lms/local/autologin/index.php?token=$token";
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Go to LMS</title>
    <style>
        body { font-family: Arial, sans-serif; padding: 30px; text-align: center; }
        a.button {
            background-color: #0073aa;
            color: white;
            padding: 12px 24px;
            font-size: 16px;
            text-decoration: none;
            border-radius: 6px;
            margin-top: 20px;
            display: inline-block;
        }
    </style>
</head>
<body>
    <h2>Welcome, <?php echo htmlspecialchars($fetch1['Employee_Full_Name']); ?></h2>
    <p>You're authenticated. Click below to enter the Learning Management System.</p>
    <a href="<?php echo $lms_url; ?>" class="button" target="_blank">Go to LMS Now</a>
</body>
</html>
