<?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 ,mobile , admission_number FROM students WHERE id = ? AND institution_id = ? AND branch_id = ? AND can_activate = 1";
    } elseif ($type == 'faculty') {
        $sql = "SELECT name, email,mobile 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'];
        $mobile = str_replace("+91", "", $result1[0]['mobile']);
        if ($type == 'student') {
        $username_sms = $result1[0]['admission_number'];
        $sms_module ='gatepass';
        }else{
        $username_sms = $result1[0]['email'];
        $sms_module = 'facultygatepass';
        }
        // 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'] ?? '';
    
            // // Set default domain
            // $default_domain = 'rejoicelearning.in';
    
            // // Build faculty subdomain-based URL dynamically
            // if (!empty($white_label_url)) {
            //     $domain = str_replace(['http://', 'https://', 'www.'], '', $white_label_url);
            //     $domain_parts = explode('/', $domain); // remove any path
            //     $base_domain = $domain_parts[0];
    
            //     $url = 'https://faculty.' . $base_domain;
            // } else {
            //     $url = 'https://faculty.' . $default_domain;
            // }
    
            // 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';
                
            if($sms_module == 'facultygatepass') {
                $mobile_message = "Your OTP for gate access is $otp and is valid for 10 minutes. Kindly do not share it.Regards, Rejoice Learning";
            } else {
                $mobile_message = "Your OTP for Gatepass generation for Admission No. $username_sms is $otp. Do not share OTP. Regards, Rejoice Learning";
            }

            $sms_status = sendSmsAndUpdateCounter($workspace_id, $institution_id, $branch_id, $mobile, $mobile_message, $conn_rjllearning, null,$sms_module);
            
            $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>";

            $mail_status = sendMailTemplate1($conn_rjllearning,$from_email, $email, $subject, $message, $workspace_id, $institution_id, $branch_id, null, null, 'real_time');
            
                        
             
            return array(
                "success_msg" => "Kindly check your registered email and sms 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 generateGatePassOTP($conn_rjllearning, $conn_rjllearning_specific, $institution_id, $branch_id, $user_id, $type, $username, $workspace_id, $web_app_title, $student_id = null, $class_id = null, $section_id = null)
// {
//     if ($type == 'student') {
//         $sql = "SELECT name, email, mobile, admission_number 
//                 FROM students 
//                 WHERE id = ? AND institution_id = ? AND branch_id = ? AND can_activate = 1";
//     } elseif ($type == 'faculty') {
//         $sql = "SELECT name, email, mobile 
//                 FROM faculty_info 
//                 WHERE id = ? AND institution_id = ? AND branch_id = ?";
//     } else {
//         errorreturn("Invalid user type.");
//     }

//     $res_type = $conn_rjllearning_specific->prepare($sql);
//     $res_type->execute([$user_id, $institution_id, $branch_id]);
//     $result1 = $res_type->fetch(PDO::FETCH_ASSOC);

//     if (!$result1) {
//         errorreturn("User not available in the specified branch of the institution.");
//     }

//     $name = $result1['name'];
//     $email = $result1['email'];
//     $mobile = str_replace("+91", "", $result1['mobile']);

//     if ($type == 'student') {
//         $username_sms = $result1['admission_number'];
//         $sms_module = 'gatepass';
//         $gatepass_name =$name;
//     } else {
//         $username_sms = $result1['email'];
//         $sms_module = 'facultygatepass';
//         $gatepass_name = mb_strimwidth($name, 0, 20, "...");
//     }

//     require_once $GLOBALS['base_path_to_learning_resources'] . 'lib/mail_system/mail_Template1.php';

//     // Get OTP settings
//     $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);

//     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) {
//         errorreturn("Gate OTP cannot be sent.");
//     }

//     // Generate OTP and store
//     $otp = generate_OTP();
//     $userToken = generate_Random_Token();
//     $otp_type = 'gate_pass_otp';

//     $stmt = $conn_rjllearning->prepare(
//         "INSERT INTO otp_store (username, otp, user_token, otp_type, timestamp, status) 
//          VALUES (?, ?, ?, ?, ?, ?)"
//     );
//     $stmt->execute([$username, $otp, $userToken, $otp_type, time(), 0]);

//     // Prepare white label info
//     $institution_info = getInstitution($conn_rjllearning, $institution_id);
//     $app_name = !empty($institution_info['white_label_app_name']) ? $institution_info['white_label_app_name'] : $web_app_title;
//     $from_email = !empty($institution_info['white_label_email']) ? $institution_info['white_label_email'] : 'no-reply@rejoicelearning.in';

//     // Send SMS
//     if ($sms_module == 'facultygatepass') {
//         $mobile_message = "Your OTP for gate access is $otp and is valid for 3 minutes. Kindly do not share it. Regards, Rejoice Learning";
//     } else {
//         $mobile_message = "Your OTP for Gatepass generation for Admission No. $username_sms is $otp. Valid for 3 minutes. Do not share. Regards, Rejoice Learning";
//     }

//     sendSmsAndUpdateCounter($workspace_id, $institution_id, $branch_id, $mobile, $mobile_message, $conn_rjllearning, null, $sms_module);
    
      
//       $sms_message = "{$gate_name} Pass Alert: {$student_name} (Adm No. {$admission_no}) has requested a gate pass. Kindly review in the app. Regards, Rejoice Learning.\n\n{$gate_name} Faculty {$faculty_name_short}";

//         sendGatePassAlertToPrincipal(
//             $conn_rjllearning,
//             $institution_id,
//             $branch_id,
//             $workspace_id,
//             $sms_message
//         );

//     // Send Email
//     $subject = 'Gate Pass OTP - ' . $app_name;
//     $email_message = "<h1>Gate Pass OTP - $app_name</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 it with anyone.</p>";

//     sendMailTemplate1($conn_rjllearning, $from_email, $email, $subject, $email_message, $workspace_id, $institution_id, $branch_id, null, null, 'real_time');
//     require_once $GLOBALS['base_path_to_learning_resources'] . 'lib/cron_jobs/function/function.php'; 
//     require_once $GLOBALS['base_path_to_learning_resources'] . 'lib/cron_jobs/firebase_notification/fcm_notifications_function.php';
            
//     // Notifications
//     if ($type == 'student' && $student_id && $class_id && $section_id) {
//         $notification_count = sendGatePassStudentRequestNotification(
//             $conn_rjllearning,
//             $institution_id,
//             $branch_id,
//             $student_id,
//             $class_id,
//             $section_id
//         );
//         updateMailSmsCount($workspace_id, $institution_id, $branch_id, null, null, $notification_count, 'notification', $conn_rjllearning);
//     }

//     if ($type == 'faculty') {
//         $notifTitle = "Faculty Gate Pass Request";
//         $notifBody  = "Faculty member $name has requested a gate pass.";
//         $redirectType = "gatepass";
//         $redirectId   = $user_id;

//         $notification_count = sendNotificationToPrincipal(
//             $conn_rjllearning,
//             $institution_id,
//             $branch_id,
//             $notifTitle,
//             $notifBody,
//             $redirectType,
//             $redirectId
//         );

//         updateMailSmsCount($workspace_id, $institution_id, $branch_id, null, null, $notification_count, 'notification', $conn_rjllearning);
//     }

//     return [
//         "success_msg" => "Kindly check your registered email and SMS for the gate pass OTP.",
//         "username"    => $username,
//         "user_token"  => $userToken
//     ];
// }

// 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, mobile, admission_number , id , class_id , section_id 
//                 FROM students 
//                 WHERE id = ? AND institution_id = ? AND branch_id = ? AND can_activate = 1";
//     } elseif ($type == 'faculty') {
//         $sql = "SELECT name, email, mobile, dob
//                 FROM faculty_info 
//                 WHERE id = ? AND institution_id = ? AND branch_id = ?";
//     } else {
//         errorreturn("Invalid user type.");
//     }

//     $res_type = $conn_rjllearning_specific->prepare($sql);
//     $res_type->execute([$user_id, $institution_id, $branch_id]);
//     $result1 = $res_type->fetch(PDO::FETCH_ASSOC);

//     if (!$result1) {
//         errorreturn("User not available in the specified branch of the institution.");
//     }

//     $name   = $result1['name'];
//     $email  = $result1['email'];
//     $mobile = preg_replace('/^\+91/', '91', $result1['mobile']);

//     if ($type == 'student') {
//         $username_sms  = $result1['admission_number'];
//         $student_id  = $result1['id'];
//         $class_id  = $result1['class_id'];
//         $section_id  = $result1['section_id'];
//         $sms_module    = 'gatepass';
//         $gatepass_name = mb_strimwidth($name, 0, 20, "...");;
//         $student_name  = $name;
//         $admission_no  = $result1['admission_number'];
//         $var2          = 'Adm No. ' . $admission_no;  // ✅ FIXED CONCAT
//     } else {
//         $username_sms  = $result1['email'];
//         $sms_module    = 'facultygatepass';
//         $gatepass_name = mb_strimwidth($name, 0, 20, "...");
//         $student_name  = '';
//         $admission_no  = '';
//         $faculty_dob   = $result1['dob'];
//         $var2          = $faculty_dob;
//     }

//     require_once $GLOBALS['base_path_to_learning_resources'] . 'lib/mail_system/mail_Template1.php';

//     // OTP Settings
//     $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);

//     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) {
//         errorreturn("Gate OTP cannot be sent.");
//     }

//     // Generate OTP + Store
//     $otp       = generate_OTP();
//     $userToken = generate_Random_Token();
//     $otp_type  = 'gate_pass_otp';

//     $stmt = $conn_rjllearning->prepare(
//         "INSERT INTO otp_store (username, otp, user_token, otp_type, timestamp, status) 
//          VALUES (?, ?, ?, ?, ?, ?)"
//     );
//     $stmt->execute([$username, $otp, $userToken, $otp_type, time(), 0]);

//     // Institution info
//     $institution_info = getInstitution($conn_rjllearning, $institution_id);
//     $app_name   = !empty($institution_info['white_label_app_name']) ? $institution_info['white_label_app_name'] : $web_app_title;
//     $from_email = !empty($institution_info['white_label_email']) ? $institution_info['white_label_email'] : 'no-reply@rejoicelearning.in';

//     // SMS to user
//     if ($sms_module == 'facultygatepass') {
//         $mobile_message = "Your OTP for gate access is $otp and is valid for 10 minutes. Kindly do not share it. Regards, Rejoice Learning";
//     } else {
//         $mobile_message = "Your OTP for Gatepass generation for Admission No. $username_sms is $otp. Do not share OTP. Regards, Rejoice Learning";
//     }
    

//   // 1
//   sendSmsAndUpdateCounter(
//         $workspace_id,
//         $institution_id,
//         $branch_id,
//         $mobile,
//         $mobile_message,
//         $conn_rjllearning,
//         null,
//         $sms_module
//     );

//     // SMS Alert to Principal
//     if ($type == 'student') {
//         $gate_name = "Gate";
//         $principal_sms_message = "{$gate_name} Pass Alert: {$gatepass_name} {$var2} has requested a gate pass. Kindly review in the app. Regards, Rejoice Learning.";
//     } else {
//         $gate_name = "Gate";
//         $principal_sms_message = "{$gate_name} Pass Alert: {$gatepass_name} {$var2} has requested a gate pass. Kindly review in the app. Regards, Rejoice Learning.";
//     }
    
//   // 2
//     sendGatePassSmsAlertToPrincipal(
//         $conn_rjllearning,
//         $conn_rjllearning_specific,
//         $institution_id,
//         $branch_id,
//         $workspace_id,
//         $principal_sms_message
//     );

//     // Email to User
//     $subject = 'Gate Pass OTP - ' . $app_name;
//     $email_message = "<h1>Gate Pass OTP - $app_name</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 it with anyone.</p>";
//  // 3
 
//     sendMailTemplate1(
//         $conn_rjllearning,
//         $from_email,
//         $email,
//         $subject,
//         $email_message,
//         $workspace_id,
//         $institution_id,
//         $branch_id,
//         null,
//         null,
//         'real_time'
//     );
    


//     // Notifications
//     require_once $GLOBALS['base_path_to_learning_resources'] . 'lib/cron_jobs/function/function.php'; 
//     require_once $GLOBALS['base_path_to_learning_resources'] . 'lib/cron_jobs/firebase_notification/fcm_notifications_function.php';
//     require_once $GLOBALS['base_path_to_learning_resources'] . 'lib/cron_jobs/firebase_notification/faculty_and_principal_notification_function.php';
    
//     // 4
    
//     if ($type == 'student' && $student_id && $class_id && $section_id) {
//         $notification_count = sendGatePassStudentRequestNotification(
//             $conn_rjllearning,
//             $conn_rjllearning_specific,
//             $institution_id,
//             $branch_id,
//             $student_id,
//             $class_id,
//             $section_id
//         );

//         updateMailSmsCount(
//             $workspace_id,
//             $institution_id,
//             $branch_id,
//             null,
//             null,
//             $notification_count,
//             'notification',
//             $conn_rjllearning
//         );
//     }
  
//   // 5
  
//     if ($type == 'faculty') {
//         $notifTitle   = "Faculty Gate Pass Request";
//         $notifBody    = "Faculty member $name has requested a gate pass.";
//         $redirectType = "gatepass";
//         $redirectId   = $user_id;

//         $notification_count = sendNotificationToPrincipal(
//             $conn_rjllearning,
//             $conn_rjllearning_specific,
//             $institution_id,
//             $branch_id,
//             $notifTitle,
//             $notifBody,
//             $redirectType,
//             $redirectId
//         );

//         updateMailSmsCount(
//             $workspace_id,
//             $institution_id,
//             $branch_id,
//             null,
//             null,
//             $notification_count,
//             'notification',
//             $conn_rjllearning
//         );
//     }

//     return [
//         "success_msg" => "Kindly check your registered email and SMS for the gate pass OTP.",
//         "username"    => $username,
//         "user_token"  => $userToken
//     ];
// }





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

function generate_inventorysale_otp($conn_rjllearning, $conn_rjllearning_specific, $institution_id, $branch_id, $otp_authorisation, $username, $workspace_id, $web_app_title, $first_party, $userid, $jwt_email)
{
    if ($otp_authorisation == 'student') {
        $sql = "SELECT name, email, admission_number ,mobile FROM students WHERE id = ? AND institution_id = ? AND branch_id = ? AND can_activate = 1";
        $res_type = $conn_rjllearning_specific->prepare($sql);
        $res_type->execute([$first_party, $institution_id, $branch_id]);
        $result1 = $res_type->fetchAll();

        if (count($result1) != 1) {
            errorreturn("User not available in the specified branch of the institution.");
        }

        $name = $result1[0]['name'];
        $email = $result1[0]['email'];
        $admission_number = $result1[0]['admission_number'];
        $mobile = $result1[0]['mobile'];  // Assuming no mobile for student, set blank or fetch if available

    } elseif ($otp_authorisation == 'self') {
        $sql = "SELECT name, email, mobile FROM faculty_info WHERE userid = ? AND institution_id = ? AND branch_id = ?";
        $res_type = $conn_rjllearning_specific->prepare($sql);
        $res_type->execute([$userid, $institution_id, $branch_id]);
        $resultself1 = $res_type->fetchAll();

        if (count($resultself1) != 1) {
            errorreturn("Faculty not available in the specified branch of the institution.");
        }

        $name = $resultself1[0]['name'];
        $email = $resultself1[0]['email'];
        $mobile = $resultself1[0]['mobile'];
        $admission_number = '';  // No admission number for faculty

    } else {
        errorreturn("Invalid user type.");
    }

    $item = 'item';

    // 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);

    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['inventory_sale_otp']) && in_array($otp_settings_array['inventory_sale_otp'], [1, 2, 3])) {
        $key = 'XyR5yGWg6Pq';
        $iv = random_bytes(16);

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

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

        // Store OTP 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([$username, $otp, $userToken, $otp_type, time(), 0]);

        $otp_method = $otp_settings_array['inventory_sale_otp'];

        if ($otp_method == 1 || $otp_method == 2) {
            require_once $GLOBALS['base_path_to_learning_resources'] . 'lib/mail_system/mail_Template1.php';
            $subject = 'Inventory Sale OTP - ' . $web_app_title;
            $message = "<h1>Inventory Sale OTP - <span class='web_app_title'>$web_app_title</span></h1>
            <p>Dear $name,</p>
            <p>You are attempting to complete an inventory sale. To proceed, please use the One-Time Password (OTP) below:</p>
            <p><strong>OTP: $otp</strong></p>
            <p>This OTP is valid for 3 minutes. Please do not share it with anyone to ensure the security of your transaction.</p>
            <p>If you did not request this OTP, please ignore this email or contact support immediately.</p>";

            sendMailTemplate1($conn_rjllearning, 'no-reply@rejoicelearning.in', $email, $subject, $message, $workspace_id, $institution_id, $branch_id, null, null, 'real_time');
        }

        if (($otp_method == 1 || $otp_method == 3) && !empty($mobile)) {
            $mobile_message = "$otp is your OTP for collecting the $item" . ($admission_number ? " for Admission No. $admission_number" : "") . ". Regards, Rejoice Learning";
            $sms_status = sendSmsAndUpdateCounter($workspace_id, $institution_id, $branch_id, $mobile, $mobile_message, $conn_rjllearning,null,'item_distribution');
        }

        return [
            "success_msg" => "Kindly check your registered email/SMS for the inventory sale OTP.",
            "username" => $username,
            'user_token' => $userToken,
        ];
    } else {
        errorreturn("Inventory sale OTP cannot be sent.");
    }
}

