<?php
ini_set('display_errors', 1);
// this file is used to create all other users except superadmin
require_once '../resources/base_path_include.php';

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

//valdation file
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_resources . 'lib/curl_external/company/curl_find_workspace.php';

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

checkIfNoPhpContentsReceive();

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

validateApiSignature($postdata['api_signature']);

$jwttoken = $postdata['jwt_token'];

$jwt_validate = authenticate_jwt($jwttoken);
//then workspace_id is iin decodede data of jwt use from there
$userid = $jwt_validate->data->id;
$workspace_id = $jwt_validate->data->workspace_id;
$created_by = $jwt_validate->data->role;

if (
    !isset($postdata['name']) or !checkIfIssetAndNotEmpty($postdata['name']) or !isset($postdata['role']) or  !checkIfIssetAndNotEmpty($postdata['role']) or
    !isset($postdata['dob']) or
    !checkIfIssetAndNotEmpty($postdata['dob']) or !isset($postdata['gender']) or  !checkIfIssetAndNotEmpty($postdata['gender']) or
    !isset($postdata['username']) or !checkIfIssetAndNotEmpty($postdata['username']) or !isset($postdata['email']) or !checkIfIssetAndNotEmpty($postdata['email']) or
    !isset($postdata['mobile']) or !checkIfIssetAndNotEmpty($postdata['mobile'])
) {
    errorreturn("All * fields are required.");
}

if ($postdata['function_type'] == "create_user") {

    $institution_id = (isset($postdata['institution_id']) and !empty($postdata['institution_id'])) ? trim($postdata['institution_id']) : null;
    $name = ucwords(strtolower(trim($postdata['name']))); // use trim and ucwords here
    $dob = trim($postdata['dob']);
    $gender = trim($postdata['gender']);
    $username = trim($postdata['username']);
    $email = trim($postdata['email']);
    $mobile = trim($postdata['mobile']);
    $designation = (isset($postdata['designation']) and !empty($postdata['designation'])) ? trim($postdata['designation']) : null;
    $role = trim($postdata['role']); // should be admin or null for others 


    if ($role === 'admin' && $created_by !== 'superadmin') {
        errorreturn('Access denied. Only SuperAdmin can create Admin users.');
    }
    
    if ($role === 'subadmin' && !in_array($created_by, ['superadmin', 'admin'])) {
        errorreturn('Access denied. Only Admin/SuperAdmin can create SubAdmin users.');
    }

    // if usser added is teacher or coordinator or cashier
    // allowed roples should also have principal
    // $allowed_roles = array();
    $allowed_roles = array(
        'principal' => array('superadmin', 'admin'),
        'subadmin' => array('superadmin', 'admin'),
        'coordinator' => array('superadmin', 'admin', 'principal'),
        'teacher' => array('superadmin', 'admin', 'principal', 'coordinator'),
        'student' => array('superadmin', 'admin', 'principal', 'coordinator', 'teacher'),
        'cashier' => array('superadmin', 'admin', 'principal')
    );

    // die();
    if (!in_array($created_by, $allowed_roles[$role])) {
        errorreturn('Access denied.');
    }

    if ($institution_id !=  null) {
        $res = $conn_rjllearning->prepare("SELECT institution_code FROM institutions WHERE id = ?  ");
        $res->execute(array($institution_id));
        $result1 = $res->fetchAll();
        if (count($result1) != 1) {

            errorreturn("Institution not found.");
        }
    }

    // {'principal':['superadmin','admin']}
    // $allowed_roles = ['superadmin','admin','principal'];


    // array_push($allowed_roles, 'principal');


    // if(!in_array($role, $allowed_roles)) {

    //      errorreturn('Access denied.');
    // }

    // if ($role == 'superadmin' or $role == 'admin') {

    //     $branch_id = null;
    // } else {
    //     //$branch_id = (isset($branch_id) and !empty($branch_id)) ? trim($branch_id) : null; // fetching this from jwt
    //     $branch_id = $branch_id;
    // }

    //validation for name, email, dob, gender, mobile
    {
        // validation for character only name be added here

        //should only allow alphabets
        if (!checkOnlyCharacters($name)) { // 6 digit only
            //eg House Name, Street Name
            errorreturn('Name must only contain letters!"');
        }

        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            errorreturn('Enter valid Email Id');
        }

        if (strlen($mobile) != 13 or !is_numeric($mobile) or $mobile <= 0) {
            errorreturn('Enter valid 12 digit mobile number');
        }

        if ($gender != 'M' && $gender != 'F') {
            errorreturn('Invalid gender details');
        }

        $date_now = date("Y-m-d");
        if (!CheckDob($dob) or $dob >= $date_now) {
            errorreturn('Invalid DOB formats');
        }

        // Use preg_match to validate against the pattern
        if (!CheckUsername($username)) {
            errorreturn('Username must be alphanumeric, underscore (_) or at symbol (@)');
        }

        // validate if username is available
        if (!strlen($username) == 5) {
            // valid username, alphanumeric & longer than or equals 5 chars
            errorreturn('Invalid username details');
        }


        $check_availability = checkUsernameAvailabilty($conn_rjllearning, $username);
        if (!$check_availability) {
            errorreturn('Username already exists. Please try another username.');
        }

        // validate from users if existing super admins have either the same email or mobile, incase yes stop from proceeding
        $res = $conn_rjllearning->prepare("SELECT email,role,mobile FROM users WHERE institution_id = ? and  (email= ? or mobile = ?)");
        $res->execute(array($institution_id, $email, $mobile));
        $result1 = $res->fetchAll();
        if (count($result1) >= 1) {
            errorreturn("Email or Mobile already exists.");
        }
    }

    try {
        // Generating Password
        $chars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789!@#$%&*_";
        $password = substr(str_shuffle($chars), 0, 8);

        $sql = "INSERT INTO users(workspace_id,institution_id,name,dob,gender,username,email,mobile,role,password,date_time_created,designation,status)
                                   VALUES(?,?,?,?,?,?,?,?,?,?,?, ?,?)";
        $stmt =  $conn_rjllearning->prepare($sql);

        $stmt->execute(array($workspace_id, $institution_id, $name, $dob, $gender, $username, $email, $mobile, $role, $password, time(), $designation, '1'));

        require_once $GLOBALS['base_path_to_learning_resources'] . 'lib/mail_system/mail_Template1.php';
        $subject = 'Welcome to ' . $web_app_title;
        $message = 'Welcome to ';

        $message = "<h1>Welcome To <span class='web_app_title'>$web_app_title</span></h1>
    <p>Thank you for creating a user account on $web_app_title. You can now sign in at $web_app_front_end_website or <a href='$web_app_front_end_website'>Click Here</a>. </p>
    <p>
        Username : <b>$email</b><br>
        Password : <b>$password</b>
    </p>";

        sendMailTemplate1($conn_rjllearning, 'Rejoice Learning <no-reply@rejoicelearning.in>', $email, $subject, $message, $workspace_id);
        successreturn("User created successfully. Kindly check your registered email id for your login credentials.");
    } catch (Exception $e) {
        echo "Error : " . $e->getMessage();
    }
}
