<?php
/**
 * template: ProQyz Course template 
 */
defined('ABSPATH') || exit;
require_once ST_PROQYZ_LIBS_DIR . '/lms/utill.php';
require_once 'functions.php';

// Get the current page URL
$current_url = home_url($_SERVER['REQUEST_URI']);
// These variables are correctly fetched from the URL, regardless of its structure.
$proqyz_course_type   = get_query_var('course_type');
$proqyz_course_id     = get_query_var('course_id');
$proqyz_lesson_id     = get_query_var('lesson_id');
$proqyz_quiz_category = get_query_var('quiz_category');
$proqyz_quiz_slug     = get_query_var('quiz_slug');
$proqyz_quiz_id       = get_query_var('quiz_id');
$proqyz_action        = get_query_var('action');


if ( empty($proqyz_lesson_id) ) { 
    // This block runs for the MAIN COURSE PAGE (e.g., /your-brand/your-courses/123/)
    
    // Course ID is required for the main page
    if ( empty($proqyz_course_id) ) {
        $proqyz_response = 'Course id missing or empty';
        include_once ST_PROQYZ_TEMPLATE_DIR . '/errors/404.php';
        exit; 
    }

    get_header();
    ?>
    <div class="entry-content" style="display:flex;align-items-center;width:100%;flex-direction:column;">
        <?php   
            // This shortcode is fine as it relies on the course_id, not the URL.
            echo do_shortcode("[proqyz-course course_id='$proqyz_course_id']");
        ?>
    </div>
    <?php
    get_footer();

} else {

    // --- Validations for the quiz page ---
    if ( empty($proqyz_course_id) ) {
        $proqyz_response = 'Course id missing or empty';
        include_once ST_PROQYZ_TEMPLATE_DIR . '/errors/404.php';
        exit; 
    }

    if ( empty($proqyz_lesson_id) ) {
        $proqyz_response = 'Lesson id missing or empty';
        include_once ST_PROQYZ_TEMPLATE_DIR . '/errors/404.php';
        exit; 
    }

    if ( !in_array($proqyz_quiz_category, ["ielts-reading", "ielts-listening", "ielts-writing", "ielts-speaking", "gov-sectional-timing", "gov-non-sectional-timing", 'proqyz-pdf-quiz']) ) {
        $proqyz_response = 'Unknown Quiz category';
        include_once ST_PROQYZ_TEMPLATE_DIR . '/errors/400.php';
        exit;
    }

    # get remote course with course id
    if( class_exists('ST_ProQyz_Oauth') ) {
        $fetch_rest_quiz = false;
        $session_obj     = [];

        // This logic can be simplified as we already know we're inside a course context.
        // Let's assume proqyz-course for this example.
        if ( empty($proqyz_course_type) ) {
            $proqyz_course_type = 'proqyz-course'; // Set a default if not present
        }



        # begin:: proqyz-course  
        if( $proqyz_course_type == "proqyz-course" ) {

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

            $rest_course = (object) ST_ProQyz_Oauth::rest_post_request("/courses/course/".$proqyz_course_id, $main_params_course);
            if( isset($rest_course->success) ) {
                $remote_c_res  = (object) $rest_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;

                        if ($proqyz_action && $proqyz_action === "view") { ?>
                            <!DOCTYPE html>
                            <html <?php language_attributes(); ?>>
                            <head>
                                <meta charset="<?php bloginfo('charset'); ?>" />
                                <meta name="viewport" content="width=device-width, initial-scale=1.0" />
                                <title><?php wp_title(); ?></title>
                            </head>
                            <body>
                                <?php 
                                    // --- NEW: DYNAMICALLY GENERATE THE 'START' URL ---
                                    // NOTE: You need to get the specific quiz details ($quiz_category, $quiz_slug, $quiz_id)
                                    // from your $res_course object to build the link correctly.
                                    $link_args = [
                                        'course_type'   => $proqyz_course_type,
                                        'course_id'     => $proqyz_course_id,
                                        'lesson_id'     => $proqyz_lesson_id,
                                        'quiz_category' => 'ielts-reading', // EXAMPLE: Get this from course data
                                        'quiz_slug'     => 'sample-quiz',   // EXAMPLE: Get this from course data
                                        'quiz_id'       => '456',           // EXAMPLE: Get this from course data
                                        'action'        => 'start'
                                    ];
                                    # update - slug
                                    $attempt_url = st_proqyz_get_course_quiz_url($link_args);
                                ?>
                                <a class="btn btn-primary" href="<?php echo esc_url($attempt_url); ?>" target="_blank">Start</a>
                            </body>
                            </html>
                            <?php 
                        } elseif ($proqyz_action && $proqyz_action === "start") {
                            $fetch_rest_quiz = true;
                            $session_obj = [
                                "course_title"      => $res_course->title,
                                "course"            => $res_course,
                                "session_category"  => "course",
                                "course_id"         => $proqyz_course_id,
                                "lesson_id"         => $proqyz_lesson_id,
                                'course_category'   => "proqyz-course",
                                "quiz_category"     => $proqyz_quiz_category,
                                "api_id"            => $proqyz_quiz_id
                            ];
                        }
        
                    } else {
                        // null - c
                        // remote - json
                        $proqyz_response = "Null Response from Server";
                        include_once ST_PROQYZ_TEMPLATE_DIR . '/errors/400.php';
                        exit;
                    }
        
        
                } else {
                    // remote - json
                    $proqyz_response = "Invalid Response from Server";
                    include_once ST_PROQYZ_TEMPLATE_DIR . '/errors/400.php';
                    exit;
                } 
                
            }
        
            if( isset($rest_course->error) ) {
                $error = (object) $rest_course->error;
                $proqyz_response  = $error->message;
                $proqyz_code      = $error->status;
                if($proqyz_code == "404"){
                    include_once ST_PROQYZ_TEMPLATE_DIR . '/errors/404.php';
                } else {
                    include_once ST_PROQYZ_TEMPLATE_DIR . '/errors/500.php';
                }
                exit;
            }

        
        } # end:: proqyz-course 


        # begin:: sfwd-course 
        if( $proqyz_course_type == "sfwd-course" ) {
            
            # learndash get post title
            $course_post = get_post($proqyz_course_id);
            if( !$course_post ) {
                include_once ST_PROQYZ_TEMPLATE_DIR . '/errors/404.php';
                exit;
            }

            $course_title = $course_post->post_title;
            $session_obj   = (object) [
                "course_title"      => $course_title,
                "session_category"  => "course",
                "course_id"         => $proqyz_course_id,
                "lesson_id"         => $proqyz_lesson_id,
                "course_category"   => "sfwd-course",
                "quiz_category"     => $proqyz_quiz_category,
                "api_id"            => $proqyz_quiz_id,
                "course"            => []    
            ];


            if(is_user_logged_in()) {
                $c_user_id = get_current_user_id();
                if( !function_exists('sfwd_lms_has_access') ) {
                    $proqyz_response = 'Function Learndash::sfwd_lms_has_access - not found';
                    include_once ST_PROQYZ_TEMPLATE_DIR . '/errors/400.php';
                    exit;
                }
                if( !sfwd_lms_has_access($proqyz_course_id, $c_user_id) ) {
                    $proqyz_response = 'User does not have access to the course';
                    include_once ST_PROQYZ_TEMPLATE_DIR . '/errors/403.php';
                    exit;
                }
            }

            $fetch_rest_quiz = true;
            
        } # end:: sfwd-course 

        if( $fetch_rest_quiz ) {

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


            $response = (object) ST_ProQyz_Oauth::rest_post_request("/quizzes/quiz/".$proqyz_quiz_id, $main_params);
            if (!isset($response->error)) {
                /**
                * sections [html]
                * styles   [html]
                */
        
                $html_response = load_quiz((object) [
                    'category'          => $proqyz_quiz_category,
                    'res'               => $response,
                    'session'           => (object) $session_obj
                ]);
        
                echo $html_response;
        
            } else {
                $error = (object) $response->error;
                $proqyz_response  = $error->message;
                $proqyz_code      = $error->status;
                if($proqyz_code == "404"){
                    include_once ST_PROQYZ_TEMPLATE_DIR . '/errors/404.php';
                } else {
                    include_once ST_PROQYZ_TEMPLATE_DIR . '/errors/500.php';
                }
                exit;
            }
        }


    }
}