<?php 
/**
 * hooks which triggers on events
 */


/**
 * Function to replace placeholders in a string with corresponding values from an array of objects.
 *
 * @param string $content The content string with placeholders.
 * @param array $tasks An array of objects where keys are task properties and values are their corresponding data.
 * @return string The content string with placeholders replaced by corresponding values.
 */
function writing_replace_placeholders($content, $tasks) {
    // Find all placeholders in the content
    preg_match_all('/\{tasks\[(\d+)\]\[(.*?)\]\}/', $content, $matches, PREG_SET_ORDER);

    foreach ($matches as $match) {
        $task_index = (int)$match[1] - 1; // Convert to zero-based index
        $property = $match[2];
        $replacement = '';

        if (isset($tasks[$task_index])) {
            $task = $tasks[$task_index];

            if ($property === 'title' && isset($task->title)) {
                $replacement = $task->title;
            } elseif ($property === 'band' && isset($task->band)) {
                $replacement = $task->band;
            } elseif ($property === 'order' && isset($task->order)) {
                $replacement = $task->order;
            } elseif (strpos($property, 'score') === 0) {
                $score_index = (int)str_replace('score', '', $property) - 1;
                if (isset($task->scores[$score_index])) {
                    $replacement = $task->scores[$score_index];
                }
            }
        }

        $content = str_replace($match[0], $replacement, $content);
    }

    return $content;
}

/**
 * Function to replace additional placeholders in a string with corresponding values from an associative array.
 *
 * @param string $content The content string with placeholders.
 * @param array $replacements An associative array where keys are placeholders and values are replacements.
 * @return string The content string with placeholders replaced by corresponding values.
 */
function replace_additional_placeholders($content, $replacements) {
    foreach ($replacements as $placeholder => $replacement) {
        $content = str_replace($placeholder, $replacement, $content);
    }
    return $content;
}

/**
 * Function to send an email in WordPress.
 *
 * @param array $email_params The parameters for the email.
 * @return bool True if the email was sent successfully, false otherwise.
 */
function proqyz_send_custom_email($recipient, $subject, $content) {
    // Check if the required parameters are set
    if (!isset($recipient) || !isset($subject) || !isset($content)) {
        return false;
    }

    // Extract the parameters
    $recipient  = $recipient;
    $subject    = $subject;
    $content    = $content;

    // Sanitize the email subject
    $subject = sanitize_text_field($subject);

    // Set the email headers
    $headers  = 'MIME-Version: 1.0' . "\r\n";
    $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

    // Use wp_mail to send the email
    // 
    
    wp_mail($recipient, $subject, $content, $headers, array());
}




/**
 * trigger @var proqyz_quiz__on_finish
 * @var user_id
 * @var quiz_category
 * @var session_type
 * @var session_category
 * @var course_category
 * @var course_id
 * @var topic_id
 * @var lesson_id
 * @var api_id
 * @var result_url
 * @var quiz
*/


add_filter('proqyz_quiz__on_finish', 'proqyz_quiz__on_finish_callback', 10, 1);
function proqyz_quiz__on_finish_callback( $params = [] ) {
    $student_id = $params['user_id'];
    $quiz       = $params['quiz'];
    $result_url = $params['result_url'];

    if(!$student_id) { return; }

    # student info
    $student_info = get_userdata($student_id);
    // Check if user data is retrieved
    if ( !$student_info ){ return; }

    // Retrieve username and email
    $student_username       = $student_info->user_login;
    $student_email          = $student_info->user_email;

    // retrive quiz details
    $quiz_title                  = $quiz->title;
    $quiz_type                   = $quiz->_type;
    $quiz_category               = $quiz->_category;

    $module = "";
    if( $quiz_type == "ielts" && $quiz_category == "reading" ) {
        $module = "Reading";
    } else if( $quiz_type == "ielts" && $quiz_category == "listening" ) {
        $module = "Listening";
    } else if( $quiz_type == "ielts" && $quiz_category == "speaking" ) {
        $module = "Speaking";
    } else if( $quiz_type == "ielts" && $quiz_category == "writing" ) {
        $module = "Writing";
    } else if( $quiz_type == "gov" && ($quiz_category == "sectional-timing" || $quiz_category == "non-sectional-timing") ) {
        $module = "Competitive exam";
    }




    global $wpdb, $table_proqyz_groups;
    global $ST_EMAILS;


    $send_email = [];
    # if email trigger enable/disabled check
    $email_triggers = $ST_EMAILS;
    if( count($email_triggers) > 0 ) {
        foreach( $email_triggers as $trigger ) {
            if(in_array($trigger->post_name, ['on-test-submit-teacher','on-test-submit-owner','on-test-submit-student'])){
                $args = [
                    'name' => $trigger->post_name,
                    'post_type' => 'proqyz-email',
                    'post_status' => 'publish',
                    'posts_per_page' => 1,
                ];

                $posts = get_posts( $args );
                if ( !empty($posts) ) {
                    $trigger_id = $posts[0]->ID;
                    # check if trigger is enabled
                    $email_notification_enabled = get_post_meta($trigger_id,'_proqyz__email-notification-enabled',true);
                    # modified states variables
                    $email_notification_enabled = isset($email_notification_enabled)? $email_notification_enabled : 0;

                    if( $email_notification_enabled == 1 ) {

                        $email_recipient            = get_post_meta($trigger_id,'_proqyz__email-recipient',true);
                        $email_subject              = get_post_meta($trigger_id,'_proqyz__email-subject',true);
                        $email_content              = get_post_meta($trigger_id,'_proqyz__email-content',true);
                        

                        $email_recipient            = (isset($email_recipient))? (array) $email_recipient : [];
                        $email_subject              = (isset($email_subject))? $email_subject : 'Quiz completed';
                        $email_content              = (isset($email_content))? $email_content : '';

                        $send_email[] = (object) [
                            "trigger"       => $trigger->post_name,
                            "recipients"    => $email_recipient,
                            "subject"       => $email_subject,
                            "content"       => $email_content
                        ];

                    }


                    
                }
            }
        }
    }

    if( count( $send_email ) <= 0 ) { return; }

    /**
     * @var instructor name
     * @var instructor email
     * @var review[scores]
     * @var result_url
     * @var quiz_title
     * @var student name
     * @var student email
     */

    $common_replacements = [
        "{student_username}"    => $student_username,
        "{student_email}"       => $student_email,
        "{quiz_title}"          => $quiz_title,
        "{quiz_category}"       => $module,
        "{result_url}"          => $result_url
    ];
    

    if( count( $send_email ) > 0 ) {
        foreach( $send_email as $si => $se ) {
            $email_type         = $se->trigger;
            $email_subject      = $se->subject;
            $email_ids          = $se->recipients;
            $email_content      = $se->content;

            
            # other common params replacer
            $email_content = replace_additional_placeholders($email_content, $common_replacements);
            $email_subject = replace_additional_placeholders($email_subject, $common_replacements);


            # for student
            if( $email_type === "on-test-submit-student" ) {
                $response = proqyz_send_custom_email($student_email, $email_subject, $email_content);
                
            } else if( $email_type === "on-test-submit-teacher" ) {
                # needs params 
                # get associated teachers
                $teacher_ids = [];
                $groups = $wpdb->get_results("SELECT * FROM {$table_proqyz_groups} WHERE `status` = 1");
                if( count($groups) > 0 ) {
                    foreach( $groups as $gi => $group ) {
                        $student_ids_string = $group->student_ids;
                        $student_ids_arr    = explode(",", $student_ids_string);
                        $teacher_ids_string = $group->teacher_ids;
                        $teacher_ids_arr    = explode(",", $teacher_ids_string);

                        if( count($student_ids_arr) > 0 ) {
                            if(in_array($student_id, $student_ids_arr)) {
                                if( count($teacher_ids_arr) > 0 ) {
                                    foreach( $teacher_ids_arr as $tid ) {
                                        
                                        $teacher_ids[] = $tid;
                                    }
                                }
                            }
                        }
                    }
                }

                # find all teacher ids and there emails 
                if( count($teacher_ids) > 0 ) {
                    foreach( $teacher_ids as $tid ) {
                        $teacher_info = get_userdata($tid);
                        // Check if user data is retrieved
                        if ( $teacher_info ){
                            // Retrieve username and email
                            $teacher_username       = $teacher_info->user_login;
                            $teacher_email          = $teacher_info->user_email;
                            $teacher_roles          = $teacher_info->roles; // Get the user's roles

                            if (!in_array('administrator', $teacher_roles)) {
                                # replace the teacher/instructor replacers
                                $email_content_modified = replace_additional_placeholders($email_content, [
                                    "{teacher_username}"    => $teacher_username,
                                    "{teacher_email}"       => $teacher_email
                                ]);

                                $email_subject_modified = replace_additional_placeholders($email_subject, [
                                    "{teacher_username}"    => $teacher_username,
                                    "{teacher_email}"       => $teacher_email
                                ]);

                                # handle email
                                proqyz_send_custom_email($teacher_email, $email_subject_modified, $email_content_modified);
                            }
                            
                        }

                        
                    }
                }
                
                
            } else if( $email_type === "on-test-submit-owner" ) {

                # needs params 
                # for admin emails
                # for admin emails
                $admins = get_users(['role' => 'administrator']);
                foreach ($admins as $admin) {
                    $admin_username = $admin->user_login;
                    $admin_email    = $admin->user_email;

                    $email_content_modified = replace_additional_placeholders($email_content, [
                        "{admin_username}"    => $admin_username,
                        "{admin_email}"       => $admin_email
                    ]);

                    $email_subject_modified = replace_additional_placeholders($email_subject, [
                        "{admin_username}"    => $admin_username,
                        "{admin_email}"       => $admin_email
                    ]);

                    # handle email
                    proqyz_send_custom_email($admin_email, $email_subject_modified, $email_content_modified);
                    
                }
            } 
        }

        # final return 

    }



}

/**
 * trigger @var proqyz_quiz__on_evaluation_writing
 * @var user_id
 * @var result_id
*/
add_filter('proqyz_quiz__on_evaluation_writing', 'proqyz_quiz__on_evaluation_writing_callback', 10, 1);
function proqyz_quiz__on_evaluation_writing_callback( $params = [] ) {

    $student_id         = $params['user_id'];
    $result_id          = $params['result_id'];
    $teacher_id         = $params['reviewer_id'];
    $current_user_id    = get_current_user_id();
    

    if( !$student_id && !$result_id && !$teacher_id) { return; }

    if( $teacher_id == "-1" ) {
        $teacher_username    = "ProQyz AI";
        $teacher_email       = 'support@spacetree.org';
    } else {
        $teacher_info = get_userdata($teacher_id);
        // Check if user data is retrieved
        if ( !$teacher_info ){ return; }

        // Retrieve username and email
        $teacher_username    = $teacher_info->user_login;
        $teacher_email       = $teacher_info->user_email;
    }

    

    

    # student info
    $student_info = get_userdata($student_id);
    // Check if user data is retrieved
    if ( !$student_info ){ return; }

    // Retrieve username and email
    $student_username       = $student_info->user_login;
    $student_email          = $student_info->user_email;


    global $wpdb, 
	$table_proqyz_v3_progress_submissions,
	$table_proqyz_v3_progress_submissions_meta,
	$table_proqyz_groups, 
	$table_proqyz_v3_submissions_review,
	$table_proqyz_v3_submissions_review_meta;

    global $ST_EMAILS;

    if(count($ST_EMAILS) <= 0 ) { return; }

    $send_email         = [];
    $total_reviews      = [];
    $reviwed_section    = null;  
    
    

    # if email trigger enable/disabled check
    $email_triggers = $ST_EMAILS;
    if( count($email_triggers) > 0 ){
        foreach( $email_triggers as $trigger ) {
            if(in_array($trigger->post_name, [
                'on-writing-evaluation-owner',
                'on-writing-evaluation-teacher',
                'on-writing-evaluation-student'
            ])){

                $args = [
                    'name' => $trigger->post_name,
                    'post_type' => 'proqyz-email',
                    'post_status' => 'publish',
                    'posts_per_page' => 1,
                ];

                $posts = get_posts($args);
                if (!empty($posts)) {

                    $trigger_id = $posts[0]->ID;
                    # check if trigger is enabled
                    $email_notification_enabled = get_post_meta($trigger_id,'_proqyz__email-notification-enabled',true);
                    # modified states variables
                    $email_notification_enabled = isset($email_notification_enabled)? $email_notification_enabled : 0;

                    if( $email_notification_enabled == 1 ) {

                        $email_recipient            = get_post_meta($trigger_id,'_proqyz__email-recipient',true);
                        $email_subject              = get_post_meta($trigger_id,'_proqyz__email-subject',true);
                        $email_content              = get_post_meta($trigger_id,'_proqyz__email-content',true);

                        $email_recipient            = (isset($email_recipient))? (array) $email_recipient : [];
                        $email_subject              = (isset($email_subject))? $email_subject : 'Writing Evaluation';
                        $email_content              = (isset($email_content))? $email_content : '';

                        $send_email[] = (object) [
                            "trigger"       => $trigger->post_name,
                            "recipients"    => $email_recipient,
                            "subject"       => $email_subject,
                            "content"       => $email_content
                        ];
                        
                        

                    }


                    
                }
            }
        }
    }
    


    if( count( $send_email ) <= 0 ) { return; }
    

    # get quiz details data
    $quiz_title = null;
    $quiz_slug = null;
    $sections = [];
    # get result if exists by given result id
    $result = $wpdb->get_row("SELECT `ID`, `quiz_category`, `api_id` FROM {$table_proqyz_v3_progress_submissions} WHERE `ID` = '$result_id' AND `user_id` = '$student_id' LIMIT 1");
    $section_review = $wpdb->get_row("SELECT `section_id`, `ID` from {$table_proqyz_v3_submissions_review} WHERE `user_id` = '$student_id' AND `result_id` = '$result_id' AND `status` = 1 LIMIT 1");
    if( !$result || !$section_review) { return; }

    # get submission meta details meta_key (quiz_title, quiz_slug, sections)

    # get quiz title from submission meta table 
    $quiz_title_q = $wpdb->get_var("SELECT `meta_value` FROM {$table_proqyz_v3_progress_submissions_meta} WHERE `submission_id` = '$result_id' AND `meta_key` = 'quiz_title' LIMIT 1");
    if( $quiz_title_q ) {
        $quiz_title = $quiz_title_q->meta_value;
    }
    $quiz_slug_q = $wpdb->get_var("SELECT `meta_value` FROM {$table_proqyz_v3_progress_submissions_meta} WHERE `submission_id` = '$result_id' AND `meta_key` = 'quiz_slug' LIMIT 1");
    if( $quiz_slug_q ) {
        $quiz_slug = $quiz_slug_q->meta_value;
    }

    $sections_q = $wpdb->get_var("SELECT `meta_value` FROM {$table_proqyz_v3_progress_submissions_meta} WHERE `submission_id` = '$result_id' AND `meta_key` = 'sections' LIMIT 1");
    if( $sections_q ) {
        $sections = maybe_unserialize($sections_q);
        $sections = !empty($sections) ? (array) $sections : [];
    }


    # now get writing result details
    $section_id             = $section_review->section_id;
    $review_id              = $section_review->ID;
    $quiz_category          = $result->quiz_category;
    // $quiz_slug              = isset($quiz_obj->slug)? $quiz_obj->slug : null;
    $quiz_id                = $result->api_id;
    # update - slug
    $result_url             = st_proqyz_get_result_url( $quiz_category, $quiz_slug, $quiz_id, $result_id );
    

    $module = "";
    if( $quiz_category == "ielts-reading" ) {
        $module = "Reading";
    } else if( $quiz_category == "ielts-listening" ) {
        $module = "Listening";
    } else if( $quiz_category == "ielts-speaking" ) {
        $module = "Speaking";
    } else if( $quiz_category == "ielts-writing" ) {
        $module = "Writing";
    } else if( $quiz_category == "gov-non-sectional-timing" || $quiz_category == "gov-sectional-timing" ) {
        $module = "Competitive exam";
    }


    if( count( $sections ) > 0 ) {
        foreach( $sections as $skey => $section ) {
            $section = (object) $section;
            if( $section_id == $section->_id ) {
                
                $section_order      = $section->order;
                $section_title      = $section->title;
                
                $review_scores = $wpdb->get_row("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 ) {

                    $scores = (array) json_decode($review_scores->meta_value);
                    # Calculate the sum of the scores
                    $sum = array_sum($scores);
                    # Calculate the number of scores
                    $count = count($scores);
                    # Calculate the average
                    $average = $sum / $count;
                    # Round the average to the nearest half band or whole band
                    $rounded_average = round($average * 2) / 2;
                    
                    $reviwed_section    = (object) [
                        "task_title"                => $section_title,
                        "task_order"                => $section_order,
                        "score1"                    => $scores[0],
                        "score2"                    => $scores[1],
                        "score3"                    => $scores[2],
                        "score4"                    => $scores[3],
                        "overall_score"             => $rounded_average
                    ];
                }
            }
        }
    }
    

    if( $reviwed_section == null ) {
        return;
    }


    /**
     * @var {section[x][title]}
     * @var {section[x][order]}
     * @var {section[x][band]}
     * @var {section[x][score1]}
     * @var {section[x][score2]}
     * @var {section[x][score3]}
     * @var {section[x][score4]}
     * 
     * @var {quiz_title}
     * @var {student_name}
     * @var {student_email}
     * 
     * @var {teacher_name}
     * @var {teacher_email}
     * 
     * @var {admin_name}
     * @var {admin_email}
     * 
    */


    $common_replacements = [
        "{student_username}"    => $student_username,
        "{student_email}"       => $student_email,
        "{quiz_title}"          => $quiz_title,
        "{quiz_category}"       => $module,
        "{result_url}"          => $result_url,
        "{teacher_email}"       => $teacher_email,
        "{teacher_username}"    => $teacher_username,
        "{task_title}"          => $reviwed_section->task_title,
        "{task_order}"          => $reviwed_section->task_order,
        "{score1}"              => $reviwed_section->score1,
        "{score2}"              => $reviwed_section->score2,
        "{score3}"              => $reviwed_section->score3,
        "{score4}"              => $reviwed_section->score4,
        "{overall_score}"       => $reviwed_section->overall_score,

    ];

    if( count( $send_email ) > 0 ) {
        foreach( $send_email as $si => $se ) {
            $email_type         = $se->trigger;
            $email_subject      = $se->subject;
            $email_ids          = $se->recipients;
            $email_content      = $se->content;

            # other common params replacer
            $email_content      = replace_additional_placeholders($email_content, $common_replacements);
            $email_subject      = replace_additional_placeholders($email_subject, $common_replacements);

            # for student
            if( $email_type === "on-writing-evaluation-student" ) {
                # handle email
                proqyz_send_custom_email($student_email, $email_subject, $email_content);
            } elseif( $email_type === "on-writing-evaluation-teacher" ) {
                # for teachers
                proqyz_send_custom_email($teacher_email, $email_subject, $email_content);
            } elseif( $email_type === "on-writing-evaluation-owner" ) {
                # for admin emails
                $admins = get_users(['role' => 'administrator']);
                foreach ($admins as $admin) {
                    $admin_username = $admin->user_login;
                    $admin_email    = $admin->user_email;

                    $email_content_modified = replace_additional_placeholders($email_content, [
                        "{admin_username}"    => $admin_username,
                        "{admin_email}"       => $admin_email
                    ]);

                    $email_subject_modified = replace_additional_placeholders($email_subject, [
                        "{admin_username}"    => $admin_username,
                        "{admin_email}"       => $admin_email
                    ]);

                    # handle email
                    proqyz_send_custom_email($admin_email, $email_subject_modified, $email_content_modified);
                    
                }
            }  
        }

    }

}

/**
 * trigger @var proqyz_quiz__on_evaluation_speaking
 * @var user_id
 * @var result_id
*/
add_filter('proqyz_quiz__on_evaluation_speaking', 'proqyz_quiz__on_evaluation_speaking_callback', 10, 1);
function proqyz_quiz__on_evaluation_speaking_callback( $params = [] ) {

    $student_id         = $params['user_id'];
    $result_id          = $params['result_id'];
    $teacher_id         = $params['reviewer_id'];
    $current_user_id    = get_current_user_id();

    if( !$student_id && !$result_id && !$teacher_id) { return; }

    $teacher_info = get_userdata($teacher_id);
    // Check if user data is retrieved
    if ( !$teacher_info ){ return; }

    // Retrieve username and email
    $teacher_username    = $teacher_info->user_login;
    $teacher_email       = $teacher_info->user_email;

    # student info
    $student_info = get_userdata($student_id);
    // Check if user data is retrieved
    if ( !$student_info ){ return; }

    // Retrieve username and email
    $student_username       = $student_info->user_login;
    $student_email          = $student_info->user_email;

    

    global $wpdb, 
	$table_proqyz_v3_progress_submissions,
	$table_proqyz_v3_progress_submissions_meta,
	$table_proqyz_groups, 
	$table_proqyz_v3_submissions_review,
	$table_proqyz_v3_submissions_review_meta;
    global $ST_EMAILS;

    if(count($ST_EMAILS) <= 0 ) { return; }

    $send_email     = [];
    

    # if email trigger enable/disabled check
    $email_triggers = $ST_EMAILS;
    if( count($email_triggers) > 0 ){
        foreach( $email_triggers as $trigger ) {
            if(in_array($trigger->post_name, [
                'on-speaking-evaluation-owner',
                'on-speaking-evaluation-teacher',
                'on-speaking-evaluation-student'
            ])){

                $args = [
                    'name' => $trigger->post_name,
                    'post_type' => 'proqyz-email',
                    'post_status' => 'publish',
                    'posts_per_page' => 1,
                ];

                $posts = get_posts($args);
                if (!empty($posts)) {
                    $trigger_id = $posts[0]->ID;
                    # check if trigger is enabled
                    $email_notification_enabled = get_post_meta($trigger_id,'_proqyz__email-notification-enabled',true);
                    # modified states variables
                    $email_notification_enabled = isset($email_notification_enabled)? $email_notification_enabled : 0;

                    if( $email_notification_enabled == 1 ) {

                        $email_recipient            = get_post_meta($trigger_id,'_proqyz__email-recipient',true);
                        $email_subject              = get_post_meta($trigger_id,'_proqyz__email-subject',true);
                        $email_content              = get_post_meta($trigger_id,'_proqyz__email-content',true);

                        $email_recipient            = (isset($email_recipient))? (array) $email_recipient : [];
                        $email_subject              = (isset($email_subject))? $email_subject : 'Speaking Evaluation';
                        $email_content              = (isset($email_content))? $email_content : '';

                        $send_email[] = (object) [
                            "trigger"       => $trigger->post_name,
                            "recipients"    => $email_recipient,
                            "subject"       => $email_subject,
                            "content"       => $email_content
                        ];

                    }


                    
                }
            }
        }
    }
    

    if( count( $send_email ) <= 0 ) { return; }

    # get result if exists by given result id
    $result = $wpdb->get_row("SELECT `ID`, `quiz_category`, `api_id` FROM {$table_proqyz_v3_progress_submissions} WHERE `ID` = '$result_id' AND `user_id` = '$student_id' LIMIT 1");
    # get that section review
    $quiz_review = $wpdb->get_row("SELECT `ID` from {$table_proqyz_v3_submissions_review} WHERE `user_id` = '$student_id' AND `result_id` = '$result_id' AND `status` = 1 LIMIT 1");
    if( !$result || !$quiz_review ) { return; }

    # get quiz details data
    $quiz_title = null;
    $quiz_slug = null;
    $sections = [];
    $quiz_id  = $result->api_id;
    $quiz_category = $result->quiz_category;
    # get submission meta details meta_key (quiz_title, quiz_slug, sections)
    $quiz_title_q = $wpdb->get_var("SELECT `meta_value` FROM {$table_proqyz_v3_progress_submissions_meta} WHERE `submission_id` = '$result_id' AND `meta_key` = 'quiz_title' LIMIT 1");
    if( $quiz_title_q ) {
        $quiz_title = $quiz_title_q->meta_value;
    }
    $quiz_slug_q = $wpdb->get_var("SELECT `meta_value` FROM {$table_proqyz_v3_progress_submissions_meta} WHERE `submission_id` = '$result_id' AND `meta_key` = 'quiz_slug' LIMIT 1");
    if( $quiz_slug_q ) {
        $quiz_slug = $quiz_slug_q->meta_value;
    }
    $sections_q = $wpdb->get_var("SELECT `meta_value` FROM {$table_proqyz_v3_progress_submissions_meta} WHERE `submission_id` = '$result_id' AND `meta_key` = 'sections' LIMIT 1");
    if( $sections_q ) {
        $sections = maybe_unserialize($sections_q);
        $sections = !empty($sections) ? (array) $sections : [];
    }

    $module = "";
    if( $quiz_category == "ielts-reading" ) {
        $module = "Reading";
    } else if( $quiz_category == "ielts-listening" ) {
        $module = "Listening";
    } else if( $quiz_category == "ielts-speaking" ) {
        $module = "Speaking";
    } else if( $quiz_category == "ielts-writing" ) {
        $module = "Writing";
    } else if( $quiz_category == "gov-non-sectional-timing" || $quiz_category == "gov-sectional-timing" ) {
        $module = "Competitive exam";
    }

    # update - slug
    $result_url             = st_proqyz_get_result_url( $quiz_category, $quiz_slug, $quiz_id, $result_id );

    if( $quiz_review ) {
        $review_id = $quiz_review->ID;
        # get review details
        $review_scores = $wpdb->get_row("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 ) {

            $scores = (array) json_decode($review_scores->meta_value);
            $review_data['scores'] = $scores;

            # Calculate the sum of the scores
            $sum = array_sum($scores);
            # Calculate the number of scores
            $count = count($scores);
            # Calculate the average
            $average = $sum / $count;
            # Round the average to the nearest half band or whole band
            $rounded_average = round($average * 2) / 2;
            $review_data['band']   = $rounded_average; 

            
        }
    }



    /**
     * @var {quiz_title}
     * @var {student_name}
     * @var {student_email}
     * 
     * @var {teacher_name}
     * @var {teacher_email}
     * 
     * @var {admin_name}
     * @var {admin_email}
     * 
    */

    $common_replacements = [
        "{student_username}"    => $student_username,
        "{student_email}"       => $student_email,
        "{quiz_title}"          => $quiz_title,
        "{quiz_category}"       => $module,
        "{result_url}"          => $result_url,
        "{teacher_email}"       => $teacher_email,
        "{teacher_username}"    => $teacher_username,
        "{score1}"              => isset($review_data['scores'][0])? $review_data['scores'][0] : '', 
        "{score2}"              => isset($review_data['scores'][1])? $review_data['scores'][1] : '', 
        "{score3}"              => isset($review_data['scores'][2])? $review_data['scores'][2] : '', 
        "{score4}"              => isset($review_data['scores'][3])? $review_data['scores'][3] : '', 
        "{overall_score}"       => isset($review_data['band'])? $review_data['band'] : ''
    ];

    if( count( $send_email ) > 0 ) {
        foreach( $send_email as $si => $se ) {
            $email_type         = $se->trigger;
            $email_subject      = $se->subject;
            $email_ids          = $se->recipients;
            $email_content      = $se->content;

    
            # other common params replacer
            $email_content = replace_additional_placeholders($email_content, $common_replacements);
            $email_subject = replace_additional_placeholders($email_subject, $common_replacements);

            # for student
            if( $email_type === "on-speaking-evaluation-student" ) {
                # handle email
                proqyz_send_custom_email($student_email, $email_subject, $email_content);
            } elseif( $email_type === "on-speaking-evaluation-teacher" ) {
                # for teachers
                # handle email
                proqyz_send_custom_email($teacher_email, $email_subject, $email_content);
            } elseif( $email_type === "on-speaking-evaluation-owner" ) {
                # for admin emails
                # for admin emails
                $admins = get_users(['role' => 'administrator']);
                foreach ($admins as $admin) {
                    $admin_username = $admin->user_login;
                    $admin_email    = $admin->user_email;

                    $email_content_modified = replace_additional_placeholders($email_content, [
                        "{admin_username}"    => $admin_username,
                        "{admin_email}"       => $admin_email
                    ]);

                    $email_subject_modified = replace_additional_placeholders($email_subject, [
                        "{admin_username}"    => $admin_username,
                        "{admin_email}"       => $admin_email
                    ]);

                    # handle email
                    proqyz_send_custom_email($admin_email, $email_subject_modified, $email_content_modified);
                    
                }

            } 


        }
    }

}



