<?php

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

/**
 * Handle audio creation for Speaking Test.
 */
class QC_Form_SFF_Learning_Mode_Test_VoiceMessageCreate
{

	public function __construct()
	{
		add_action('wp_ajax_wpvoicemessage_sff_learning_mode_test_send', [$this, 'wpvoicemessage_sff_learning_mode_test_send']);
		add_action('wp_ajax_nopriv_wpvoicemessage_sff_learning_mode_test_send', [$this, 'wpvoicemessage_sff_learning_mode_test_send']);
	}

	public function wpvoicemessage_sff_learning_mode_test_send()
	{

		check_ajax_referer('qcld_stt_test_nonce', 'nonce');

		if (empty($_POST)) {
			wp_die();
		}

		$cForm_id = filter_input(INPUT_POST, 'cform-id', FILTER_SANITIZE_NUMBER_INT);
		$level_index = filter_input(INPUT_POST, 'level_index', FILTER_SANITIZE_NUMBER_INT);
        $session_id = isset($_POST['session_id']) ? sanitize_text_field($_POST['session_id']) : '';
        $student_name = isset($_POST['student_name']) ? sanitize_text_field($_POST['student_name']) : '';
        $student_email = isset($_POST['student_email']) ? sanitize_email($_POST['student_email']) : '';

		$audio_file_path = $this->save_audio_file($cForm_id);

		if (!$audio_file_path) {
			wp_send_json_error('Failed to save audio');
		}

		$post_id = $this->create_record($cForm_id, $audio_file_path, $level_index, $session_id, $student_name, $student_email);

		if ($post_id) {
			$audio_url = str_replace(
				wp_normalize_path(untrailingslashit(ABSPATH)),
				site_url(),
				wp_normalize_path($audio_file_path)
			);

			wp_send_json_success([
				'post_id' => $post_id,
				'audio_url' => esc_url_raw($audio_url),
			]);
		}
		else {
			wp_send_json_error('Failed to create record');
		}

		wp_die();
	}

	private function create_record($cForm_id, $audio_file_path, $level_index, $session_id = '', $student_name = '', $student_email = '')
	{

		$post_author = is_user_logged_in() ? get_current_user_id() : 0;

		$post_id = wp_insert_post([
			'post_type' => 'qcvoicemsg_record',
			'post_title' => 'Speaking Test Result - ' . get_the_title($cForm_id) . ($session_id ? ' - ' . $session_id : ''),
			'post_status' => 'publish',
			'post_author' => $post_author,
		]);

		if ($post_id) {
			update_post_meta($post_id, 'qcld_wpvm_vmwpmdp_voicemssg_audio', wp_slash($audio_file_path));
			update_post_meta($post_id, 'vmwpmdp_cform_id', $cForm_id);
			update_post_meta($post_id, 'vmwpmdp_test_level_index', $level_index);
            update_post_meta($post_id, 'vmwpmdp_exam_session_id', $session_id);
            
            // Store the label for easier access in the results table
            $levels = get_post_meta($cForm_id, 'vmwpmdp_test_levels', true);
            if (is_array($levels) && isset($levels[$level_index])) {
                update_post_meta($post_id, 'vmwpmdp_test_level_label', $levels[$level_index]['label']);
            }

            if (is_user_logged_in() && empty($student_name)) {
                $current_user = wp_get_current_user();
                $first_name = $current_user->user_firstname;
                $last_name = $current_user->user_lastname;
                $full_name = trim( $first_name . ' ' . $last_name );
                
                $student_name = ! empty( $full_name ) ? $full_name : $current_user->display_name;
                $student_email = $current_user->user_email;
            }

            $additional_fields = [
                [
                    'label' => esc_html__('Name', 'qcld_wp_voice'),
                    'value' => $student_name,
                ],
                [
                    'label' => esc_html__('Email', 'qcld_wp_voice'),
                    'value' => $student_email,
                ],
            ];
            update_post_meta($post_id, 'vmwpmdp_additional_fields', json_encode($additional_fields));
		}

		return $post_id;
	}

	private function save_audio_file($cForm_id)
	{

		if (empty($_FILES['audio_data'])) {
			return false;
		}

		$upload_dir = wp_get_upload_dir();
		$upload_basedir = $upload_dir['basedir'] . '/wpvoicemessage/';

		if (!file_exists($upload_basedir)) {
			wp_mkdir_p($upload_basedir);
		}

		$unique_id = uniqid();
		$file_name = 'speaking_test_' . $cForm_id . '_' . $unique_id . '.wav';
		$file_path = $upload_basedir . $file_name;

		$file_tmp_name = $_FILES['audio_data']['tmp_name'];

		if (move_uploaded_file($file_tmp_name, $file_path)) {
			return $file_path;
		}

		return false;
	}

}

new QC_Form_SFF_Learning_Mode_Test_VoiceMessageCreate();
