<?php 
/**
 * v3.1.0
 * Attach meta data (score, etc.) to session object from meta table
 * 
 * @param object $session Session object from submissions table
 * @return object Session object with meta data attached
 * DB tables used: ---------------------------------------------------------
 * @table_proqyz_progress_submissions_meta {meta_key, meta_value} as {json (unserialize), score (unserialize), quiz_title (string), course_title (string)}
 * -------------------------------------------------------------------------
 */
function proqyz_attach_meta_data_to_session($session) {
    global $wpdb, $table_proqyz_v3_progress_submissions_meta, 
    $table_proqyz_v3_progress_submissions_user_response,
    $table_proqyz_v3_progress_submissions_score,
    $table_proqyz_v3_submissions_review_meta,
    $table_proqyz_v3_submissions_review;
    
    if (!$session || !isset($session->ID)) {
        return $session;
    }

    $quiz_category = $session->quiz_category;
    
    
    // Fetch all meta data for this submission in one optimized query
    // This replaces the old schema where score was directly in the main table
    $meta_data = $wpdb->get_results($wpdb->prepare(
        "SELECT meta_key, meta_value FROM {$table_proqyz_v3_progress_submissions_meta} 
        WHERE submission_id = %d 
        AND meta_key IN ('score', 'quiz_title', 'course_title', 'course_subcategory')",
        $session->ID
    ));
    
    // Attach meta data to session object (maintain backward compatibility)
    $session->score = null;
    $session->quiz_title = null;
    $session->course_title = null;
    $session->course_subcategory = null;
    
    if ($meta_data) {
        foreach ($meta_data as $meta) {
            $key = $meta->meta_key;
            $value = $meta->meta_value;
            
            // Attach each meta field to session object
            $session->$key = $value;
        }
    }

    // get json from user response table
    $session->json = null;
    $json = $wpdb->get_var("SELECT `response_data` FROM {$table_proqyz_v3_progress_submissions_user_response} WHERE `submission_id` = '$session->ID' LIMIT 1");
    if( $json ) {
        $session->json = $json;
    }

    // get score from score table
    $session->score = null;
    if($quiz_category == 'ielts-writing'){
        $scores = [];
        if($session->review == 1) { 
            $sections = $wpdb->get_var("SELECT `meta_value` FROM {$table_proqyz_v3_progress_submissions_meta} WHERE `submission_id` = '$session->ID' AND `meta_key` = 'sections' LIMIT 1");
            $sections = maybe_unserialize($sections);
            $sections = !empty($sections) ? (array) $sections : [];
            $has_task_1 = false;
            $task_1_id = null;
            $has_task_2 = false;
            $task_2_id = null;
            if(count($sections) > 0) {
                foreach($sections as $section) {
                    $section = (object) $section;
                    $section_id = $section->_id;
                    if($section->order == 1) {
                        $has_task_1 = true;
                        $task_1_id = $section_id;
                    } else if($section->order == 2) {
                        $has_task_2 = true;
                        $task_2_id = $section_id;
                    }
                }
            }
            if($has_task_1) {
                # get review id by using result_id and section_id
                $review_id = $wpdb->get_var("SELECT `ID` FROM {$table_proqyz_v3_submissions_review} WHERE `result_id` = '$session->ID' AND `section_id` = '$task_1_id' AND `status` = 1 LIMIT 1");
                if($review_id) {
                    # get review scores meta from review meta table using review_id
                    $review_scores = $wpdb->get_var("SELECT `meta_value` FROM {$table_proqyz_v3_submissions_review_meta} WHERE `review_id` = '$review_id' AND `meta_key` = 'review-scores' AND `meta_status` = 1 LIMIT 1");
                    if($review_scores) {
                        $review_scores = json_decode($review_scores, true);
                        $scores['task-1'] = $review_scores;
                    }
                }
            }
            if($has_task_2) {
                # get review id by using result_id and section_id
                $review_id = $wpdb->get_var("SELECT `ID` FROM {$table_proqyz_v3_submissions_review} WHERE `result_id` = '$session->ID' AND `section_id` = '$task_2_id' AND `status` = 1 LIMIT 1");
                if($review_id) {
                    # get review scores meta from review meta table using review_id
                    $review_scores = $wpdb->get_var("SELECT `meta_value` FROM {$table_proqyz_v3_submissions_review_meta} WHERE `review_id` = '$review_id' AND `meta_key` = 'review-scores' AND `meta_status` = 1 LIMIT 1");
                    if($review_scores) {
                        $review_scores = json_decode($review_scores, true);
                        $scores['task-2'] = $review_scores;
                    }
                }
            }
            $session->score = $scores;
        }

    } if( $quiz_category == 'ielts-speaking') {
        if($session->review == 1) {
            $review_id = $wpdb->get_var("SELECT `ID` FROM {$table_proqyz_v3_submissions_review} WHERE `result_id` = '$session->ID' AND `status` = 1 LIMIT 1");
            if($review_id) {
                # get review scores meta from review meta table using review_id
                $review_scores = $wpdb->get_var("SELECT `meta_value` FROM {$table_proqyz_v3_submissions_review_meta} WHERE `review_id` = '$review_id' AND `meta_key` = 'review-scores' AND `meta_status` = 1 LIMIT 1");
                if($review_scores) {
                    $review_scores = json_decode($review_scores, true);
                    $scores['tasks'] = $review_scores;
                }
            }
        }
        $session->score = $scores;

    } else {
        $score = $wpdb->get_var("SELECT `score_data` FROM {$table_proqyz_v3_progress_submissions_score} WHERE `submission_id` = '$session->ID' LIMIT 1");
        if( $score ) {
            $session->score = $score;
        }
    }
    
    return $session;
}
/**
 * user session check
 */
function proqyz_get_user_session_details($params = []) {
    if( is_user_logged_in()){
        global $wpdb, 
        $table_proqyz_v3_progress_submissions;
        $user_id            = get_current_user_id();
        $params             = (object) $params;
        $quiz_category      = $params->quiz_category;
        $api_id             = $params->quiz_id;
        $quiz_slug          = $params->quiz_slug;
        $session_category   = $params->session_category;
        $course_category    = $params->course_category;
        $course_id          = $params->course_id;
        
        $topic_id           = isset($params->topic_id)? $params->topic_id: null;
        $lesson_id          = isset($params->lesson_id)? $params->lesson_id: null;
        



        $filters_fixed  = " `user_id` = '$user_id' AND `quiz_category` = '$quiz_category' AND `api_id` = '$api_id' ";
        
        $filters        = "";
        if($session_category == "course"){
            $filters .= " AND `session_category` = '$session_category' AND `course_category` = '$course_category' AND `course_id` = '$course_id' ";
            if($topic_id !== null){
                $filters .= " AND `topic_id` = '$topic_id' ";
            }

            if($lesson_id !== null){
                $filters .= " AND `lesson_id` = '$lesson_id' ";
            }
        }



        $resume             = 0;
        $fresh              = 0;
        $retake             = 0;
        $recent             = 0;
        $result_id          = null;
        $result_session     = null;
        $fresh_result_id    = null;
        $fresh_session      = null;
        $recent_session     = null;
        $btn_type           = "take-test";
        # check first attempt session-------
        $first_attempt = $wpdb->get_row("SELECT * FROM {$table_proqyz_v3_progress_submissions} WHERE $filters_fixed $filters AND `session_type` = 'fresh' AND ( `session_status` = 1 OR `session_status` = 2 ) ORDER BY `$table_proqyz_v3_progress_submissions`.`date_created` DESC LIMIT 1");
        if( $first_attempt ) {
            // need to attach its meta 
            $first_attempt = proqyz_attach_meta_data_to_session($first_attempt);
            # this means first attempt is already done
            $fresh_result_id = $first_attempt->ID;
            $fresh_session   = (object) $first_attempt; # required for return
            $recent_session  = (object) $first_attempt;
            $recent          = 1;
            # check for retake complete
            $retake_attempt = $wpdb->get_row("SELECT * FROM {$table_proqyz_v3_progress_submissions} WHERE $filters_fixed $filters AND `session_type` = 'retake' AND (`session_status` = 1 OR `session_status` = 2 ) ORDER BY `$table_proqyz_v3_progress_submissions`.`date_created` DESC LIMIT 1");
            if( $retake_attempt ) {
                // need to attach its meta 
                $retake_attempt = proqyz_attach_meta_data_to_session($retake_attempt);
                # if take is already attempted check for resume session and get retake result
                $recent_result_id   = $retake_attempt->ID;
                $result_id          = $recent_result_id;    
                $result_session     = (object) $retake_attempt;
                $recent_session     = (object) $retake_attempt;
                $retake             = 1;
                $recent             = 1;
                # check for any resume session
                $retake_attempt_resume = $wpdb->get_row("SELECT `ID` FROM {$table_proqyz_v3_progress_submissions} WHERE $filters_fixed $filters AND `session_type` = 'retake' AND (`session_status` = 3 ) ORDER BY `$table_proqyz_v3_progress_submissions`.`date_created` DESC LIMIT 1");
                if( $retake_attempt_resume ) {
                    # resume available
                    $resume = 1;
                    $btn_type = "resume";
                } else {
                    # retake but fresh
                    $fresh = 1;
                    $btn_type = "retake";
                    
                }
            } else {
                $retake_attempt_resume = $wpdb->get_row("SELECT `ID` FROM {$table_proqyz_v3_progress_submissions} WHERE $filters_fixed $filters AND `session_type` = 'retake' AND (`session_status` = 3 ) ORDER BY `$table_proqyz_v3_progress_submissions`.`date_created` DESC LIMIT 1");
                if( $retake_attempt_resume ) {
                    # resume available
                    $resume = 1;
                    $btn_type = "resume";
                } else {
                    # retake but fresh
                    $fresh = 1;
                    $btn_type = "retake";
                    
                }
            }
        
        } else {
            $first_attempt_resume = $wpdb->get_row("SELECT `ID` FROM {$table_proqyz_v3_progress_submissions} WHERE $filters_fixed $filters AND `session_type` = 'fresh' AND ( `session_status` = 3 ) ORDER BY `$table_proqyz_v3_progress_submissions`.`date_created` DESC LIMIT 1"); 
            if( $first_attempt_resume ) {
                # resume avaible for fresh session
                $resume = 1;
                $btn_type = "resume";
            } else {
                # fresh session
                $fresh = 1;
                $btn_type = "take-test";
            }
        }

        return (object) [
            "status"             => 1,
            "fresh"              => $fresh,
            "resume"             => $resume,
            "retake"             => $retake,
            "fresh_session"      => $fresh_session,
            "retake_session"     => $result_session,
            "recent"             => $recent,
            "recent_session"     => $recent_session,
            "btn_type"           => $btn_type
        ];

    } else {
        return (object) [
            "status"             => 1,
            "fresh"              => 1,
            "resume"             => 0,
            "retake"             => 0,
            "fresh_session"      => null,
            "retake_session"     => null,
            "recent"             => 0,
            "recent_session"     => null,
            "btn_type"           => "take-test"
        ];
    }


}