<?php 
/**
 * Manage
 */
# for create new group layout
add_action('wp_ajax_proqyz-get-group-modal', 'proqyz_get_group_layout_callback');
function proqyz_get_group_layout_callback(){
    global $wpdb, $table_proqyz_groups;
    ob_start();
    ?>
        <form id="create-group-form" data-proqyz-form="create-group-form" style="display:contents;" >
            
            <div class="modal-header">
                <h5 style="flex: 1 1 auto;margin: 0;" class="modal-title">
                    Manage Group
                </h5>
            </div>

            <div class="modal-header">

                <div class="form-field" style="margin-bottom:10px;">
                    <input 
                        style="width:100%;" 
                        class="form-control" 
                        type="text" 
                        name="group-title" 
                        id="group-title" 
                        placeholder="Enter Group title"
                        required
                    >
                </div>

                <div class="form-group clearfix">
                    <div class="icheck-primary d-inline-flex">
                        <input type="radio" id="username-search" checked value="username" name="search-by" data-proqyz-search-for="groups">
                        <label for="username-search" style="font-weight:normal;">Username</label>
                    </div>
                    <div class="icheck-primary d-inline-flex">
                        <input type="radio" id="email-search" value="email" name="search-by" data-proqyz-search-for="groups">
                        <label for="email-search" style="font-weight:normal;">Email</label>
                    </div>
                    
                    <div class="icheck-primary d-inline-flex">
                        <input type="radio" id="id-search" value="user-id" name="search-by" data-proqyz-search-for="groups">
                        <label for="id-search" style="font-weight:normal;">User id</label>
                    </div>
                    
                    <div class="d-flex" id="search-text">

                    </div>
        
                </div>



            </div>

            <div class="modal-body" id="modal-body-groups">
            
            

                <div class="wrapper">
                    

                    <?php
                        global $wpdb;
                        $table_users = $wpdb->prefix."users";
                        $students_ids = array(); $students_details = array();
                        $teachers_ids = array(); $teachers_details = array();
                        $already_student_ids = array();

                        # get all groups students
                        $get_groups = $wpdb->get_results("SELECT * FROM {$table_proqyz_groups} WHERE `status` = 1");
                        foreach($get_groups as $group){
                            $group_student_ids = $group->student_ids;
                            $group_student_ids = stripslashes($group_student_ids);
                            $group_student_ids = str_replace('"',"",$group_student_ids);
                            $group_student_ids_arr = explode(",",$group_student_ids);
                            
                            foreach($group_student_ids_arr as $gid){
                                if(!in_array($gid,$already_student_ids)){
                                    array_push($already_student_ids,$gid);
                                }
                            }
                        }

                        

                        $query =  "SELECT * FROM `$table_users` WHERE 1 ORDER BY `display_name` ASC"; 
                        $all_users_query = $wpdb->get_results($query);
                        foreach($all_users_query as $user){
                            $usermeta = get_userdata($user->ID);
                            $user_roles = (array) $usermeta->roles;

                            if(!in_array('administrator',$user_roles) && !in_array('teacher',$user_roles)){
                                # check if this student is already part of any group
                                if(!in_array($user->ID,$already_student_ids)){
                                    
                                    if(!in_array($user->ID,$students_ids)){
                                        array_push($students_ids,$user->ID);
                                        array_push($students_details,array(
                                            "ID"            => $user->ID,
                                            "display_name"  => $user->display_name,
                                            "role"          => "student",
                                            "username"      => $user->user_login,
                                            "email"         => $user->user_email
                                        ));
                                    }
                                }
                            }else if(in_array('administrator',$user_roles) || in_array('teacher',$user_roles)){
                                if(!in_array($user->ID,$teachers_ids)){
                                    array_push($teachers_ids,$user->ID);
                                    array_push($teachers_details,array(
                                        "ID"            => $user->ID,
                                        "display_name"  => $user->display_name,
                                        "role"          => "teacher",
                                        "username"      => $user->user_login,
                                        "email"         => $user->user_email
                                    ));
                                }
                            }
                            
                        } 

                        $items = 20;
                        $current_page = 1;
                        $offset = ($current_page - 1) * $items;

                        # students only below
                        $total_records_found_students = count($students_ids); # TOTAL UERS
                        $number_of_page_students = ceil ($total_records_found_students / $items); # number of pages
                        $final_data_array_students = array_slice($students_details, $offset, $items);

                        # teachers only below
                        $total_records_found_teachers = count($teachers_ids); # TOTAL UERS
                        $number_of_page_teachers = ceil ($total_records_found_teachers / $items); # number of pages
                        $final_data_array_teachers = array_slice($teachers_details, $offset, $items);

                    ?>
                    <div id="proqyz-binary-selector-for-students" class="ielts-lms-binary-selector" data-type="ielts-lms-binary-selector" data-category="students">
                        <input type="hidden" name="data-ids" id="data-ids" value="[]">
                        <table class="ielts-lms-binary-selector-table">
                            <tr> 
                                <td class="left-selector">
                                    <input type="text" class="top-search search-left ielts-lms-binary-search" name="search-left" id="search-left" placeholder="Search student by username" data-type="left" data-proqyz-root="#proqyz-binary-selector-for-students" />
                                    <select class="ielts-lms-binary-selector-select" multiple="multiple">
                                        <?php foreach($final_data_array_students as $fdata){ ?>
                                            <option class="ielts-lms-binary-selector-select-options" value="<?php echo esc_html( $fdata["ID"] ); ?>" data-value="<?php echo esc_html( $fdata["ID"] ); ?>"> 
                                                <?php echo $fdata["username"]; ?> ( <?php echo $fdata['email']; ?> )
                                            </option>
                                        <?php } ?>    
                                    </select>
                                    <ul class="ielts-lms-pagination ielts-lms-pagination-left" data-type="pagination" data-pos="left">
                                        <li class="learndash-binary-selector-pager-prev">
                                            <a data-proqyz-root="#proqyz-binary-selector-for-students" data-pos="left" data-type="prev" data-total="<?php echo $number_of_page_students; ?>" class="page-links learndash-binary-selector-pager prev-link learndash-binary-selector-pager-prev" href="javascript:void(0);" style="<?php echo ($number_of_page_students > 1 && $current_page > 1) ? 'display:flex;' : 'display:none;'; ?>">
                                                ‹ prev
                                            </a>
                                        </li>
                                        <li class="learndash-binary-selector-pager-info"> 
                                            Page <span class="current_page"><?php echo $current_page; ?></span> of <span class="total_pages"><?php echo $number_of_page_students; ?></span> 
                                            <input type="hidden" name="current-page" value="<?php echo $current_page; ?>">
                                            <input type="hidden" name="total-pages" value="<?php echo $number_of_page_students; ?>">
                                        </li>
                                        <li data-pos="right" class="learndash-binary-selector-pager-next">
                                            <a data-proqyz-root="#proqyz-binary-selector-for-students" data-pos="left" data-type="next" data-total="<?php echo $number_of_page_students; ?>" class="page-links learndash-binary-selector-pager next-link learndash-binary-selector-pager-next" href="javascript:void(0);" style="<?php echo ($number_of_page_students > 1 && $current_page < $number_of_page_students) ? 'display:flex;' : 'display:none;'; ?>">
                                                next ›
                                            </a>
                                        </li>
                                    </ul>

                                </td>
                                <td class="center-selector">
                                    <a href="javascript:void(0);" class="ielts-lms-binary-selector-buttons ielts-lms-binary-selector-button-add" data-proqyz-root="#proqyz-binary-selector-for-students">
                                        <img src="<?php echo ST_PROQYZ_PLUGIN_URL . "includes/admin/dist/img/arrow_right.png"; ?>">
                                    </a>
                                    <br />
                                    <a href="javascript:void(0);" class="ielts-lms-binary-selector-buttons ielts-lms-binary-selector-button-remove" data-proqyz-root="#proqyz-binary-selector-for-students">
                                        <img src="<?php echo ST_PROQYZ_PLUGIN_URL. "includes/admin/dist/img/arrow_left.png"; ?>">
                                    </a>

                                </td>
                                <td class="right-selector">
                                    <input type="text" class="top-search search-right ielts-lms-binary-search" name="search-left" id="search-right" placeholder="Search student by username" data-type="right" data-proqyz-root="#proqyz-binary-selector-for-students" />
                                    <select class="ielts-lms-binary-selector-select" multiple="multiple">
                                        
                                    </select>
                                </td>
                            </tr>
                        </table>
                    </div>

                    <div id="proqyz-binary-selector-for-teachers" class="ielts-lms-binary-selector" data-type="ielts-lms-binary-selector" data-category="teachers">
                        <input type="hidden" name="data-ids" id="data-ids" value="[]">
                        <table class="ielts-lms-binary-selector-table">
                            <tr>
                                <td class="left-selector">
                                    <input type="text" class="bottom-search search-left ielts-lms-binary-search" name="search-left" id="search-left" placeholder="Search teachers by username" data-type="left" data-proqyz-root="#proqyz-binary-selector-for-teachers" />
                                    <select class="ielts-lms-binary-selector-select" multiple="multiple">
                                        <?php foreach($final_data_array_teachers as $fdata){ ?>
                                            <option class="ielts-lms-binary-selector-select-options" value="<?php echo esc_html( $fdata["ID"] ); ?>" data-value="<?php echo esc_html( $fdata["ID"] ); ?>"> 
                                                <?php echo $fdata["username"]; ?> ( <?php echo $fdata['email']; ?> )
                                            </option>
                                        <?php } ?>    
                                    </select>
                                    <ul class="ielts-lms-pagination ielts-lms-pagination-left" data-type="pagination" data-pos="left">
                                        <li class="learndash-binary-selector-pager-prev">
                                            <a data-proqyz-root="#proqyz-binary-selector-for-teachers" data-pos="left" data-type="prev" data-total="<?php echo $number_of_page_teachers; ?>" class="page-links learndash-binary-selector-pager prev-link learndash-binary-selector-pager-prev" href="javascript:void(0);" style="<?php echo ($number_of_page_teachers > 1 && $current_page > 1) ? 'display:flex;' : 'display:none;'; ?>">‹ prev</a>
                                        </li>
                                        <li class="learndash-binary-selector-pager-info"> 
                                            Page <span class="current_page"><?php echo $current_page; ?></span> of <span class="total_pages"><?php echo $number_of_page_teachers; ?></span> 
                                            <input type="hidden" name="current-page" value="<?php echo $current_page; ?>">
                                            <input type="hidden" name="total-pages" value="<?php echo $number_of_page_teachers; ?>">
                                        </li>
                                        <li data-pos="left" class="learndash-binary-selector-pager-next">
                                            <a data-proqyz-root="#proqyz-binary-selector-for-teachers" data-pos="left" data-type="next" data-total="<?php echo $number_of_page_teachers; ?>" class="page-links learndash-binary-selector-pager next-link learndash-binary-selector-pager-next" href="javascript:void(0);" style="<?php echo ($number_of_page_teachers > 1 && $current_page < $number_of_page_teachers) ? 'display:flex;' : 'display:none;'; ?>">next ›</a>
                                        </li>
                                    </ul>
                                </td>
                                <td class="center-selector">
                                    <a href="javascript:void(0);" class="ielts-lms-binary-selector-buttons ielts-lms-binary-selector-button-add" data-proqyz-root="#proqyz-binary-selector-for-teachers">
                                        <img src="<?php echo ST_PROQYZ_PLUGIN_URL . "includes/admin/dist/img/arrow_right.png"; ?>">
                                    </a>
                                    <br />
                                    <a href="javascript:void(0);" class="ielts-lms-binary-selector-buttons ielts-lms-binary-selector-button-remove" data-proqyz-root="#proqyz-binary-selector-for-teachers">
                                        <img src="<?php echo ST_PROQYZ_PLUGIN_URL. "includes/admin/dist/img/arrow_left.png"; ?>">
                                    </a>

                                </td>
                                <td class="right-selector">
                                    <input type="text" class="bottom-search search-right ielts-lms-binary-search" name="search-left" id="search-right" placeholder="Search teacher by username" data-type="right" data-proqyz-root="#proqyz-binary-selector-for-teachers" />
                                    <select class="ielts-lms-binary-selector-select" multiple="multiple">
                                        
                                    </select>
                                </td>
                            </tr>
                        </table>
                    </div>


                </div>  


            </div>

            <div class="modal-footer">
                <input type="hidden" id="post" value="<?php echo $_POST['type']; ?>" />
                <?php if($_POST['type'] == "new"){ ?>
                <button id="save-btn" type="submit" class="btn btn-primary components-button is-primary"> Create Group </button>
                <?php } ?>
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> 
            </div>

        </form>
    <?php
    $group_layout = ob_get_clean();

    if($_POST['type'] == "new"){
        wp_send_json([
            "success" => (object) [
                "has_html" => true,
                "html"     => $group_layout 
            ]
        ]);
    }

    
}

# for editable group layout
add_action('wp_ajax_proqyz-groups-action', 'proqyz_groups_action_callback');
function proqyz_groups_action_callback(){
    if(isset($_POST['type']) && !empty($_POST['type'])) {
        if($_POST['type'] == "edit") {
            if(isset($_POST['id']) && !empty($_POST['id'])) {
                global $wpdb, $table_proqyz_groups;
                $table_users            = $wpdb->prefix."users";
                $students_ids = array(); $students_details = array(); $students_assigned_details = array();
                $teachers_ids = array(); $teachers_details = array(); $teachers_assigned_details = array();
                $already_student_ids    = array();
                $group_id               = $_POST['id'];

                $get_group = $wpdb->get_row("SELECT * FROM {$table_proqyz_groups} WHERE `ID` = '$group_id' AND `status` = 1 LIMIT 1");
                if( $get_group ) {
                    $group_title        = $get_group->group_title;
                    $student_ids_db     = $get_group->student_ids;
                    $teacher_ids_db     = $get_group->teacher_ids;
                    $student_ids_arr_db = explode(",",$student_ids_db);
                    $teacher_ids_arr_db = explode(",",$teacher_ids_db);

                    # get all groups students
                    $get_groups = $wpdb->get_results("SELECT * FROM {$table_proqyz_groups} WHERE `status` = 1 AND `ID` != '$group_id' ");
                    foreach($get_groups as $group){
                        $group_student_ids = $group->student_ids;
                        $group_student_ids = stripslashes($group_student_ids);
                        $group_student_ids = str_replace('"',"",$group_student_ids);
                        $group_student_ids_arr = explode(",",$group_student_ids);      
                        foreach($group_student_ids_arr as $gid){
                            if(!in_array($gid,$already_student_ids)){
                                array_push($already_student_ids,$gid);
                            }
                        }
                    }

                    # merge already ids
                    
                    

                    $query =  "SELECT * FROM `$table_users` WHERE 1 ORDER BY `display_name` ASC"; 
                    $all_users_query = $wpdb->get_results($query);
                    foreach($all_users_query as $user){
                        $usermeta = get_userdata($user->ID);
                        $user_roles = (array) $usermeta->roles;

                        if(!in_array('administrator',$user_roles) && !in_array('teacher',$user_roles)){
                            # check if this student is already part of any group
                            if(!in_array($user->ID,$students_ids)){
                                if(!in_array($user->ID,$already_student_ids)){
                                    array_push($students_ids,$user->ID);
                                    array_push($students_details,array(
                                        "ID"            => $user->ID,
                                        "display_name"  => $user->display_name,
                                        "role"          => "student",
                                        "username"      => $user->user_login,
                                        "email"         => $user->user_email
                                    ));
                                }
                                // already assigned user ids
                                if(in_array($user->ID,$student_ids_arr_db)){
                                    array_push($students_assigned_details,array(
                                        "ID"            => $user->ID,
                                        "display_name"  => $user->display_name,
                                        "role"          => "student",
                                        "username"      => $user->user_login,
                                        "email"         => $user->user_email
                                    ));
                                }
                            }
                        }else if(in_array('administrator',$user_roles) || in_array('teacher',$user_roles)){
                            if(!in_array($user->ID,$teachers_ids)){
                                array_push($teachers_ids,$user->ID);
                                array_push($teachers_details,array(
                                    "ID"            => $user->ID,
                                    "display_name"  => $user->display_name,
                                    "role"          => "teacher",
                                    "username"      => $user->user_login,
                                    "email"         => $user->user_email
                                ));
                                if(in_array($user->ID,$teacher_ids_arr_db)){
                                    array_push($teachers_assigned_details,array(
                                        "ID"            => $user->ID,
                                        "display_name"  => $user->display_name,
                                        "role"          => "teacher",
                                        "username"      => $user->user_login,
                                        "email"         => $user->user_email
                                    ));
                                }
                            }
                        }
                        
                    } 

                    $items = 20;
                    $current_page = 1;
                    $offset = ($current_page - 1) * $items;

                    # students only below
                    # students only below
                    $total_records_found_students = count($students_ids); # TOTAL UERS
                    $number_of_page_students = ceil ($total_records_found_students / $items); # number of pages
                    $final_data_array_students = array_slice($students_details, $offset, $items);

                    # teachers only below
                    $total_records_found_teachers = count($teachers_ids); # TOTAL UERS
                    $number_of_page_teachers = ceil ($total_records_found_teachers / $items); # number of pages
                    $final_data_array_teachers = array_slice($teachers_details, $offset, $items);

                    ob_start(); ?>
                    <div class="wrapper">
                        <div id="proqyz-binary-selector-for-students" class="ielts-lms-binary-selector" data-type="ielts-lms-binary-selector" data-category="students">
                            <input type="hidden" name="data-ids" id="data-ids" value="[<?php echo $student_ids_db; ?>]">
                            <table class="ielts-lms-binary-selector-table">
                                <tr> 
                                    <td class="left-selector">
                                        <input type="text" class="top-search search-left ielts-lms-binary-search" name="search-left" id="search-left" placeholder="Search student by username" data-type="left" data-proqyz-root="#proqyz-binary-selector-for-students" />
                                        <select class="ielts-lms-binary-selector-select" multiple="multiple">
                                            <?php foreach($final_data_array_students as $fdata){ 
                                                if(in_array($fdata["ID"],$student_ids_arr_db)){ ?>
                                                    <option class="ielts-lms-binary-selector-select-options ielts-lms-binary-selector-item-disabled" value="<?php echo esc_html( $fdata["ID"] ); ?>" data-value="<?php echo esc_html( $fdata["ID"] ); ?>" disabled> 
                                                        <?php echo $fdata["username"]; ?> ( <?php echo $fdata['email']; ?> )
                                                    </option>
                                                <?php }else{ ?>
                                                    <option class="ielts-lms-binary-selector-select-options" value="<?php echo esc_html( $fdata["ID"] ); ?>" data-value="<?php echo esc_html( $fdata["ID"] ); ?>"> 
                                                        <?php echo $fdata["username"]; ?> ( <?php echo $fdata['email']; ?> )
                                                    </option>
                                                <?php } 
                                            } ?>     
                                        </select>
                                        <ul class="ielts-lms-pagination ielts-lms-pagination-left" data-type="pagination" data-pos="left">
                                            <li class="learndash-binary-selector-pager-prev">
                                                <a data-proqyz-root="#proqyz-binary-selector-for-students" data-pos="left" data-type="prev" data-total="<?php echo $number_of_page_students; ?>" class="page-links learndash-binary-selector-pager prev-link learndash-binary-selector-pager-prev" href="javascript:void(0);" style="<?php echo ($number_of_page_students > 1 && $current_page > 1) ? 'display:flex;' : 'display:none;'; ?>">
                                                    ‹ prev
                                                </a>
                                            </li>
                                            <li class="learndash-binary-selector-pager-info"> 
                                                Page <span class="current_page"><?php echo $current_page; ?></span> of <span class="total_pages"><?php echo $number_of_page_students; ?></span> 
                                                <input type="hidden" name="current-page" value="<?php echo $current_page; ?>">
                                                <input type="hidden" name="total-pages" value="<?php echo $number_of_page_students; ?>">
                                            </li>
                                            <li data-pos="right" class="learndash-binary-selector-pager-next">
                                                <a data-proqyz-root="#proqyz-binary-selector-for-students" data-pos="left" data-type="next" data-total="<?php echo $number_of_page_students; ?>" class="page-links learndash-binary-selector-pager next-link learndash-binary-selector-pager-next" href="javascript:void(0);" style="<?php echo ($number_of_page_students > 1 && $current_page < $number_of_page_students) ? 'display:flex;' : 'display:none;'; ?>">
                                                    next ›
                                                </a>
                                            </li>
                                        </ul>

                                    </td>
                                    <td class="center-selector">
                                        <a href="javascript:void(0);" class="ielts-lms-binary-selector-buttons ielts-lms-binary-selector-button-add" data-proqyz-root="#proqyz-binary-selector-for-students">
                                            <img src="<?php echo ST_PROQYZ_PLUGIN_URL . "includes/admin/dist/img/arrow_right.png"; ?>">
                                        </a>
                                        <br />
                                        <a href="javascript:void(0);" class="ielts-lms-binary-selector-buttons ielts-lms-binary-selector-button-remove" data-proqyz-root="#proqyz-binary-selector-for-students">
                                            <img src="<?php echo ST_PROQYZ_PLUGIN_URL. "includes/admin/dist/img/arrow_left.png"; ?>">
                                        </a>

                                    </td>
                                    <td class="right-selector">
                                        <input type="text" class="top-search search-right ielts-lms-binary-search" name="search-left" id="search-right" placeholder="Search student by username" data-type="right" data-proqyz-root="#proqyz-binary-selector-for-students" />
                                        <select class="ielts-lms-binary-selector-select" multiple="multiple">
                                            <?php foreach($students_assigned_details as $fdata){ ?>
                                                <option class="ielts-lms-binary-selector-select-options" value="<?php echo esc_html( $fdata["ID"] ); ?>" data-value="<?php echo esc_html( $fdata["ID"] ); ?>"> 
                                                    <?php echo $fdata["username"]; ?> ( <?php echo $fdata['email']; ?> )
                                                </option>
                                            <?php } ?>   
                                        </select>
                                    </td>
                                </tr>
                            </table>
                        </div>

                        <div id="proqyz-binary-selector-for-teachers" class="ielts-lms-binary-selector" data-type="ielts-lms-binary-selector" data-category="teachers">
                            <input type="hidden" name="data-ids" id="data-ids" value="[<?php echo $teacher_ids_db; ?>]">
                            <table class="ielts-lms-binary-selector-table">
                                <tr>
                                    <td class="left-selector">
                                        <input type="text" class="bottom-search search-left ielts-lms-binary-search" name="search-left" id="search-left" placeholder="Search teachers by username" data-type="left" data-proqyz-root="#proqyz-binary-selector-for-teachers" />
                                        <select class="ielts-lms-binary-selector-select" multiple="multiple">
                                            <?php foreach($final_data_array_teachers as $fdata){ 
                                                if(in_array($fdata["ID"],$teacher_ids_arr_db)){ ?>
                                                    <option class="ielts-lms-binary-selector-select-options ielts-lms-binary-selector-item-disabled" value="<?php echo esc_html( $fdata["ID"] ); ?>" data-value="<?php echo esc_html( $fdata["ID"] ); ?>" disabled> 
                                                        <?php echo $fdata["username"]; ?> ( <?php echo $fdata['email']; ?> )
                                                    </option>
                                                <?php }else{ ?>
                                                    <option class="ielts-lms-binary-selector-select-options" value="<?php echo esc_html( $fdata["ID"] ); ?>" data-value="<?php echo esc_html( $fdata["ID"] ); ?>"> 
                                                        <?php echo $fdata["username"]; ?> ( <?php echo $fdata['email']; ?> )
                                                    </option>
                                                <?php } 
                                            } ?>      
                                        </select>
                                        <ul class="ielts-lms-pagination ielts-lms-pagination-left" data-type="pagination" data-pos="left">
                                            <li class="learndash-binary-selector-pager-prev">
                                                <a data-proqyz-root="#proqyz-binary-selector-for-teachers" data-pos="left" data-type="prev" data-total="<?php echo $number_of_page_teachers; ?>" class="page-links learndash-binary-selector-pager prev-link learndash-binary-selector-pager-prev" href="javascript:void(0);" style="<?php echo ($number_of_page_teachers > 1 && $current_page > 1) ? 'display:flex;' : 'display:none;'; ?>">‹ prev</a>
                                            </li>
                                            <li class="learndash-binary-selector-pager-info"> 
                                                Page <span class="current_page"><?php echo $current_page; ?></span> of <span class="total_pages"><?php echo $number_of_page_teachers; ?></span> 
                                                <input type="hidden" name="current-page" value="<?php echo $current_page; ?>">
                                                <input type="hidden" name="total-pages" value="<?php echo $number_of_page_teachers; ?>">
                                            </li>
                                            <li data-pos="left" class="learndash-binary-selector-pager-next">
                                                <a data-proqyz-root="#proqyz-binary-selector-for-teachers" data-pos="left" data-type="next" data-total="<?php echo $number_of_page_teachers; ?>" class="page-links learndash-binary-selector-pager next-link learndash-binary-selector-pager-next" href="javascript:void(0);" style="<?php echo ($number_of_page_teachers > 1 && $current_page < $number_of_page_teachers) ? 'display:flex;' : 'display:none;'; ?>">next ›</a>
                                            </li>
                                        </ul>
                                    </td>
                                    <td class="center-selector">
                                        <a href="javascript:void(0);" class="ielts-lms-binary-selector-buttons ielts-lms-binary-selector-button-add" data-proqyz-root="#proqyz-binary-selector-for-teachers">
                                            <img src="<?php echo ST_PROQYZ_PLUGIN_URL . "includes/admin/dist/img/arrow_right.png"; ?>">
                                        </a>
                                        <br />
                                        <a href="javascript:void(0);" class="ielts-lms-binary-selector-buttons ielts-lms-binary-selector-button-remove" data-proqyz-root="#proqyz-binary-selector-for-teachers">
                                            <img src="<?php echo ST_PROQYZ_PLUGIN_URL. "includes/admin/dist/img/arrow_left.png"; ?>">
                                        </a>

                                    </td>
                                    <td class="right-selector">
                                        <input type="text" class="bottom-search search-right ielts-lms-binary-search" name="search-left" id="search-right" placeholder="Search teacher by username" data-type="right" data-proqyz-root="#proqyz-binary-selector-for-teachers" />
                                        <select class="ielts-lms-binary-selector-select" multiple="multiple">
                                            <?php foreach($teachers_assigned_details as $fdata){ ?>
                                                <option class="ielts-lms-binary-selector-select-options" value="<?php echo esc_html( $fdata["ID"] ); ?>" data-value="<?php echo esc_html( $fdata["ID"] ); ?>"> 
                                                    <?php echo $fdata["username"]; ?> ( <?php echo $fdata['email']; ?> )
                                                </option>
                                            <?php } ?>    
                                        </select>
                                    </td>
                                </tr>
                            </table>
                        </div>    
                    </div>
                    <?php $groups_html = ob_get_clean();

                    ob_start(); ?>
                    <form id="create-group-form" data-proqyz-form="create-group-form" style="display:contents;" >
                        
                        <div class="modal-header">
                            <h5 style="flex: 1 1 auto;margin: 0;" class="modal-title">
                                Manage Group
                            </h5>
                        </div>

                        <div class="modal-header">

                            <div class="form-field" style="margin-bottom:10px;">
                                <input 
                                    value="<?php echo $group_title; ?>"
                                    style="width:100%;" 
                                    class="form-control" 
                                    type="text" 
                                    name="group-title" 
                                    id="group-title" 
                                    placeholder="Enter Group title"
                                    required
                                >
                            </div>

                            <div class="form-group clearfix">
                                <div class="icheck-primary d-inline-flex">
                                    <input type="radio" id="username-search" checked value="username" name="search-by" data-proqyz-search-for="groups">
                                    <label for="username-search" style="font-weight:normal;">Username</label>
                                </div>
                                <div class="icheck-primary d-inline-flex">
                                    <input type="radio" id="email-search" value="email" name="search-by" data-proqyz-search-for="groups">
                                    <label for="email-search" style="font-weight:normal;">Email</label>
                                </div>
                                
                                <div class="icheck-primary d-inline-flex">
                                    <input type="radio" id="id-search" value="user-id" name="search-by" data-proqyz-search-for="groups">
                                    <label for="id-search" style="font-weight:normal;">User id</label>
                                </div>
                                
                                <div class="d-flex" id="search-text">

                                </div>
                    
                            </div>



                        </div>

                        <div class="modal-body" id="modal-body-groups">
                            <?php echo $groups_html; ?>    
                        </div>

                        <div class="modal-footer">
                            <input type="hidden" id="post" value="edit" />
                            <input type="hidden" id="id" value="<?php echo $group_id; ?>" />
                            <button id="save-btn" type="submit" class="components-button is-primary"> Save Group </button>
                            <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> 
                        </div>

                    </form>
                    <?php $main_html = ob_get_clean();

                    wp_send_json([
                        "success" => (object) [
                            "message"  => "Group loaded successfully",
                            "has_html" => true,
                            "html"     => $main_html 
                        ]
                    ]);


                } else {
                    wp_send_json([
                        "error" => (object) [
                            "message" => "It Looks like this group dosn't exists anymore"
                        ]
                    ]);
                }
            } else {
                wp_send_json([
                    "error" => (object) [
                        "message" => "Missing post id"
                    ]
                ]);
            }
        } else if($_POST['type'] == "delete") { 
            if(isset($_POST['id']) && !empty($_POST['id'])) {
                global $wpdb, $table_proqyz_groups;
                $group_id               = $_POST['id'];
                $get_group = $wpdb->get_row("SELECT * FROM {$table_proqyz_groups} WHERE `ID` = '$group_id' AND `status` = 1 LIMIT 1");
                if( $get_group ) {
                    $remove = $wpdb->delete($table_proqyz_groups, [
                        "ID" => $group_id
                    ]);

                    if( $remove ) {
                        wp_send_json([
                            "success" => (object) [
                                "res_type" => 'success',
                                "message" => "Group removed successfully"
                            ]
                        ]);
                    } else {
                        wp_send_json([
                            "error" => (object) [
                                "res_type" => 'info',
                                "message" => "Failed to remove, It Looks like this group dosn't exists anymore"
                            ]
                        ]);
                    }

                } else {
                    wp_send_json([
                        "error" => (object) [
                            "res_type" => 'info',
                            "message" => "It Looks like this group dosn't exists anymore"
                        ]
                    ]);
                }
            } else {
                wp_send_json([
                    "error" => (object) [
                        "res_type" => 'warning',
                        "message" => "Missing post id"
                    ]
                ]);
            }
        } else {
            wp_send_json([
                "error" => (object) [
                    "message" => "Missing post action type"
                ]
            ]);
        }
    } else {
        wp_send_json([
            "error" => (object) [
                "message" => "Action undefined"
            ]
        ]);
    }
}

# for post edit / insert layout
add_action('wp_ajax_proqyz-ajax-group-form-action', 'proqyz_ajax_group_form_action_callback');
function proqyz_ajax_group_form_action_callback(){
    global $wpdb, $table_proqyz_groups;

    if(!isset($_POST['group-title']) || empty($_POST['group-title'])){
        wp_send_json([
            "error" => (object) [
                "message"   => "Missing Group title",
                "type"      => $_POST['type'],
                "res_type"  => "warning"
            ]
        ]);
    }

    $student_ids = "";
    if(isset($_POST['student-ids']) && !empty($_POST['student-ids'])){
        $student_ids = implode(",",$_POST['student-ids']);
    }

    $teacher_ids = "";
    if(isset($_POST['teacher-ids']) && !empty($_POST['teacher-ids'])){
        $teacher_ids = implode(",",$_POST['teacher-ids']);
    }

    $group_id = null;
    if($_POST['type'] == "new") {
        $new_group = $wpdb->insert($table_proqyz_groups, [
            "group_title"       => $_POST['group-title'],
            "group_slug"        => sanitize_title($_POST['group-title']),
            "student_ids"       => $student_ids,
            "teacher_ids"       => $teacher_ids,
            "status"            => 1,
            "date_of_publish"   => date("U")
        ]);

        if( $new_group ) {
            wp_send_json([
                "success" => (object) [
                    "message"   => "Group created successfully",
                    "type"      => "new",
                    "res_type"  => "success",
                    "reload"    => true
                ]
            ]);
        } else {
            wp_send_json([
                "error" => (object) [
                    "message" => "Failed to create group",
                    "type"      => "new",
                    "res_type"  => "error"
                ]
            ]);
        }

    } else if($_POST['type'] == "edit") {
        $group_id = $_POST['group-id'];
        $get_group = $wpdb->get_row("SELECT * FROM {$table_proqyz_groups} WHERE `ID` = '$group_id' AND `status` = 1 LIMIT 1");
        if($get_group) {

            $update_group = $wpdb->update($table_proqyz_groups, [
                "group_title"       => $_POST['group-title'],
                "group_slug"        => sanitize_title($_POST['group-title']),
                "student_ids"       => $student_ids,
                "teacher_ids"       => $teacher_ids,
                "status"            => 1
            ], [
                "ID"    => $group_id
            ]);

            if( $update_group ) {
                wp_send_json([
                    "success" => (object) [
                        "message" => "Group saved successfully",
                        "type"      => "edit",
                        "res_type"  => "success"
                    ]
                ]);
            } else {
                wp_send_json([
                    "success" => (object) [
                        "message"   => "No Changes made",
                        "type"      => "edit",
                        "res_type"  => "info"
                    ]
                ]);
            }
        } else {
            wp_send_json([
                "error" => (object) [
                    "message" => "Failed to get group info",
                    "type"      => "edit",
                    "res_type"  => "error"
                ]
            ]);
        }
    }

}


add_action('wp_ajax_proqyz-binary-selector', 'proqyz_binary_selector_callback');
function proqyz_binary_selector_callback(){
    if(isset($_POST['type']) && !empty($_POST['type'])){
        $request_type       = $_POST['type'];
        if($request_type == "students" || $request_type == "teachers"){
            global $wpdb, $table_proqyz_groups;
            $assigned_ids       = array();
            $ids_text           = "[]";
            
            $already_student_ids = array();
            # get all groups students
            $group_id = $_POST['group-id'];
            $get_groups = $wpdb->get_results("SELECT * FROM {$table_proqyz_groups} WHERE `status` = 1 AND `ID` != '$group_id'");
            foreach($get_groups as $group){
                $group_student_ids = $group->student_ids;
                $group_student_ids = stripslashes($group_student_ids);
                $group_student_ids = str_replace('"',"",$group_student_ids);
                $group_student_ids_arr = explode(",",$group_student_ids);      
                foreach($group_student_ids_arr as $gid){
                    if(!in_array($gid,$already_student_ids)){
                        array_push($already_student_ids,$gid);
                    }
                }
            }

            # sort by [ key | all ]
            if(isset($_POST['ids']) && !empty($_POST['ids'])){
                $get_ids = $_POST['ids'];

                foreach($get_ids as $id){
                    
                        if(get_userdata($id)){
                            $usermeta = get_userdata($id);
                            // Get all the user roles for this user as an array.
                            $user_roles = (array) $usermeta->roles;
                            if($request_type == "students" && (!in_array('administrator',$user_roles) && !in_array('teacher',$user_roles))){
                                if(!in_array($id,$assigned_ids)){
                                    array_push($assigned_ids,$id);
                                }
                            }else if($request_type == "teachers" && (in_array('administrator',$user_roles) || in_array('teacher',$user_roles))){
                                if(!in_array($id,$assigned_ids)){
                                    array_push($assigned_ids,$id);
                                }
                            }
                        }
                    
                }

            }
            $ids_text = "[".implode(",",$assigned_ids)."]";



            $table_users = $wpdb->prefix."users";

            if(isset($_POST['sort-by']) && !empty($_POST['sort-by']) && $_POST['sort-by'] == "key"){
                
                if(isset($_POST['key-type']) && !empty($_POST['key-type'])) {
                    if($_POST['key-type'] == "username") {
                        $search_by = " `user_login` LIKE ";
                        $order_by = " `user_login` ";
                    } else if($_POST['key-type'] == "email") {
                        $search_by = " `user_email` LIKE ";
                        $order_by = " `user_email` ";
                    } else if($_POST['key-type'] == "user-id") {
                        $search_by = " `ID` LIKE ";
                        $order_by = " `user_login` ";
                    } else {
                        $search_by = " `user_login` LIKE ";
                        $order_by = " `user_login` ";
                    }
                } else {
                    $search_by = " `user_login` LIKE ";
                    $order_by = " `user_login` ";
                }


                $html_options_left = "";
                $html_options_right = "";
                $display_name = trim($_POST['key']);
                $query =  "SELECT * FROM `$table_users` WHERE $search_by '%{$display_name}%' ORDER BY $order_by ASC"; 
                $all_users_query = $wpdb->get_results($query);
                foreach($all_users_query as $user){
                    $user_text = $user->user_login." ( $user->user_email ) ";
                    $usermeta = get_userdata($user->ID);
                    // Get all the user roles for this user as an array.
                    $user_roles = (array) $usermeta->roles;
                    if($request_type == "students" && (!in_array('administrator',$user_roles) && !in_array('teacher',$user_roles))){
                        # only students # left side # by key
                        if(!in_array($user->ID,$already_student_ids)){
                            if(in_array($user->ID,$assigned_ids)){
                                $class_l = "ielts-lms-binary-selector-item-disabled";
                                $disabled = 'disabled';   
                            }else{
                                $class_l = "";
                                $disabled = "";
                            }
                            # for left side search option
                            $html_options_left .= '<option class="proqyz-binary-selector-select-options '.$class_l.'" value="'.esc_html( $user->ID ).'" data-value="'.esc_html( $user->ID ).'" '.$disabled.'>'. $user_text .'</option> ';
                            # for right side search option
                            if(in_array($user->ID,$assigned_ids)){
                                $html_options_right .= '<option class="proqyz-binary-selector-select-options" value="'.esc_html( $user->ID ).'" data-value="'.esc_html( $user->ID ).'" >'. $user_text .'</option> ';
                            }
                        }

                    }else if($request_type == "teachers" && (in_array('administrator',$user_roles) || in_array('teacher',$user_roles))){
                        # only students # left side # by key
                        if(in_array($user->ID,$assigned_ids)){
                            $class_l = "ielts-lms-binary-selector-item-disabled";
                            $disabled = 'disabled';   
                        }else{
                            $class_l = "";
                            $disabled = "";
                        }
                        # for left side search option
                        $html_options_left .= '<option class="proqyz-binary-selector-select-options '.$class_l.'" value="'.esc_html( $user->ID ).'" data-value="'.esc_html( $user->ID ).'" '.$disabled.'>'. $user_text .'</option> ';
                        # for right side search option
                        if(in_array($user->ID,$assigned_ids)){
                            $html_options_right .= '<option class="proqyz-binary-selector-select-options" value="'.esc_html( $user->ID ).'" data-value="'.esc_html( $user->ID ).'">'. $user_text .'</option> ';
                        }
                    }
                }

                $json = array(
                    "success"       => (object) [
                        "has_html"  => true,
                        "has_json"  => true,
                        "json"      => (object) [
                            "ids"           => $ids_text,
                            "pos"           => $_POST['pos'],
                            "sort_by"       => "key",
                            "users"         => $all_users_query
                        ],
                        "html"      => (object) [
                            "html_left"     => $html_options_left,
                            "html_right"    => $html_options_right,
                        ],
                        "query"             => $query
                    ]
                );
    
                wp_send_json($json);

            }else{
                # show all by roles
                $html_options_left = "";
                $html_options_right = "";

                $user_ids = array();
                $user_details = array();
                $query =  "SELECT * FROM `$table_users` WHERE 1 ORDER BY `user_login` ASC"; 
                $all_users_query = $wpdb->get_results($query);
                foreach($all_users_query as $user){
                    $usermeta = get_userdata($user->ID);
                    $user_text = $user->user_login." ( $user->user_email ) ";
                    // Get all the user roles for this user as an array.
                    $user_roles = (array) $usermeta->roles;
                    if($request_type == "students" && (!in_array('administrator',$user_roles) && !in_array('teacher',$user_roles))){
                        if(!in_array($user->ID,$already_student_ids)){
                            if(!in_array($user->ID,$user_ids)){
                                array_push($user_ids,$user->ID);
                                array_push($user_details,array(
                                    "ID"            => $user->ID,
                                    "display_name"  => $user->display_name,
                                    "role"          => "student",
                                    "username"      => $user->user_login,
                                    "email"         => $user->user_email
                                ));
                            }
                        }
                    }else if($request_type == "teachers" && (in_array('administrator',$user_roles) || in_array('teacher',$user_roles))){
                        if(!in_array($user->ID,$user_ids)){
                            array_push($user_ids,$user->ID);
                            array_push($user_details,array(
                                "ID"            => $user->ID,
                                "display_name"  => $user->display_name,
                                "role"          => "teacher",
                                "username"      => $user->user_login,
                                "email"         => $user->user_email
                            ));
                        }
                    }
                    # right html only assigned ids all
                    if(in_array($user->ID,$assigned_ids)){
                        $html_options_right .= '<option class="proqyz-binary-selector-select-options" value="'.esc_html( $user->ID ).'" data-value="'.esc_html( $user->ID ).'">'. $user_text .'</option> ';
                    }

                        
                }

                # left html only those are within pagination
                $items = 20;
                $total_records_found = count($user_ids); # TOTAL UERS
                $number_of_page = ceil ($total_records_found / $items); # number of pages
                $current_page = 1;
                if(isset($_POST['current_page']) && !empty($_POST['current_page'])){
                    if($_POST['current_page'] <= $number_of_page){
                        $current_page = $_POST['current_page'];
                    }
                }

                if(isset($_POST['page_mod']) && !empty($_POST['page_mod'])){
                    if($_POST['page_mod'] == "prev"){
                        
                        if($_POST['current_page'] > 0){  
                            $current_page = $current_page - 1;
                            if($current_page == 0){
                                $current_page = 1;
                            }
                        }

                    }else if($_POST['page_mod'] == "next"){
                        
                        if($_POST['current_page'] < $number_of_page){
                            $current_page = $current_page + 1;
                        }else{
                            $current_page = 1;
                        }
                    }
                }
                

                $offset = ($current_page - 1) * $items;
                $final_data_array = array_slice($user_details, $offset, $items);
                    
                foreach($final_data_array as $fdata){
                    $user_text = $fdata['username']." ( ".$fdata['email']." ) ";
                    # right html only assigned ids all
                    if(in_array($fdata["ID"],$assigned_ids)){
                        $html_options_left .= '<option class="proqyz-binary-selector-select-options ielts-lms-binary-selector-item-disabled" value="'.esc_html( $fdata["ID"] ).'" data-value="'.esc_html( $fdata["ID"] ).'" disabled>'.$user_text.'</option> ';
                    }else{
                        $html_options_left .= '<option class="proqyz-binary-selector-select-options " value="'.esc_html( $fdata["ID"] ).'" data-value="'.esc_html( $fdata["ID"] ).'">'. $user_text .'</option> ';
                    }
                }

                    

                $json = array(
                    "success"       => (object) [
                        "has_html"  => true,
                        "has_json"  => true,
                        "json"      => (object) [
                            "ids"           => $ids_text,
                            "pos"           => $_POST['pos'],
                            "sort_by"       => "all",
                            "current_page"  => $current_page,
                            "total_pages"   => $number_of_page
                        ],
                        "html"      => (object) [
                            "html_left"     => $html_options_left,
                            "html_right"    => $html_options_right,
                        ]
                    ]
                );
        
                wp_send_json($json);


            }

        } else if($request_type == "course-access-all") {
            global $wpdb;
            $course_id          = $_POST['group-id'];
            $table_users        = $wpdb->prefix."users";

            // Get the post object
            $post = get_post($course_id);
            // Check if the post exists and matches the specified post type
            if ( $post && $post->post_type === 'product' ) {
                $course = (object) array(
                    'ID'         => $post->ID,
                    'title'      => get_the_title($post),
                    'api_id'     => get_post_meta($post->ID, '_sku', true), // Get the 'sku' meta field
                );

                $enrolled_users = []; $enrolled_users_ids = [];
                $ids_text           = "[]";

                # sort by [ key | all ]
                if(isset($_POST['ids']) && !empty($_POST['ids'])){
                    $get_ids = $_POST['ids'];

                    foreach($get_ids as $id){
                        
                            if(get_userdata($id)){
                                $usermeta = get_userdata($id);
                                // Get all the user roles for this user as an array.
                                $user_roles = (array) $usermeta->roles;
                                if( !in_array( $id, $enrolled_users_ids) ){
                                    array_push( $enrolled_users_ids, $id );
                                }
                                
                            }
                        
                    }

                }

                $ids_text = "[".implode(",", $enrolled_users_ids)."]";


                if(isset($_POST['sort-by']) && !empty($_POST['sort-by']) && $_POST['sort-by'] == "key"){
                
                    if(isset($_POST['key-type']) && !empty($_POST['key-type'])) {
                        if($_POST['key-type'] == "username") {
                            $search_by = " `user_login` LIKE ";
                            $order_by = " `user_login` ";
                        } else if($_POST['key-type'] == "email") {
                            $search_by = " `user_email` LIKE ";
                            $order_by = " `user_email` ";
                        } else if($_POST['key-type'] == "user-id") {
                            $search_by = " `ID` LIKE ";
                            $order_by = " `user_login` ";
                        } else {
                            $search_by = " `user_login` LIKE ";
                            $order_by = " `user_login` ";
                        }
                    } else {
                        $search_by = " `user_login` LIKE ";
                        $order_by = " `user_login` ";
                    }
    
    
                    $html_options_left = "";
                    $html_options_right = "";
                    $display_name = trim($_POST['key']);

                    // Loop through each user and collect the required data
                    $display_name       = trim($_POST['key']);
                    $query              =  "SELECT * FROM `$table_users` WHERE $search_by '%{$display_name}%' ORDER BY $order_by ASC"; 
                    $all_users_query    = $wpdb->get_results($query);
                    foreach ($all_users_query as $user) {
                        $user_text = $user->user_login." ( $user->user_email ) ";
                        # only students # left side # by key
                        if( in_array( $user->ID, $enrolled_users_ids )){
                            $class_l = "ielts-lms-binary-selector-item-disabled";
                            $disabled = 'disabled';   
                        } else {
                            $class_l = "";
                            $disabled = "";
                        }

                        # for left side search option
                        $html_options_left .= '<option class="proqyz-binary-selector-select-options '.$class_l.'" value="'.esc_html( $user->ID ).'" data-value="'.esc_html( $user->ID ).'" '.$disabled.'>'. $user_text .'</option> ';
                        # for right side search option
                        if(in_array($user->ID, $enrolled_users_ids)){
                            $html_options_right .= '<option class="proqyz-binary-selector-select-options" value="'.esc_html( $user->ID ).'" data-value="'.esc_html( $user->ID ).'" >'. $user_text .'</option> ';
                        }
                        
                    }
                    

    
                    $json = array(
                        "success"       => (object) [
                            "has_html"  => true,
                            "has_json"  => true,
                            "json"      => (object) [
                                "ids"           => $ids_text,
                                "pos"           => $_POST['pos'],
                                "sort_by"       => "key",
                                "users"         => $all_users_query
                            ],
                            "html"      => (object) [
                                "html_left"     => $html_options_left,
                                "html_right"    => $html_options_right,
                            ],
                            "query"             => $query
                        ]
                    );
        
                    wp_send_json($json);
    
                } else {
                    
                    # show all by roles
                    $html_options_left = "";
                    $html_options_right = "";

                    $user_ids = array();
                    $user_details = array();
                    $query =  "SELECT * FROM `$table_users` WHERE 1 ORDER BY `user_login` ASC"; 
                    $all_users_query = $wpdb->get_results($query);

                    foreach($all_users_query as $user){
                        $usermeta = get_userdata($user->ID);
                        $user_text = $user->user_login." ( $user->user_email ) ";
                        // Get all the user roles for this user as an array.
                        
                        if(!in_array( $user->ID,$user_ids )){
                            array_push($user_ids,$user->ID);
                            array_push($user_details,array(
                                "ID"            => $user->ID,
                                "display_name"  => $user->display_name,
                                "username"      => $user->user_login,
                                "email"         => $user->user_email
                            ));
                        }
                        
                        
                        # right html only assigned ids all
                        if(in_array($user->ID,$enrolled_users_ids)){
                            $html_options_right .= '<option class="proqyz-binary-selector-select-options" value="'.esc_html( $user->ID ).'" data-value="'.esc_html( $user->ID ).'">'. $user_text .'</option> ';
                        }

                            
                    }

                    # left html only those are within pagination
                    $items = 20;
                    $total_records_found = count($user_ids); # TOTAL UERS
                    $number_of_page = ceil ($total_records_found / $items); # number of pages
                    $current_page = 1;

                    if(isset($_POST['current_page']) && !empty($_POST['current_page'])){
                        if($_POST['current_page'] <= $number_of_page){
                            $current_page = $_POST['current_page'];
                        }
                    }

                    if(isset($_POST['page_mod']) && !empty($_POST['page_mod'])){
                        if($_POST['page_mod'] == "prev"){
                            
                            if($_POST['current_page'] > 0){  
                                $current_page = $current_page - 1;
                                if($current_page == 0){
                                    $current_page = 1;
                                }
                            }

                        }else if($_POST['page_mod'] == "next"){
                            
                            if($_POST['current_page'] < $number_of_page){
                                $current_page = $current_page + 1;
                            }else{
                                $current_page = 1;
                            }
                        }
                    }


                    $offset = ($current_page - 1) * $items;
                    $final_data_array = array_slice($user_details, $offset, $items);
                        
                    foreach($final_data_array as $fdata){
                        $user_text = $fdata['username']." ( ".$fdata['email']." ) ";
                        # right html only assigned ids all
                        if(in_array($fdata["ID"],$enrolled_users_ids)){
                            $html_options_left .= '<option class="proqyz-binary-selector-select-options ielts-lms-binary-selector-item-disabled" value="'.esc_html( $fdata["ID"] ).'" data-value="'.esc_html( $fdata["ID"] ).'" disabled>'.$user_text.'</option> ';
                        }else{
                            $html_options_left .= '<option class="proqyz-binary-selector-select-options " value="'.esc_html( $fdata["ID"] ).'" data-value="'.esc_html( $fdata["ID"] ).'">'. $user_text .'</option> ';
                        }
                    }

                        

                    $json = array(
                        "success"       => (object) [
                            "has_html"  => true,
                            "has_json"  => true,
                            "json"      => (object) [
                                "ids"           => $ids_text,
                                "pos"           => $_POST['pos'],
                                "sort_by"       => "all",
                                "current_page"  => $current_page,
                                "total_pages"   => $number_of_page
                            ],
                            "html"      => (object) [
                                "html_left"     => $html_options_left,
                                "html_right"    => $html_options_right,
                            ]
                        ]
                    );
            
                    wp_send_json($json);
    
    
                }




            } else {
                wp_send_json([
                    "error" => (object) [
                        "message" => "Post is not registered"
                    ]
                ]);
            }

        } else {
            wp_send_json([
                "error" => (object) [
                    "message"   => 'Type of Action not defined !'
                ]
            ]);
        }

    } else {
        wp_send_json([
            "error" => (object) [
                "message"   => 'Type of Action not defined !'
            ]
        ]);
    }
} 


/**
 * course access
 */
add_action('wp_ajax_proqyz-course-action','proqyz_course_action_callback');
function proqyz_course_action_callback(){
    if(isset($_POST['type']) && !empty($_POST['type'])) {
        if($_POST['type'] == "course-access") {
            if(isset($_POST['id']) && !empty($_POST['id'])) {
                $course_id  = $_POST['id'];
                // Get the post object
                $post = get_post($course_id);
                // Check if the post exists and matches the specified post type
                if ( $post && $post->post_type === 'product' ) {

                    $course = (object) array(
                        'ID'         => $post->ID,
                        'title'      => get_the_title($post),
                        'api_id'     => get_post_meta($post->ID, '_sku', true), // Get the 'sku' meta field
                    );

                    # users
                    $users          = get_users();
                    // Initialize an empty array to store user data
                    $all_users      = []; $all_users_ids = [];
                    $enrolled_users = []; $enrolled_users_ids = [];


                    // Loop through each user and collect the required data
                    foreach ($users as $user) {
                        $all_users_ids[]    = $user->ID;
                        $all_users[]        = array(
                            'ID'            => $user->ID,
                            'username'      => $user->user_login,
                            'email'         => $user->user_email,
                            'first_name'    => $user->first_name,
                            'last_name'     => $user->last_name,
                            'display_name'  => $user->display_name,
                            'roles'         => $user->roles
                        );
                    }

                    $args_enroll = array(
                        'meta_query' => array(
                            array(
                                'key'     => 'enroll-'.$course->api_id,
                                'compare' => 'EXISTS',
                            ),
                        ),
                    );
                
                    // Create a new instance of WP_User_Query
                    $user_query     = new WP_User_Query($args_enroll);
                    // Get the results
                    $users_enrolled = $user_query->get_results();
                    foreach ($users_enrolled as $user) {
                        $enrolled_users_ids[]       = $user->ID;
                        $enrolled_users[]           = array(
                            'ID'            => $user->ID,
                            'username'      => $user->user_login,
                            'email'         => $user->user_email,
                            'first_name'    => $user->first_name,
                            'last_name'     => $user->last_name,
                            'display_name'  => $user->display_name,
                            'roles'         => $user->roles
                        );
                    }

                    $items = 20;
                    $current_page = 1;
                    $offset = ($current_page - 1) * $items;

                    # students only below
                    # students only below
                    $total_records_found        = count($all_users_ids); # TOTAL UERS
                    $number_of_page_students    = ceil ($total_records_found / $items); # number of pages
                    $final_data_array           = array_slice($all_users, $offset, $items);
                    $enrolled_users_ids_txt     = implode(",",$enrolled_users_ids);

                    ob_start(); ?>
                    <div class="wrapper">
                        <div id="proqyz-binary-selector-for-all" class="ielts-lms-binary-selector" data-type="ielts-lms-binary-selector" data-category="course-access-all">
                            <input type="hidden" name="data-ids" id="data-ids" value="[<?php echo $enrolled_users_ids_txt; ?>]">
                            <table class="ielts-lms-binary-selector-table">
                                <tr> 
                                    <td class="left-selector">
                                        <input type="text" class="top-search search-left ielts-lms-binary-search" name="search-left" id="search-left" placeholder="Search All Course Users By Username" data-type="left" data-proqyz-root="#proqyz-binary-selector-for-all" />
                                        <select class="ielts-lms-binary-selector-select" multiple="multiple">
                                            <?php foreach($final_data_array as $fdata){ 
                                                if(in_array($fdata["ID"],$enrolled_users_ids)){ ?>
                                                    <option class="ielts-lms-binary-selector-select-options ielts-lms-binary-selector-item-disabled" value="<?php echo esc_html( $fdata["ID"] ); ?>" data-value="<?php echo esc_html( $fdata["ID"] ); ?>" disabled> 
                                                        <?php echo $fdata["username"]; ?> ( <?php echo $fdata['email']; ?> )
                                                    </option>
                                                <?php }else{ ?>
                                                    <option class="ielts-lms-binary-selector-select-options" value="<?php echo esc_html( $fdata["ID"] ); ?>" data-value="<?php echo esc_html( $fdata["ID"] ); ?>"> 
                                                        <?php echo $fdata["username"]; ?> ( <?php echo $fdata['email']; ?> )
                                                    </option>
                                                <?php } 
                                            } ?>     
                                        </select>
                                        <ul class="ielts-lms-pagination ielts-lms-pagination-left" data-type="pagination" data-pos="left">
                                            <li class="learndash-binary-selector-pager-prev">
                                                <a data-proqyz-root="#proqyz-binary-selector-for-all" data-pos="left" data-type="prev" data-total="<?php echo $number_of_page_students; ?>" class="page-links learndash-binary-selector-pager prev-link learndash-binary-selector-pager-prev" href="javascript:void(0);" style="<?php echo ($number_of_page_students > 1 && $current_page > 1) ? 'display:flex;' : 'display:none;'; ?>">
                                                    ‹ prev
                                                </a>
                                            </li>
                                            <li class="learndash-binary-selector-pager-info"> 
                                                Page <span class="current_page"><?php echo $current_page; ?></span> of <span class="total_pages"><?php echo $number_of_page_students; ?></span> 
                                                <input type="hidden" name="current-page" value="<?php echo $current_page; ?>">
                                                <input type="hidden" name="total-pages" value="<?php echo $number_of_page_students; ?>">
                                            </li>
                                            <li data-pos="right" class="learndash-binary-selector-pager-next">
                                                <a data-proqyz-root="#proqyz-binary-selector-for-all" data-pos="left" data-type="next" data-total="<?php echo $number_of_page_students; ?>" class="page-links learndash-binary-selector-pager next-link learndash-binary-selector-pager-next" href="javascript:void(0);" style="<?php echo ($number_of_page_students > 1 && $current_page < $number_of_page_students) ? 'display:flex;' : 'display:none;'; ?>">
                                                    next ›
                                                </a>
                                            </li>
                                        </ul>

                                    </td>
                                    <td class="center-selector">
                                        <a href="javascript:void(0);" class="ielts-lms-binary-selector-buttons ielts-lms-binary-selector-button-add" data-proqyz-root="#proqyz-binary-selector-for-all">
                                            <img src="<?php echo ST_PROQYZ_PLUGIN_URL . "includes/admin/dist/img/arrow_right.png"; ?>">
                                        </a>
                                        <br />
                                        <a href="javascript:void(0);" class="ielts-lms-binary-selector-buttons ielts-lms-binary-selector-button-remove" data-proqyz-root="#proqyz-binary-selector-for-all">
                                            <img src="<?php echo ST_PROQYZ_PLUGIN_URL. "includes/admin/dist/img/arrow_left.png"; ?>">
                                        </a>

                                    </td>
                                    <td class="right-selector">
                                        <input type="text" class="top-search search-right ielts-lms-binary-search" name="search-left" id="search-right" placeholder="Search Assigned Course Users By Username" data-type="right" data-proqyz-root="#proqyz-binary-selector-for-all" />
                                        <select class="ielts-lms-binary-selector-select" multiple="multiple">
                                            <?php foreach($enrolled_users as $fdata){ ?>
                                                <option class="ielts-lms-binary-selector-select-options" value="<?php echo esc_html( $fdata["ID"] ); ?>" data-value="<?php echo esc_html( $fdata["ID"] ); ?>"> 
                                                    <?php echo $fdata["username"]; ?> ( <?php echo $fdata['email']; ?> )
                                                </option>
                                            <?php } ?>   
                                        </select>
                                    </td>
                                </tr>
                            </table>
                        </div>

                    </div>
                    <?php $couse_access_html = ob_get_clean();

                    ob_start(); ?>
                    <form id="create-group-form" data-proqyz-form="course-access" style="display:contents;" >
                        
                        <div class="modal-header">
                            <h5 style="flex: 1 1 auto;margin: 0;" class="modal-title">
                                <?php echo $course->title; ?>
                            </h5>
                        </div>

                        <div class="modal-header">
                            <div class="form-group clearfix">
                                <div class="icheck-primary d-inline-flex">
                                    <input type="radio" id="username-search" checked value="username" name="search-by" data-proqyz-search-for="course-access">
                                    <label for="username-search" style="font-weight:normal;">Username</label>
                                </div>
                                <div class="icheck-primary d-inline-flex"> 
                                    <input type="radio" id="email-search" value="email" name="search-by" data-proqyz-search-for="course-access">
                                    <label for="email-search" style="font-weight:normal;">Email</label>
                                </div>
                                
                                <div class="icheck-primary d-inline-flex">
                                    <input type="radio" id="id-search" value="user-id" name="search-by" data-proqyz-search-for="course-access">
                                    <label for="id-search" style="font-weight:normal;">User id</label>
                                </div>
                                
                                <div class="d-flex" id="search-text">

                                </div>

                            </div>
                        </div>

                        <div class="modal-body" id="modal-body-groups">
                            <?php echo $couse_access_html; ?>    
                        </div>

                        <div class="modal-footer">
                            <input type="hidden" id="post" value="edit" />
                            <input type="hidden" id="id" value="<?php echo $course_id; ?>" />
                            <button id="save-btn" type="submit" class="components-button is-primary"> Save Changes </button>
                            <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> 
                        </div>

                    </form>
                    <?php $main_html = ob_get_clean();

                    wp_send_json([
                        "success" => (object) [
                            "message"  => "Course loaded successfully",
                            "has_html" => true,
                            "html"     => $main_html 
                        ]
                    ]);


                } else {
                    wp_send_json([
                        "error" => (object) [
                            "message" => "Post is not registered"
                        ]
                    ]);
                }
            } else {
                wp_send_json([
                    "error" => (object) [
                        "message" => "Missing post id"
                    ]
                ]);
            }
        } else {
            wp_send_json([
                "error" => (object) [
                    "message" => "Missing post action type"
                ]
            ]);
        }
    } else {
        wp_send_json([
            "error" => (object) [
                "message" => "Action undefined"
            ]
        ]);
    }
}

# for post edit - course access
add_action('wp_ajax_proqyz-ajax-course-access-form-action', 'proqyz_ajax_course_access_form_action_callback');
function proqyz_ajax_course_access_form_action_callback(){
    if(isset($_POST['course-id']) && !empty($_POST['course-id'])) {
        $course_id              = $_POST['course-id'];
        $assigned_user_ids      = isset($_POST['user-ids'])? (array) $_POST['user-ids'] : [];
        $unassigned_user_ids    = [];


        // Get the post object
        $post = get_post($course_id);
        // Check if the post exists and matches the specified post type
        if ( $post && $post->post_type === 'product' ) {
            $course = (object) array(
                'ID'         => $post->ID,
                'title'      => get_the_title($post),
                'api_id'     => get_post_meta($post->ID, '_sku', true), // Get the 'sku' meta field
                "enroll"     => get_post_meta($post->ID, 'course-meta_payment', true)
            );

            $course_payment_settings    = $course->enroll;
            $course_access              = isset($course_payment_settings->access)? $course_payment_settings->access : 'open';
            if( $course_access == "enroll" ) {
                $course_price           = isset($course_payment_settings->price)? $course_payment_settings->price : 0;
                $course_sale_price      = isset($course_payment_settings->sale)? $course_payment_settings->sale : 0;
                $course_expire_obj      = isset($course_payment_settings->expire)? (object) $course_payment_settings->expire : null;
                $course_expire_status   = isset($course_expire_obj->status)? (string) $course_expire_obj->status : 'never';
                $course_expire_days     = isset($course_expire_obj->dd)? (int) $course_expire_obj->dd : 0;

                $order_confirmation     = (object) [];
                if( $course_expire_status == "never" ) {
                    # no need to calculate payment anymore
                    $order_confirmation     = (object) [
                        "expire"        => "never",
                        "enroll"        => true,
                        "access"        => "enroll",
                        "created_at"    => date("U"),
                        "expires_in"    => 0,    
                        "expires_on"    => 0,
                        "status"        => "active"
                    ];
                } else if( $course_expire_status == "time" ) {
                    # payment - expire - days
                    if($course_expire_days > 0){
                        $mili_time  = ((int) $course_expire_days * 86400);
                        $expires_on = date("U") + $mili_time;
                        $order_confirmation     = (object) [
                            "expire"        => "expire",
                            "enroll"        => true,
                            "access"        => "enroll",
                            "created_at"    => date("U"),
                            "expires_in"    => $course_expire_days,    
                            "expires_on"    => $expires_on,
                            "status"        => "active"
                        ];
                    } else {
                        $order_confirmation     = (object) [
                            "expire"        => "never",
                            "enroll"        => true,
                            "access"        => "enroll",
                            "created_at"    => date("U"),
                            "expires_in"    => 0,    
                            "expires_on"    => 0,
                            "status"        => "active"
                        ];
                    }
                }

            } else if( $course_access == "open" ) {
                // no need to do anything
            }




            $args_enroll = array(
                'meta_query' => array(
                    array(
                        'key'     => 'enroll-'.$course->api_id,
                        'compare' => 'EXISTS',
                    ),
                ),
            );
        
            // Create a new instance of WP_User_Query
            $user_query     = new WP_User_Query($args_enroll);
            // Get the results
            $users_enrolled = $user_query->get_results();
            foreach ($users_enrolled as $user) {
                $enrolled_users_ids[]       = $user->ID;
                $enrolled_users[]           = array(
                    'ID'            => $user->ID,
                    'username'      => $user->user_login,
                    'email'         => $user->user_email,
                    'first_name'    => $user->first_name,
                    'last_name'     => $user->last_name,
                    'display_name'  => $user->display_name,
                    'roles'         => $user->roles
                );

                if (in_array($user->ID, $assigned_user_ids)) {
                    // Find the index of the user's ID in the assigned_ids array
                    $index = array_search($user->ID, $assigned_user_ids);
                    // Remove the ID from the assigned_ids array
                    if ($index !== false) {
                        unset($assigned_user_ids[$index]);
                    }
                } else {
                    $unassigned_user_ids[] = $user->ID;
                }
            }

            // Reindex the array to remove gaps in the keys
            $assigned_user_ids = array_values($assigned_user_ids);

            foreach( $unassigned_user_ids as $uid ) {
                delete_user_meta((int) $uid, 'enroll-'.$course->api_id);
            }

            foreach( $assigned_user_ids as $uid ) {
                if( $course_access == "enroll" ) {
                    update_user_meta((int) $uid, 'enroll-'.$course->api_id, $order_confirmation);
                }
            }

            wp_send_json([
                "success" => (object) [
                    "message"   => "Changes save successfully",
                    "res_type"  => "success",
                    "type"      => "edit"
                ]
            ]);

        } else {
            wp_send_json([
                "error" => (object) [
                    "message" => "Post is not registered",
                    "res_type"  => "warning",
                ]
            ]);
        }

    } else {
        wp_send_json([
            "error" => (object) [
                "message"   => "Missing post id",
                "res_type"  => "warning",
            ]
        ]);
    }
}

/**
 * sync courses
 */
add_action('wp_ajax_proqyz-sync-courses', 'proqyz_sync_courses_callback');
function proqyz_sync_courses_callback(){
    require_once ST_PROQYZ_ABSPATH . "includes/admin/class-st-proqyz-admin-page-course-access.php";
    if(class_exists('ST_ProQyz_Oauth') && class_exists('ST_ProQyz_Admin_Page_Course_Access')){
        $ilms_courses_res = (object) ST_ProQyz_Oauth::rest_post_request("/courses/sync", []);
        $courses = [];
        $payment_courses = [];
        
        if( isset($ilms_courses_res->success) ) {
            $remote_c_res  = (object) $ilms_courses_res->success;
            $remote_c_json = isset($remote_c_res->json)? (object) $remote_c_res->json : null;
            if( $remote_c_json ){
                $courses = isset($remote_c_json->courses)? (array) $remote_c_json->courses : [];
                $course_ids = [];
                if( count($courses) > 0 ) {
                    foreach( $courses as $ckey => $course ) {
                        $res_course = (object) $course;

                        $course_found = ST_ProQyz_Admin_Page_Course_Access::check_if_post_exists($res_course->_id);
                        if( !$course_found ) {
                            $course_frontend_title          = isset($res_course->title)? $res_course->title : $course_frontend_title;
                            $course_short_description       = isset($res_course->description)? $res_course->description : $course_short_description;
                            $course_payment_settings        = isset($res_course->_payment)? (object) $res_course->_payment : null;
                            $course_thumbnail_settings      = isset($res_course->_thumbnail)? (object) $res_course->_thumbnail: null;
                            $course_thumbnail_method        = isset($course_thumbnail_settings->method)? (string) $course_thumbnail_settings->method : null;
                            $course_thumbnail_url           = isset($course_thumbnail_settings->url)? (string) $course_thumbnail_settings->url : null;


                            # payment settings
                            $calculate_payment              = false;
                            if( $course_payment_settings ) {
                                
                                $course_access = isset($course_payment_settings->access)? $course_payment_settings->access : 'open';
                                
                                
                                
                                
                                
                                if( $course_access == "enroll" ) {
                                    
                                    
                                    
                                    $course_price           = isset($course_payment_settings->price)? $course_payment_settings->price : 0;
                                    $course_sale_price      = isset($course_payment_settings->sale)? $course_payment_settings->sale : 0;
                                    $course_expire_obj      = isset($course_payment_settings->expire)? (object) $course_payment_settings->expire : null;
                                    $course_expire_status   = isset($course_expire_obj->status)? (string) $course_expire_obj->status : 'never';
                                    $course_expire_days     = isset($course_expire_obj->dd)? (int) $course_expire_obj->dd : 0;
                                    
                                    

                                    # if price is payable - when has_product = true
                                    # then make woocommerce payment
                                    # filter for woocommerce integration
                                    $has_thumbnail = false;
                                    if($course_thumbnail_method === "url"){
                                        if($course_thumbnail_url) {
                                            $has_thumbnail = true;
                                        }
                                    } 

                                    $filtered_res = (object) apply_filters('proqyz-course-get-woo-product',"", (object) [
                                        "_id"               => $res_course->_id,
                                        "title"             => $course_frontend_title,
                                        "description"       => $course_short_description,
                                        "sale"              => $course_sale_price,
                                        "price"             => $course_price,
                                        "_payment"          => (object) $course_payment_settings,
                                        "thumbnail"         => $has_thumbnail? $course_thumbnail_url : null
                                    ]);
                                    
                                    $payment_courses[] = (object) [
                                        "_id"               => $res_course->_id,
                                        "title"             => $course_frontend_title,
                                        "access"            => $course_access,
                                        "_payment"          => (object) $course_payment_settings,
                                        "thumbnail"         => $has_thumbnail? $course_thumbnail_url : null,
                                        "sale"              => $course_sale_price,
                                        "price"             => $course_price,
                                        "is_active"         => $filtered_res->success
                                    ];

                                    if(isset($filtered_res->success)) {
                                        $woo_res            = (object) $filtered_res->success;
                                        $course_ids[]       = $woo_res->product_id;
                                    }
                                }
                            }
                        } else {
                            $course_ids[] = $course_found;
                        }

                    }
                }

                ST_ProQyz_Admin_Page_Course_Access::trash_unwanted_posts($course_ids);
                
                wp_send_json([
                    "success" => (object) [
                        "res_type" => "success",
                        "message"  => "Courses synced successfully",
                        "total"    => count($courses),
                        "ids"      => $course_ids,
                        "course"    => $payment_courses
                    ]
                ]);
                

            }
        } else if( isset($ilms_courses_res->error) ){
            $errors         = (object) $ilms_courses_res->error;
            $error_message  = $errors->message;
            wp_send_json([
                "error" => (object) [
                    "res_type" => "error",
                    "message"  => $error_message
                ]
            ]);
        }


    } else {
        wp_send_json([
            "error" => (object) [
                "res_type" => "error",
                "message" => "Sync failed, oauth class missing"
            ]
        ]);
    }
}