<?php 
/**
 * v2.1.0 
 * 
 * hint: use of $wpdb and tables - none
 * hint:
 * update: none (next update move assets to another common location)
 * status: completed
 */

add_shortcode('proqyz-course', 'shortcode_proqyz_single_course');
add_shortcode('ilms-course', 'shortcode_proqyz_single_course');

function shortcode_proqyz_single_course( $atts = [], $content = null, $tag = '' ) {
    // load header
    $atts = array_change_key_case((array)$atts, CASE_LOWER);
    # override default attributes with user attributes
    $wporg_atts = shortcode_atts(
        array(
            'course_title'        => null,
            'course_category'     => null,
            'course_id'           => null,
            'course_status'       => null, 
            'created_at'          => null, 
            'course_icon_url'     => null, 
            'course_description'  => null
        ) , $atts, $tag
    );

    if( 1 == 1 ) {
        if($wporg_atts['course_id'] !== null) {

            $ilms_attempt_url = site_url();
            # quiz_id for rest_api
            // $response_Rest = (object) Ielts_Lms_Oauth::verify_rest_id("ilms-course", $wporg_atts['course_id']);
            if( 1 == 1 ) {
                
                $course_id                = $wporg_atts['course_id'];
                $course_frontend_title    = $wporg_atts['course_title'];
                $course_short_description   = $wporg_atts['course_description'];
                $course_published_date    = (int) $wporg_atts['created_at'] / 1000;
                $has_short_description    = true;
                $has_product              = false;
                $enroll_btn               = "";
                $user_enroll_status       = false;

                $enrolled_class           = "";
                $enrolled_text            = "open";

                $is_paid                  = false;
                $is_expired               = false;
                $course_access_status     = "open";
                $user_course_access       = "no-access";

                
                
                # get remote course
                if( class_exists('ST_ProQyz_Oauth') ) {

                    
            
                    $main_params = array_merge([
                        "where" => (object) [],
                        "grant_type" => "request",
                        "permission" => "course"
                    ],[
                        "request_id" => date("U")
                    ]);

                    $remote_course_ = (object) ST_ProQyz_Oauth::rest_post_request("/courses/course/".$course_id, $main_params);
                    if( isset($remote_course_->success) ) {
                        $remote_c_res  = (object) $remote_course_->success;
                        $remote_c_json = isset($remote_c_res->json)? (object) $remote_c_res->json : null;
                        if( $remote_c_json ){
                            $c = isset($remote_c_json->_c)? (object) $remote_c_json->_c : null;
                            if( $c ){
                                $res_course   = isset($c->course)? (object) $c->course : null;
                                $res_lessons    = isset($c->lessons)? (array) $c->lessons : [];

                                $per_page_lessons   = 5;      
                                $total_lessons      = count($res_lessons); # TOTAL UERS
                                $total_lesson_pages = ceil ($total_lessons / $per_page_lessons); # number of pages

                                
                                $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_published_date      = isset($res_course->creation)? (int) $res_course->creation : 0;
                                if($course_published_date > 0 ) {
                                    $course_published_date      = $course_published_date/1000;
                                }
                                # 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( $course_expire_status == "never" ) {
                                            # no need to calculate payment anymore
                                            $calculate_payment = true;



                                        } else if( $course_expire_status == "time" ) {
                                            # payment - expire - days
                                            if($course_expire_days > 0){
                                                $calculate_payment = true;
                                            }
                                        }
                                        # if price is payable - when has_product = true
                                        # then make woocommerce payment
                                        # filter for woocommerce integration

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

                                        if(isset($filtered_res->success)) {
                                            $woo_res          = (object) $filtered_res->success;
                                            $original_amount    = $woo_res->original_amount;
                                            $sale_amount      = $woo_res->sale_amount;
                                            $currency         = $woo_res->currency_symbol;
                                            $product_id       = $woo_res->product_id;
                                            $has_product      = true;
                                            // Display button based on sale price availability
                                            if ($sale_amount > 0) {
                                                // Display button with strike through original amount and sale amount
                                                ob_start(); ?>
                                                <button data-key="<?php echo $product_id; ?>" class="btn__enroll btn">
                                                    <strike><?php echo $currency."".$original_amount; ?></strike>
                                                    <?php echo $currency."".$sale_amount; ?>
                                                </button>
                                                

                                                
                                                <?php if($course_expire_status == "time"){
                                                    if($course_expire_days == 1){ ?>
                                                        <small>This course will expire the <b>Next day</b> after the purchase.</small>
                                                        
                                                    <?php } else { ?>

                                                        <small>This course will expire <b><?php echo $course_expire_days; ?> days</b> after the purchase.</small>
                                                    <?php }
                                                } else if($course_expire_status == "never"){ ?>
                                                    <small>This course will not expire after the purchase.</small>
                                                <?php } 

                                                $enroll_btn = ob_get_clean();

                                                
                                            } else {
                                                // Display button with original amount only
                                                ob_start(); ?>
                                                <button data-key="<?php echo $product_id; ?>" class="btn__enroll btn">
                                                    <?php echo $currency."".$original_amount; ?>
                                                </button>

                                                <?php if($course_expire_status == "time"){
                                                    if($course_expire_days == 1){ ?>
                                                        <small>This course will expire the <b>Next day</b> after the purchase.</small>
                                                        
                                                    <?php } else { ?>

                                                        <small>This course will expire <b><?php echo $course_expire_days; ?> days</b> after the purchase.</small>
                                                    <?php }
                                                } else if($course_expire_status == "never"){ ?>
                                                    <small>This course will not expire after the purchase.</small>
                                                <?php } 

                                                $enroll_btn = ob_get_clean();
                                                
                                            }

                                            
                                            
                                        }

                                        # calculate payment options
                                        if( $calculate_payment ) {
                                            $course_access_status   = "Get access";
                                        } else {
                                            $user_course_access     = "access";
                                            $course_access_status   = "open";
                                        }



                                    } else if( $course_access == "open" ) {
                                        $user_course_access   = "access";
                                        $course_access_status   = "open";
                                    }
                                } else {
                                    $user_course_access       = "access";
                                }

                                # check for course paid status
                                if( is_user_logged_in() ) {
                                    $current_user_id = get_current_user_id();
                                    $enroll_meta = get_user_meta( $current_user_id, 'enroll-'.$course_id, true);
                                    if( $enroll_meta ) {
                                        $enroll_meta    = (object) $enroll_meta;
                                        $expire         = isset($enroll_meta->expire)? $enroll_meta->expire : "never";
                                        $is_enroll      = isset($enroll_meta->enroll)? $enroll_meta->enroll : false;
                                        $enroll_access    = isset($enroll_meta->access)? $enroll_meta->access : "open";
                                        $order_time     = isset($enroll_meta->created_at)? (int) $enroll_meta->created_at : null;
                                        $expires_on     = isset($enroll_meta->expires_on)? (int) $enroll_meta->expires_on : null;   
                                        
                                        if( $enroll_access == "enroll" ) {

                                            if($is_enroll){
                                                if($expire ==  "never"){
                                                    $is_paid = true;
                                                    $is_expired = false;
                                                    $user_course_access = "access";
                                                    $course_access_status = "enrolled";
                                                    $enroll_btn = "";
                                                } else if($expire == "expire"){
                                                    if(date("U") >= $expires_on){
                                                        $is_paid = true;
                                                        $is_expired = true;
                                                        $user_course_access = "np-access";
                                                        $course_access_status = "expired";
                                                        
                                                    } else {
                                                        $is_paid = true;
                                                        $is_expired = false;
                                                        $user_course_access = "access";
                                                        $course_access_status = "enrolled";
                                                        ob_start(); ?>
                                                        <small>Course will expire on: <?php echo date("Y/m/d h:m a", (int) $expires_on); ?></small>
                                                        <?php $enroll_btn = ob_get_clean();

                                                    }
                                                }
                                            }
                                        }

                                    }
                                }


                                # this is for template layout [js, styles, dist, img]
                                static $assets_enqueued = false;
                                if (!$assets_enqueued) {
                                    $assets_enqueued = true;
                                    $plugin_dir = plugin_dir_url(ST_PROQYZ_PLUGIN_FILE);
                                    st_proqyz_enqueue_fonts();
                                    wp_enqueue_style('st-proqyz-course-common-css', $plugin_dir . 'includes/templates/shortcodes/course/default/dist/css/common.css', array(), false);
                                    wp_enqueue_style('st-proqyz-course-iot-icons-css', $plugin_dir . 'includes/templates/shortcodes/course/default/dist/css/iot-icons.css', array(), false);
                                    wp_enqueue_style('st-proqyz-course-style-4-css', $plugin_dir . 'includes/templates/shortcodes/course/default/dist/css/style-4.css', array(), false);
                                    wp_enqueue_script("st-proqyz-course-single", $plugin_dir . 'includes/templates/shortcodes/course/default/dist/js/proqyz-course-single.js', array( 'jquery' ),'2.6.0', false ); 
                                    wp_localize_script('st-proqyz-course-single', 'proqyz_data', array(
                                        'ajaxurl' => admin_url( 'admin-ajax.php' ),
                                    ));
                                }

                                ob_start();
                                    require ST_PROQYZ_ABSPATH .'includes/templates/shortcodes/course/default/default.php';
                                ?>
                                
                                    <script type="application/json" data-course-id="<?php echo $course_id; ?>">
                                        <?php echo json_encode($res_lessons); ?>
                                    </script>
                                    <script type="application/json" data-course-info="<?php echo $course_id; ?>">
                                        <?php echo json_encode((object) [
                                            "course" => (object) $res_course,
                                            "access" => $user_course_access
                                        ]); ?>
                                    </script>
                                <?php
                                return ob_get_clean();
                            } else {
                                return "[C]";
                            }
                        } else {
                            return "[JSON]";
                        }
                    } else {
                        if(isset($remote_course_->error)) {
                            $error_obj = (object) $remote_course_->error;
                            $error_res = isset($error_obj->message)? $error_obj->message : 'Unknown response';
                            return $error_res;
                        } else {
                            return "Unknown response";    
                        }
                        
                    }
                }
            }
        }

    }

}

function proqyz_get_lessons($params = []) {
    global $ST_OPTION_st_proqyz__IELTS_LMS, $ST_OPTION_st_proqyz__GOV_LMS, $ST_OPTION_st_proqyz__PDF_QUIZ_LMS;
    $IELTS_LMS_SHOW = get_option($ST_OPTION_st_proqyz__IELTS_LMS, 1);
    $GOV_LMS_SHOW = get_option($ST_OPTION_st_proqyz__GOV_LMS, 1);
    $PDF_QUIZ_LMS_SHOW = get_option($ST_OPTION_st_proqyz__PDF_QUIZ_LMS, 1);



    $params         = (array) $params;
    $lessons        = (array) $params['lessons'];
    $current_page   = (int) $params['current-page'];
    $course_id      = $params['course-id'];
    $course_layout  = $params['course-layout'];
    $course_access  = $params["_ec"];


    $per_page_lessons   = 5;      
    $total_lessons      = count($lessons); # TOTAL UERS
    $total_lesson_pages = ceil ($total_lessons / $per_page_lessons); # number of pages
    $offset_lesson = ($current_page - 1) * $per_page_lessons;
    $lessons_ids_arr = array_slice($lessons, $offset_lesson, $per_page_lessons);

    
            

    ob_start();
    if( count($lessons_ids_arr) ) {
        foreach( $lessons_ids_arr as $lkey => $lesson ) {
            $lesson       = (object) $lesson;
            $lesson_id    = $lesson->_id;
            $lesson_title   = $lesson->title;
            
            $preview_lesson = 0;
            $quizzes        = isset($lesson->quizzes)? (array) $lesson->quizzes : [];
            $quiz_html      = "";

            $lesson_preview = 0;
            if( $lesson->preview ) {
                $lesson_preview = 1;
            }

            // REMINDER
            $is_fullmock_test = false;
            // CHANGED: Using the new helper function to generate the dynamic URL.
            # update - slug
            $fullmock_test_url = st_proqyz_get_mock_test_url($course_id, $lesson_id, 'general-guidance');
            if(isset($lesson->fullTest) && $lesson->fullTest == true) {
                $is_fullmock_test = true;
            }

            
            $steps_fullmock_test = [];
            if( count($quizzes) > 0 ) {
                foreach( $quizzes as $qkey => $quiz ) {
                    $quiz          = (object) $quiz;
                    $quiz_id       = $quiz->_id;
                    $quiz_category   = $quiz->_category;
                    $quiz_type       = $quiz->_type;
                    $quiz_slug       = $quiz->_slug;
                    $quiz_title    = $quiz->title;

                    if($quiz_type == "ielts" && $quiz_category == "reading"){
                        $quiz_category = "ielts-reading";
                        array_push($steps_fullmock_test, $quiz_category);
                    } else if($quiz_type == "ielts" && $quiz_category == "listening"){
                        $quiz_category = "ielts-listening";
                        array_push($steps_fullmock_test, $quiz_category);
                    } else if($quiz_type == "ielts" && $quiz_category == "writing"){
                        $quiz_category = "ielts-writing";
                        array_push($steps_fullmock_test, $quiz_category);
                    } else if($quiz_type == "ielts" && $quiz_category == "speaking"){
                        $quiz_category = "ielts-speaking";
                        array_push($steps_fullmock_test, $quiz_category);
                    } else if($quiz_type == "gov" && $quiz_category == "non-sectional-timing"){
                        $quiz_category = "gov-non-sectional-timing";
                    } else if($quiz_type == "gov" && $quiz_category == "sectional-timing"){
                        $quiz_category = "gov-sectional-timing";
                    } else if($quiz_type == "proqyz" && $quiz_category == "pdf-quiz"){
                        $quiz_category = "proqyz-pdf-quiz";
                    }
                    
                    
                    $show = 1;
                    if($IELTS_LMS_SHOW == 0 && $quiz_type == "ielts"){
                        $show = 0;
                    }
                    
                    if($GOV_LMS_SHOW == 0 && $quiz_type == "gov"){
                        $show = 0;
                    }

                    if($PDF_QUIZ_LMS_SHOW == 0 && $quiz_category == "proqyz-pdf-quiz"){
                        $show = 0;
                    }
                    
                    
                    if( $show == 1){
                        $session_category = "course";
                        /**
                         * this function below return full session and some meta ('score', 'quiz_title', 'course_title', 'json')
                         * hint: this function calls here only because its using static varible like (session_category, course_category - directly)
                         */
                        $get_session = proqyz_get_user_session_details((object) [
                            "quiz_category"    => $quiz_category,
                            "quiz_id"          => $quiz_id,
                            "quiz_slug"        => $quiz_slug,
                            "session_category"   => "course",
                            "course_category"    => "proqyz-course",
                            "course_id"        => $course_id,
                            "lesson_id"        => $lesson_id
                        ]);    
                        require ST_PROQYZ_ABSPATH .'includes/templates/shortcodes/quiz/default/proqyz-quiz-default-layout-shortcode.php';
                        
                    }
                    

                }
            }

            $is_valid_fullmock_test = true;
            $is_fullmock_test_completed = false;
            if( $is_fullmock_test && count($steps_fullmock_test) == 4 ) {
                foreach($steps_fullmock_test as $step) {
                    if($step === "ielts-listening" || $step === "ielts-reading" || $step === "ielts-writing" || $step === "ielts-speaking") {

                    } else {
                        $is_valid_fullmock_test = true;
                    }
                }
            } else {
                $is_fullmock_test = false;
                $is_valid_fullmock_test = false;
            }

            $progress_fullmock_test = 0;
            $icon_class = "-start";
            if( $is_valid_fullmock_test ){
                $current_user_id = get_current_user_id();
                $get_full_test_meta = get_user_meta( $current_user_id, "proqyz__full-mock-test--$course_id-$lesson_id", true);
                if( $get_full_test_meta) {
                    $get_full_test_meta = (object) $get_full_test_meta;
                    if(isset($get_full_test_meta->status)) {

                        if( $get_full_test_meta->status === "not-started" ) {
                            $progress_fullmock_test = 0;
                            $icon_class = "-start";
                        } else if($get_full_test_meta->status === "listening-completed--reading-start") {
                            $progress_fullmock_test = 25;
                            $icon_class = "-resume";
                        } else if($get_full_test_meta->status === "reading-completed--writing-start") {
                            $progress_fullmock_test = 50;
                            $icon_class = "-resume";
                        } else if($get_full_test_meta->status === "writing-completed--speaking-start") {
                            $progress_fullmock_test = 75;
                            $icon_class = "-resume";
                        } else if($get_full_test_meta->status === "speaking-completed--finish-test") {
                            $progress_fullmock_test = 100;
                            // CHANGED: Using the new helper function to generate the dynamic URL.
                            # update - slug
                            $fullmock_test_url = st_proqyz_get_mock_test_url($course_id, $lesson_id, 'result');
                            $icon_class = "-result";
                        } else {
                            $progress_fullmock_test = 0;
                        }
                    }
                }
            }

            ?><div 
                class="practice-list__card course-card-new ielts-topics" 
                data-type="lesson" 
                data-id="<?php echo $lesson_id; ?>" 
                data-content="<?php echo $lesson_title; ?>"
            >
                <h5 class="practice-list__title"><?php echo $lesson_title; ?></h5>
                <?php if($lesson_preview == 1){ ?>
                    <div class="full-test__ribbon">Preview</div>
                <?php } ?>
                <?php if($preview_lesson == 1){ ?>
                    <div class="full-test__ribbon">Preview</div>
                <?php } ?>
                <div class="practice-list__items flex-grid">
                    <?php echo $quiz_html; ?>
                </div>

                <!-- BEGIN::FULL MOCK TEST [DISABLED] -->
                <?php if($is_fullmock_test){ ?>
                    <div class="full-test " style="overflow:hidden;position:relative;">
                        <div class="full-test__ribbon fullmock-test">NEW</div>
                        <h6 class="full-test__title"> 
                            <span class="ioticon-squares-four"></span> 
                            Full Test <i class="fa fa-question-circle-o" aria-hidden="true" title="" data-original-title=" You can take a complete test for the Listening, Reading, Writing and Speaking sections now, just like in the real IELTS exam! "></i>
                        </h6>
                        <div class="full-test__progress <?php echo $progress_fullmock_test > 0? 'progress' : '-start'; ?>" style="overflow:hidden;">
                            <div class="progress-bar" role="progressbar" aria-valuenow="<?php echo $progress_fullmock_test; ?>" aria-valuemin="0" aria-valuemax="100" style="width:<?php echo $progress_fullmock_test; ?>%; <?php echo $progress_fullmock_test > 0? 'text-align:center;color:white;font-size: 12.4px;' : ''; ?>">
                                <?php echo $progress_fullmock_test; ?>%
                            </div>
                        </div>
                        <?php if($icon_class == "-result"){ ?>
                            <a class="full-test__btn <?php echo $icon_class; ?>" href="<?php echo esc_url($fullmock_test_url); ?>"> 
                                Result
                            </a>
                        <?php } else { ?>
                            
                            <button class="full-test__btn <?php echo $icon_class; ?>" data-proqyz-modal="true" data-target="#modal-fulltest" data-toggle="modal" data-speaking-mode="1" data-href="<?php echo esc_url($fullmock_test_url); ?>"> 
                                <?php if($progress_fullmock_test <= 0){ ?> 
                                    Start 
                                <?php } else if($progress_fullmock_test > 0 || $progress_fullmock_test < 100){ ?> 
                                    Continue 
                                <?php } ?>
                            </button>
                        <?php } ?>
                        <div class="new-tip" id="js-newtip"> You can take a complete test for the Listening, Reading, Writing and Speaking sections now, just like in the real IELTS exam!</div>
                    </div>
                <?php } ?>
                <!-- END::FULL MOCK TEST [DISABLED] -->
            </div>
            <?php 
        }
    }
    $html = ob_get_clean();

    return (object) [
        "status"    => 1,
        "html"      => $html
    ];
}

/**
 * ajax pagination
 */
function proqyz_course_pagination() {

    $data_response = (object) proqyz_get_lessons(array(
        "lessons"           => json_decode(stripslashes($_POST['lessons'])),
        "current-page"      => $_POST['current-page'],
        "previous-status"   => $_POST['previous-status'],
        "course-id"         => $_POST['course-id'],
        "course-layout"     => $_POST['course-layout'],
        "_ec"               => $_POST['_ec']
    ));

    if( $data_response->status == 1 ){
        wp_send_json([
            "success" => (object) [
                "message"  => "page loaded",
                "html"     => $data_response->html,
                "has_html" => true
            ]
        ]);
    } else {
        wp_send_json([
            "error" => (object) [
                "message" => "Something went wrong"
            ]
        ]);
    }
}

add_action('wp_ajax_proqyz-course-pagination','proqyz_course_pagination');
add_action('wp_ajax_nopriv_proqyz-course-pagination','proqyz_course_pagination');

/**
 * some css for course 
 */
function proqyz_enqueue_lightmodal_assets() {
    wp_enqueue_script(
        'proqyz-light-modal-js',
        ST_PROQYZ_PUBLIC_URL .'/dist/js/lightModal.js',
        array('jquery'),
        '1.0',
        true
    );
}

add_action('wp_enqueue_scripts', 'proqyz_enqueue_lightmodal_assets');