<?php
ini_set('display_errors', 1);

require_once '../../resources/base_path_include.php';
require_once $base_path_to_learning . "vendor/autoload.php";
// echo "hello";
// die();
require_once $base_path_to_learning_resources  . "includes/connect.php";
require_once $base_path_to_learning_resources . 'lib/function.php';
require_once $base_path_to_learning_resources . 'lib/validate_api_signature.php';
require_once $base_path_to_learning_resources . 'lib/validate_function.php';
require_once $base_path_to_learning . '/user_management/check_username_availability.php';
require_once $base_path_to_learning . 'user_management/authenticate.php';
require_once $base_path_to_learning_resources . 'lib/cron_jobs/sms_function/sms_function.php';

require_once $base_path_to_learning_resources . 'lib/bucket_functions/bucket_functions.php';
require_once $base_path_to_learning_resources . 'includes/aws_bucket_config.php';
require_once $base_path_to_learning . 'functions/common_functions.php';
require_once $base_path_to_learning_resources . 'includes/specific_db_config.php';
require_once $base_path_to_learning_resources . 'jwt/jwt_config.php';
require_once $base_path_to_learning . 'students_api/student_api_function/common_api_function.php';
require_once $base_path_to_learning . 'principal_api/principal_function/principal_function.php';

//fcm notification
require_once $base_path_to_learning . 'user_management/functions/fcm_token_function.php';

use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;

$postdata = json_decode(file_get_contents("php://input"), true);

checkIfNoPhpContentsReceive();

if (
    !isset($postdata['api_signature']) || !checkIfIssetAndNotEmpty($postdata['api_signature']) ||
    !isset($postdata['function_type']) || !checkIfIssetAndNotEmpty($postdata['function_type'])
) {
    errorreturn("All * fields are required.");
}


if ($postdata['function_type'] == "forgot_password") {
    $using_username = isset($postdata['username']) && checkIfIssetAndNotEmpty($postdata['username']);
    $using_admission_number = !$using_username &&
        isset($postdata['admission_number']) && checkIfIssetAndNotEmpty($postdata['admission_number']) &&
        isset($postdata['institution_id']) && checkIfIssetAndNotEmpty($postdata['institution_id']) &&
        isset($postdata['branch_id']) && checkIfIssetAndNotEmpty($postdata['branch_id']);

    if ($using_username) {
        $flow_type = 'username';
    } elseif ($using_admission_number) {
        $flow_type = 'admission_number';
    } else {
        errorreturn("Either username or (admission_number, institution_id, and branch_id) are required.");
    }
} else {
    $flow_type = (isset($postdata['flow_type']) && checkIfIssetAndNotEmpty($postdata['flow_type']))
        ? $postdata['flow_type']
        : 'username';
}


function generateOTP($length = 6)
{
    $otp = '';
    for ($i = 0; $i < $length; $i++) {
        $otp .= mt_rand(0, 9);
    }
    return $otp;
}

function generateRandomToken($length = 32)
{
    return bin2hex(random_bytes($length));
}

function encryptData($data, $key = 'XyR5yGWg6Pq')
{
    $iv = random_bytes(16);
    $encryptedData = openssl_encrypt($data, 'AES-256-CBC', $key, 0, $iv);
    return base64_encode($iv . $encryptedData);
}

function decryptData($encodedData, $key = 'XyR5yGWg6Pq')
{
    $decodedData = base64_decode($encodedData);
    $iv = substr($decodedData, 0, 16);
    $encryptedData = substr($decodedData, 16);
    return openssl_decrypt($encryptedData, 'AES-256-CBC', $key, 0, $iv);
}

// Common variables
$key = 'XyR5yGWg6Pq';
$userToken = generateRandomToken();
$otp_type = 'Reset Password';
$encodedData = '';
$username = '';
$workspace_id = '';
$institution_id = '';
$branch_id = '';
$user_id = '';
$name = '';
$role = '';
$email = '';
$mobile = '';

if ($postdata['function_type'] == "forgot_password") {
    if ($flow_type == 'username') {

        $username = $postdata['username'];
        $encodedData = encryptData($username);

        $res = $conn_rjllearning->prepare("SELECT name,username,email,workspace_id, role,mobile,institution_id,branch_id,id FROM users WHERE username = ? and can_activate = 1 and status = 1");
        $res->execute(array($username));
        $result1 = $res->fetchAll();

        if (count($result1) != 1) {
            errorreturn("User Not Found.");
        }

        $workspace_id = $result1[0]['workspace_id'];
        $user_id = $result1[0]['id'];
        $name = $result1[0]['name'];
        $role = $result1[0]['role'];
        $email = $result1[0]['email'];
        $mobile = $result1[0]['mobile'];
        $institution_id = $result1[0]['institution_id'];
        $branch_id = $result1[0]['branch_id'];

        $mobile = preg_replace('/^\+91/', '91', $mobile);

        if (in_array($role, ['principal', 'teacher', 'student'])) {
            $specific_db_name = validateUserAccess($conn_rjllearning, $user_id, $role, $workspace_id, ["principal", "teacher", "student"], null);
            if (!$specific_db_name) {
                errorreturn('Access denied.');
            } else {
                $conn_rjllearning_specific = dynamicDbConnection($specific_db_name);
            }
        }

        if (in_array($role, ['superadmin', 'admin'])) {
            errorreturn("Access Denied");
        }
    } else {

        $admission_number = $postdata['admission_number'];
        $institution_id = $postdata['institution_id'];
        $branch_id = $postdata['branch_id'];

        $query = "SELECT workspace_id FROM institutions WHERE id = ?";
        $stmt = $conn_rjllearning->prepare($query);
        $stmt->execute([$institution_id]);
        $institution = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$institution) {
            errorreturn('Institution not found.');
        }

        $workspace_id = $institution['workspace_id'];
        $conn_rjllearning_specific = getdbconnection($conn_rjllearning, $workspace_id);
        if (!$conn_rjllearning_specific) {
            errorreturn('Could not establish database connection.');
        }

        $res = $conn_rjllearning_specific->prepare("SELECT username, name, email, mobile, institution_id FROM students 
                                         WHERE admission_number = ? AND branch_id = ? AND can_activate = 1 AND status = 1");
        $res->execute(array($admission_number, $branch_id));
        $studentData = $res->fetch(PDO::FETCH_ASSOC);

        if (!$studentData) {
            errorreturn("Student Not Found with this admission number and branch.");
        }

        $username = $studentData['username'];
        $encodedData = encryptData($username);
        $name = $studentData['name'];
        $email = $studentData['email'];
        $mobile = $studentData['mobile'];
        $institution_id = $studentData['institution_id'];

        $res = $conn_rjllearning->prepare("SELECT workspace_id, role, id FROM users 
                                         WHERE username = ? AND can_activate = 1 AND status = 1");
        $res->execute(array($username));
        $userData = $res->fetch(PDO::FETCH_ASSOC);

        if (!$userData) {
            errorreturn("User account not found or not active.");
        }

        $role = $userData['role'];
        $user_id = $userData['id'];

        if ($role != 'student') {
            errorreturn("Access Denied.");
        }

        $mobile = preg_replace('/^\+91/', '91', $mobile);
    }

    $otp = generateOTP();

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

    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'] ?? '';

    $default_domain = 'rejoicelearning.in';

    if (!empty($white_label_url)) {
        $domain = str_replace(['http://', 'https://', 'www.'], '', $white_label_url);
        $domain_parts = explode('/', $domain);
        $base_domain = $domain_parts[0];
        $url = 'https://faculty.' . $base_domain;
    } else {
        $url = 'https://faculty.' . $default_domain;
    }

    $app_name = !empty($white_label_app_name) ? $white_label_app_name : $web_app_title;
    $from_email = !empty($white_label_email) ? $white_label_email : 'Rejoice Learning <no-reply@rejoicelearning.in>';

    $subject = 'Password Reset OTP -' .  $app_name;

    $message = "<h1>Password Reset OTP - <span class='web_app_title'>$app_name</span></h1>
        <p>Your One Time Password for resetting your password at $app_name is: <strong>$otp</strong></p>
        <p>Please use this OTP when prompted for the Password while resetting your password.</p>
        <p>Please note that this Password is valid for 3 minutes. Do not share this OTP with anyone for security reasons.</p>";

    $mobile_message = "Your OTP for Rejoice Learning password reset is " . $otp . ". Do not share it.";

    sendMailTemplate1($conn_rjllearning, $from_email, $email, $subject, $message, $workspace_id, $institution_id, $branch_id, $user_id, null, 'real_time');
    sendSmsAndUpdateCounter($workspace_id, $institution_id, $branch_id, $mobile, $mobile_message, $conn_rjllearning, $white_label_message_header,'forgotpassword');

    successreturn(array(
        "success_msg" => "Kindly check your registered email id for reset password.",
        "username" => $encodedData,
        'user_token' => $userToken
    ));
} else if ($postdata['function_type'] == "verify_forgot_password") {
    // if (!isset($postdata['otp']) || !isset($postdata['user_token']) || !isset($postdata['username'])) {
    //     errorreturn("OTP, user token and username are required.");
    // }
    
    if (!isset($postdata['otp']) || !isset($postdata['user_token'])) {
        errorreturn("OTP, user token are required.");
    }

    $otp = $postdata['otp'];
    $user_token = $postdata['user_token'];
    // $encodedData = $postdata['username'];
    
    if ($flow_type == 'username') {
        if (!isset($postdata['username'])) {
            errorreturn("Username is required.");
        }
            $encodedData = $postdata['username'];
    } else {
        if (!isset($postdata['admission_number'])) {
            errorreturn("Admission number is required.");
        }
            $encodedData = $postdata['admission_number'];
    }

    // Decrypt the username
    $decryptedIdentifier = decryptData($encodedData);

    if ($flow_type == 'username') {
        // For username flow, the decrypted identifier is the username
        $username = $decryptedIdentifier;

       
    } else {
        // For admission number flow, we need to get the username from students table
        $username = $decryptedIdentifier;
    }
    
    // Verify user exists
    $res = $conn_rjllearning->prepare("SELECT id FROM users WHERE username = ? and can_activate = 1 and status = 1");
    $res->execute(array($username));
    if (count($res->fetchAll()) != 1) {
        errorreturn("User Not Found.");
    }

    $res = $conn_rjllearning->prepare("SELECT * FROM otp_store WHERE username= ? and otp = ? and user_token = ? and status = ?");
    $res->execute(array($username, $otp, $user_token, 0));
    $result1 = $res->fetchAll();
    if (count($result1) != 1) {
        errorreturn("OTP Not Found. $username");
    }

    $newuserToken = generateRandomToken();
    $sql = "UPDATE otp_store SET status=?, user_token = ? WHERE username=? and otp=?";
    $conn_rjllearning->prepare($sql)->execute(array(1, $newuserToken, $username, $otp));

    successreturn(array(
        "success_msg" => "Kindly reset your password",
        "username" => $encodedData,
        'user_token' => $newuserToken
    ));
} else if ($postdata['function_type'] == "reset_password") {
    if (
        !isset($postdata['otp']) || !isset($postdata['user_token']) ||
        !isset($postdata['new_password']) || !isset($postdata['confirm_password'])
    ) {
        errorreturn("All fields are required.");
    }

    $otp = $postdata['otp'];
    $user_token = $postdata['user_token'];
    // $encodedData = $postdata['username'];
    $new_password = $postdata['new_password'];
    $confirm_password = $postdata['confirm_password'];
    
    if ($flow_type == 'username') {
        if (!isset($postdata['username'])) {
            errorreturn("Username is required.");
        }
            $encodedData = $postdata['username'];
    } else {
        if (!isset($postdata['admission_number'])) {
            errorreturn("Admission number is required.");
        }
            $encodedData = $postdata['admission_number'];
    }

    if ($new_password !== $confirm_password) {
        errorreturn("Passwords do not match.");
    }

    $decryptedIdentifier = decryptData($encodedData);

    if ($flow_type == 'username') {
        $username = $decryptedIdentifier;
    } else {
        $username = $decryptedIdentifier;
    }

    $res = $conn_rjllearning->prepare("SELECT * FROM otp_store WHERE username= ? and otp = ? and user_token = ? and status = ?");
    $res->execute(array($username, $otp, $user_token, 1));
    $result1 = $res->fetchAll();
    if (count($result1) != 1) {
        errorreturn("Incorrect user details.");
    }

    $hashedPassword = password_hash($new_password, PASSWORD_DEFAULT);
    $sql = "UPDATE users SET password=? WHERE username=?";
    $conn_rjllearning->prepare($sql)->execute(array($hashedPassword, $username));
    successreturn("Password successfully updated.");
} else {
    errorreturn("Invalid function type.");
}
