<?php
function generate_OTP($length = 6)
{
    $otp = '';
    for ($i = 0; $i < $length; $i++) {
        $otp .= mt_rand(0, 9); // Generates a random digit between 0 and 9
    }
    return $otp;
}

function generate_Random_Token($length = 32)
{
    // Generate a cryptographically secure random string
    $token = bin2hex(random_bytes($length));
    return $token;
}

function generateGatePassOTP($conn_rjllearning, $conn_rjllearning_specific, $institution_id, $branch_id, $user_id, $type, $username, $workspace_id, $web_app_title)
{
    if ($type == 'student') {
        $sql = "SELECT name, email FROM students WHERE id = ? AND institution_id = ? AND branch_id = ? AND can_activate = 1";
    } elseif ($type == 'faculty') {
        $sql = "SELECT name, email FROM faculty_info WHERE id = ? AND institution_id = ? AND branch_id = ?";
    } else {
        errorreturn("Invalid user type.");
    }

    // Execute the query
    $res_type = $conn_rjllearning_specific->prepare($sql);
    $res_type->execute([$user_id, $institution_id, $branch_id]);
    $result1 = $res_type->fetchAll();

    if (count($result1) != 1) {
        errorreturn("User not available in the specified branch of the institution.");
    } else {
        $name = $result1[0]['name'];
        $email = $result1[0]['email'];

        // Retrieve otp_settings from institution_global_settings table
        $sql = "SELECT otp_setting FROM institution_global_settings WHERE institution_id = ? AND branch_id = ?";
        $res_otp = $conn_rjllearning_specific->prepare($sql);
        $res_otp->execute([$institution_id, $branch_id]);
        $result2 = $res_otp->fetch(PDO::FETCH_ASSOC);

        // Check if the result is false
        if (!$result2) {
            errorreturn("OTP settings not found for this institution or branch.");
        }

        $otp_settings_array = json_decode($result2['otp_setting'], true);

        if (isset($otp_settings_array['gate_pass_otp']) && $otp_settings_array['gate_pass_otp'] == 1) {

            $key = 'XyR5yGWg6Pq';
            $iv = random_bytes(16);

            $otp = generate_OTP();
            $userToken = generate_Random_Token();
            $otp_type = 'gate_pass_otp';

            $encryptedUsername = openssl_encrypt($username, 'AES-256-CBC', $key, 0, $iv);
            $encodedData = base64_encode($iv . $encryptedUsername);

            // Store the OTP and token in otp_store table
            $sql = "INSERT INTO otp_store(username, otp, user_token, otp_type, timestamp, status) VALUES (?, ?, ?, ?, ?, ?)";
            $stmt = $conn_rjllearning->prepare($sql);
            $stmt->execute(array($username, $otp, $userToken, $otp_type, time(), 0));

            // Send OTP via email
            require_once $GLOBALS['base_path_to_learning_resources'] . 'lib/mail_system/mail_Template1.php';
            
            $institution_info = getInstitution($conn_rjllearning, $institution_id);

            $white_label_url = $institution_info['white_label_url'] ?? '';
            $white_label_email = $institution_info['white_label_email'] ?? '';
            $white_label_message_header = $institution_info['white_label_message_header'] ?? '';
            $white_label_app_name = $institution_info['white_label_app_name'] ?? '';
    
            // Use white label values if provided, otherwise fallback to default
            $app_name = !empty($white_label_app_name) ? $white_label_app_name : $web_app_title;
            //$app_url = $url;
            $from_email = !empty($white_label_email) ? $white_label_email : 'no-reply@rejoicelearning.in';
            $subject = 'Gate Pass OTP - ' . $app_name;
            $message = "<h1>Gate Pass OTP - <span class='web_app_title'>$app_name</span></h1>
                        <p>Dear $name,</p>
                        <p>Your One Time Password (OTP) for generating your gate pass is: <strong>$otp</strong></p>
                        <p>This OTP is valid for 3 minutes. Please do not share this OTP with anyone for security reasons.</p>";

            sendMailTemplate1($conn_rjllearning, $from_email, $email, $subject, $message, $workspace_id);

            return array(
                "success_msg" => "Kindly check your registered email for the gate pass OTP.",
                "username" => $username,
                'user_token' => $userToken,
                // 'key' => base64_encode($key), // Encode key for safe transmission
                // 'iv' => base64_encode($iv) // Encode IV for safe transmission            
            );
        } else {
            errorreturn("Gate OTP cannot be sent.");
        }
    }
}

function decryptToken($encrypted_token, $key, $iv)
{
    return openssl_decrypt($encrypted_token, 'AES-256-CBC', $key, 0, $iv);
}
