<?php

/** Exit if accessed directly. */
if (!defined('ABSPATH')) {
    exit;
}

/**
 * Shortcode to display student's own results.
 */
function qcld_stt_learning_mode_results_f($atts)
{
    if (!is_user_logged_in()) {
        return '<p>' . esc_html__('Please log in to view your test results.', 'voice-widgets') . '</p>';
    }

    $current_user_id = get_current_user_id();
    $session_id = isset($_GET['session_id']) ? sanitize_text_field($_GET['session_id']) : '';

    if ($session_id) {
        return qcld_stt_render_student_session_detail($session_id, $current_user_id);
    }

    return qcld_stt_render_student_results_summary($current_user_id);
}
add_shortcode('qcld_stt_learning_mode_results', 'qcld_stt_learning_mode_results_f');


/**
 * Render summary list of exam sessions for the student.
 */
function qcld_stt_render_student_results_summary($user_id)
{
    $args = [
        'post_type'      => 'qcvoicemsg_record',
        'author'    => $user_id,
        'posts_per_page' => -1,
        'orderby'        => 'date',
        'order'          => 'DESC',
        'meta_query'     => [
            [
                'key'     => 'vmwpmdp_cform_id',
                'compare' => 'EXISTS',
            ]
        ]
    ];

    $records = get_posts($args);
    $sessions = [];

    foreach ($records as $post) {
        $sid = get_post_meta($post->ID, 'vmwpmdp_exam_session_id', true);
        $test_id = get_post_meta($post->ID, 'vmwpmdp_cform_id', true);
        
        // Group by session ID if available, otherwise fallback to test+date for legacy (though we mostly care about sessions now)
        $key = $sid ? $sid : 'legacy_' . $test_id . '_' . date('Ymd', strtotime($post->post_date));

        if (!isset($sessions[$key])) {
            $sessions[$key] = [
                'session_id'   => $sid,
                'test_title'   => $test_id ? get_the_title($test_id) : __('Unknown Test', 'voice-widgets'),
                'date'         => $post->post_date,
                'total_score'  => 0,
                'total_levels' => 0,
                'records_count'=> 0,
            ];
        }

        $score = (int)get_post_meta($post->ID, 'vmwpmdp_test_score', true);
        $sessions[$key]['total_score'] += $score;
        $sessions[$key]['total_levels']++;
        $sessions[$key]['records_count']++;
    }

    ob_start();
    ?>
    <div class="qcld-stt-student-dashboard">
        <h3><?php esc_html_e('Your Speaking Test Results', 'voice-widgets'); ?></h3>
        
        <?php if (empty($sessions)) : ?>
            <p><?php esc_html_e('You haven\'t taken any tests yet.', 'voice-widgets'); ?></p>
        <?php else : ?>
            <table class="qcld-stt-results-table" style="width:100%; border-collapse: collapse; margin-top: 20px;">
                <thead>
                    <tr style="background: #f4f4f4; text-align: left;">
                        <th style="padding: 12px; border-bottom: 2px solid #ddd;"><?php esc_html_e('Date', 'voice-widgets'); ?></th>
                        <th style="padding: 12px; border-bottom: 2px solid #ddd;"><?php esc_html_e('Test Name', 'voice-widgets'); ?></th>
                        <th style="padding: 12px; border-bottom: 2px solid #ddd;"><?php esc_html_e('Score', 'voice-widgets'); ?></th>
                        <th style="padding: 12px; border-bottom: 2px solid #ddd;"><?php esc_html_e('Action', 'voice-widgets'); ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($sessions as $key => $session) : ?>
                        <tr>
                            <td style="padding: 12px; border-bottom: 1px solid #eee;"><?php echo date('M j, Y H:i', strtotime($session['date'])); ?></td>
                            <td style="padding: 12px; border-bottom: 1px solid #eee;"><?php echo esc_html($session['test_title']); ?></td>
                            <td style="padding: 12px; border-bottom: 1px solid #eee;">
                                <strong><?php echo $session['total_score']; ?></strong> / <?php echo $session['total_levels'] * 100; ?>
                            </td>
                            <td style="padding: 12px; border-bottom: 1px solid #eee;">
                                <?php if ($session['session_id']) : ?>
                                    <a href="<?php echo add_query_arg('session_id', $session['session_id']); ?>" class="button"><?php esc_html_e('View Details', 'voice-widgets'); ?></a>
                                <?php else : ?>
                                    <span style="color:#999; font-size:0.9em;"><?php esc_html_e('No details', 'voice-widgets'); ?></span>
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        <?php endif; ?>
    </div>
    <style>
        .qcld-stt-results-table th { font-weight: bold; }
        .qcld-stt-results-table tr:hover { background: #f9f9f9; }
        .qcld-stt-student-dashboard .button { 
            background: #0073aa; color: #fff; text-decoration: none; padding: 5px 12px; border-radius: 4px; font-size: 0.9em;
        }
    </style>
    <?php
    return ob_get_clean();
}

/**
 * Render detailed breakdown for a specific exam session.
 */
function qcld_stt_render_student_session_detail($session_id, $user_id)
{
    $args = [
        'post_type'      => 'qcvoicemsg_record',
        'author'         => $user_id,
        'posts_per_page' => -1,
        'meta_query'     => [
            [
                'key'   => 'vmwpmdp_exam_session_id',
                'value' => $session_id,
            ]
        ],
        'orderby'        => 'meta_value_num',
        'meta_key'       => 'vmwpmdp_test_level_index',
        'order'          => 'ASC',
    ];

    $records = get_posts($args);

    if (empty($records)) {
        return '<p>' . esc_html__('Session not found.', 'voice-widgets') . '</p>';
    }

    $first_record = $records[0];
    $test_id = get_post_meta($first_record->ID, 'vmwpmdp_cform_id', true);

    ob_start();
    ?>
    <div class="qcld-stt-session-detail">
        <p><a href="<?php echo remove_query_arg('session_id'); ?>">&larr; <?php esc_html_e('Back to List', 'voice-widgets'); ?></a></p>
        <h3><?php echo get_the_title($test_id); ?> - <?php esc_html_e('Detail Results', 'voice-widgets'); ?></h3>
        <p style="color:#666;"><?php echo date('F j, Y g:i a', strtotime($first_record->post_date)); ?></p>

        <div class="vmwpmdp-results-list" style="margin-top: 30px;">
            <?php foreach ($records as $post) : 
                $label = get_post_meta($post->ID, 'vmwpmdp_test_level_label', true);
                $transcription = get_post_meta($post->ID, 'vmwpmdp_transcription_txt', true);
                $evaluation = get_post_meta($post->ID, 'vmwpmdp_test_evaluation', true);
                $score = get_post_meta($post->ID, 'vmwpmdp_test_score', true);
                $audio_path = get_post_meta($post->ID, 'qcld_wpvm_vmwpmdp_voicemssg_audio', true);
                
                $audio_url = '';
                if ($audio_path) {
                    $audio_url = str_replace(wp_normalize_path(untrailingslashit(ABSPATH)), site_url(), wp_normalize_path($audio_path));
                }

                $status_class = ($evaluation === 'pass') ? 'status-pass' : 'status-fail';

                $levels = get_post_meta( $test_id, 'vmwpmdp_test_levels', true );
                $level_index = get_post_meta( $post->ID, 'vmwpmdp_test_level_index', true );
                $target = ( is_array( $levels ) && isset( $levels[ $level_index ] ) ) ? $levels[ $level_index ]['text'] : '';
                ?>
                <div class="vmwpmdp-result-item" style="border: 1px solid #ddd; padding: 15px; margin-bottom: 20px; border-radius: 8px;">
                    <div style="display:flex; justify-content:space-between; align-items:center;">
                        <h4 style="margin:0;"><?php echo esc_html($label); ?></h4>
                        <span class="status-badge <?php echo $status_class; ?>" style="padding: 3px 10px; border-radius: 15px; font-size: 0.8em; font-weight: bold; text-transform: uppercase; color: #fff; background: <?php echo ($evaluation === 'pass' ? '#46b450' : '#d63638'); ?>;">
                            <?php echo esc_html($evaluation); ?>
                        </span>
                    </div>
                    
                    <div style="margin-top: 15px; font-size: 0.95em;">
                        <p><strong><?php esc_html_e( 'Target Sentence:', 'voice-widgets' ); ?></strong></p>
                        <p style="padding: 10px; background: #f0f6fb; border-left: 3px solid #0073aa;"><?php echo esc_html( $target ); ?></p>
                        <p><strong><?php esc_html_e('Your Transcription:', 'voice-widgets'); ?></strong><br>
                        <i style="color:#555;">「 <?php echo esc_html($transcription); ?> 」</i></p>
                        
                        <?php if ($audio_url) : ?>
                            <audio controls src="<?php echo esc_url($audio_url); ?>" style="height: 30px; margin: 10px 0;"></audio>
                        <?php endif; ?>
                        
                        <p><strong><?php esc_html_e('Score:', 'voice-widgets'); ?></strong> 
                        <span style="font-size: 1.2em; font-weight: bold; color: #0073aa;"><?php echo ($score !== '') ? intval($score) : '--'; ?></span> / 100</p>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    </div>
    <style>
        .qcld-stt-session-detail h3 { margin-bottom: 5px; }
        .vmwpmdp-result-item { background: #fff; box-shadow: 0 2px 5px rgba(0,0,0,0.05); }
    </style>
    <?php
    return ob_get_clean();
}
