<?php

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

/**
 * Register Voice Test Custom Post Type and its settings.
 */
class WPVoice_VoiceTestForm {

	private static $instance;

	private function __construct() {
		add_action( 'init', [ $this, 'register_post_type' ] );
		add_action( 'add_meta_boxes', [ $this, 'add_meta_box' ] );
		add_action( 'save_post', [ $this, 'save_metabox' ] );
		
		add_filter( 'manage_voicemssg_test_qcwp_posts_columns', [ $this, 'posts_columns' ] );
		add_action( 'manage_voicemssg_test_qcwp_posts_custom_column', [ $this, 'posts_custom_column' ], 10, 2 );
        add_action( 'admin_footer', [ $this, 'admin_footer_js' ] );
	}

	public static function get_instance() {
		if ( ! isset( self::$instance ) && ! ( self::$instance instanceof WPVoice_VoiceTestForm ) ) {
			self::$instance = new WPVoice_VoiceTestForm;
		}

		return self::$instance;
	}

	public function register_post_type() {

		$labels = [
			'name'               => esc_html__( 'Speaking Tests', 'voice-widgets' ),
			'singular_name'      => esc_html__( 'Speaking Test', 'voice-widgets' ),
			'add_new'            => esc_html__( 'Add New Test', 'voice-widgets' ),
			'add_new_item'       => esc_html__( 'Add New Speaking Test', 'voice-widgets' ),
			'edit_item'          => esc_html__( 'Edit Speaking Test', 'voice-widgets' ),
			'new_item'           => esc_html__( 'New Speaking Test', 'voice-widgets' ),
			'view_item'          => esc_html__( 'View Speaking Test', 'voice-widgets' ),
			'search_items'       => esc_html__( 'Search Speaking Tests', 'voice-widgets' ),
			'not_found'          => esc_html__( 'No speaking tests found', 'voice-widgets' ),
			'not_found_in_trash' => esc_html__( 'No speaking tests found in Trash', 'voice-widgets' ),
			'parent_item_colon'  => esc_html__( 'Parent Speaking Test:', 'voice-widgets' ),
			'menu_name'          => esc_html__( 'Speaking Tests', 'voice-widgets' ),
		];

		$args = [
			'labels'              => $labels,
			'hierarchical'        => false,
			'description'         => esc_html__( 'Voice Speaking Tests', 'voice-widgets' ),
			'supports'            => [ 'title' ],
			'public'              => false,
			'show_ui'             => true,
			'show_in_menu'        => 'edit.php?post_type=wp_voicemsg_record',
			'show_in_nav_menus'   => false,
			'publicly_queryable'  => false,
			'exclude_from_search' => true,
			'has_archive'         => false,
			'query_var'           => true,
			'can_export'          => true,
			'rewrite'             => true,
			'capability_type'     => 'post',
		];

		register_post_type( 'voicemssg_test_qcwp', $args );

	}

	public function add_meta_box() {

		add_meta_box(
			'vmwpmdp_test_options',
			esc_html__( 'Speaking Test Options', 'voice-widgets' ),
			[ $this, 'render_test_options_metabox' ],
			'voicemssg_test_qcwp',
			'normal',
			'high'
		);

	}

	public function render_test_options_metabox( $post ) {

		wp_nonce_field( 'vmwpmdp_test_options_save', 'vmwpmdp_test_options_nonce' );

		$levels = get_post_meta( $post->ID, 'vmwpmdp_test_levels', true );
		if ( ! is_array( $levels ) || empty( $levels ) ) {
            // Check legacy data
            $easy = get_post_meta( $post->ID, 'vmwpmdp_easy_level_words', true );
            $hard = get_post_meta( $post->ID, 'vmwpmdp_hard_level_words', true );
            if ( $easy || $hard ) {
                $levels = [];
                if ( $easy ) $levels[] = [ 'label' => 'Easy', 'text' => $easy ];
                if ( $hard ) $levels[] = [ 'label' => 'Hard', 'text' => $hard ];
            } else {
			    $levels = [ [ 'label' => 'Level 1', 'text' => '' ] ];
            }
		}
		
		?>
		<div class="vmwpmdp-metabox-content">
            <p class="description"><?php esc_html_e( 'Add multiple sentences for this speaking test. Each sentence will be shown as a level on the frontend.', 'voice-widgets' ); ?></p>
            
            <div id="vmwpmdp-test-levels-repeater">
                <?php foreach ( $levels as $index => $level ) : ?>
                    <div class="vmwpmdp-level-row" style="border: 1px solid #ddd; padding: 15px; margin-bottom: 10px; background: #f9f9f9;">
                        <p>
                            <label><strong><?php esc_html_e( 'Level Label (e.g. Phase 1):', 'voice-widgets' ); ?></strong></label><br>
                            <input type="text" name="vmwpmdp_test_levels[<?php echo $index; ?>][label]" value="<?php echo esc_attr( $level['label'] ); ?>" style="width:100%;">
                        </p>
                        <p>
                            <label><strong><?php esc_html_e( 'Level Sentence:', 'voice-widgets' ); ?></strong></label><br>
                            <textarea name="vmwpmdp_test_levels[<?php echo $index; ?>][text]" rows="3" style="width:100%;"><?php echo esc_textarea( $level['text'] ); ?></textarea>
                        </p>
                        <p style="text-align: right; margin-bottom: 0;">
                            <button type="button" class="button vmwpmdp-remove-level" style="color: #d63638; border-color: #d63638;"><?php esc_html_e( 'Remove Level', 'voice-widgets' ); ?></button>
                        </p>
                    </div>
                <?php endforeach; ?>
            </div>

            <p>
                <button type="button" id="vmwpmdp-add-level" class="button button-primary"><?php esc_html_e( 'Add New Level', 'voice-widgets' ); ?></button>
            </p>

			<hr>
			<p>
				<strong><?php esc_html_e( 'Shortcode:', 'voice-widgets' ); ?></strong><br>
				<code>[qcld_stt_learning_mode_test id="<?php echo $post->ID; ?>"]</code><br>
                <span class="description"><?php esc_html_e( 'Use this shortcode to show all active levels on any page.', 'voice-widgets' ); ?></span>
			</p>
		</div>

        <script type="text/template" id="vmwpmdp-level-row-template">
            <div class="vmwpmdp-level-row" style="border: 1px solid #ddd; padding: 15px; margin-bottom: 10px; background: #f9f9f9;">
                <p>
                    <label><strong><?php esc_html_e( 'Level Label (e.g. Phase {n}):', 'voice-widgets' ); ?></strong></label><br>
                    <input type="text" name="vmwpmdp_test_levels[{n}][label]" value="Level {n}" style="width:100%;">
                </p>
                <p>
                    <label><strong><?php esc_html_e( 'Level Sentence:', 'voice-widgets' ); ?></strong></label><br>
                    <textarea name="vmwpmdp_test_levels[{n}][text]" rows="3" style="width:100%;"></textarea>
                </p>
                <p style="text-align: right; margin-bottom: 0;">
                    <button type="button" class="button vmwpmdp-remove-level" style="color: #d63638; border-color: #d63638;"><?php esc_html_e( 'Remove Level', 'voice-widgets' ); ?></button>
                </p>
            </div>
        </script>
		<?php

	}

	public function save_metabox( $post_id ) {

		if ( ! isset( $_POST['vmwpmdp_test_options_nonce'] ) || ! wp_verify_nonce( $_POST['vmwpmdp_test_options_nonce'], 'vmwpmdp_test_options_save' ) ) {
			return;
		}

		if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
			return;
		}

		if ( ! current_user_can( 'edit_post', $post_id ) ) {
			return;
		}

		if ( isset( $_POST['vmwpmdp_test_levels'] ) && is_array( $_POST['vmwpmdp_test_levels'] ) ) {
            $levels = [];
            foreach ( $_POST['vmwpmdp_test_levels'] as $level ) {
                if ( ! empty( $level['text'] ) ) {
                    $levels[] = [
                        'label' => sanitize_text_field( $level['label'] ),
                        'text'  => sanitize_textarea_field( $level['text'] ),
                    ];
                }
            }
			update_post_meta( $post_id, 'vmwpmdp_test_levels', $levels );
		} else {
            delete_post_meta( $post_id, 'vmwpmdp_test_levels' );
        }

	}

	public function posts_columns( $columns ) {
		$new_columns = [];
		foreach ( $columns as $key => $value ) {
			$new_columns[ $key ] = $value;
			if ( $key === 'title' ) {
				$new_columns['shortcode'] = esc_html__( 'Shortcode', 'voice-widgets' );
			}
		}
		return $new_columns;
	}

	public function posts_custom_column( $column, $post_id ) {
		if ( $column === 'shortcode' ) {
			echo '<p><code>[qcld_stt_learning_mode_test id="' . $post_id . '"]</code></p>';
		}
	}

    public function admin_footer_js() {
        $screen = get_current_screen();
        if ( $screen && $screen->post_type === 'voicemssg_test_qcwp' ) {
            ?>
            <script type="text/javascript">
                jQuery(document).ready(function($) {
                    $('#vmwpmdp-add-level').on('click', function() {
                        var count = $('#vmwpmdp-test-levels-repeater .vmwpmdp-level-row').length;
                        var template = $('#vmwpmdp-level-row-template').html();
                        var html = template.replace(/{n}/g, count);
                        $('#vmwpmdp-test-levels-repeater').append(html);
                    });

                    $(document).on('click', '.vmwpmdp-remove-level', function() {
                        if (confirm('Are you sure you want to remove this level?')) {
                            $(this).closest('.vmwpmdp-level-row').remove();
                        }
                    });
                });
            </script>
            <?php
        }
    }

}
