<?php
/**
 * Custom Post Type: Assessment Question
 *
 * Meta fields:
 * - _sea_cefr       : string  (A1, A2, B1, B2, C1, C2)
 * - _sea_age_tag    : string  (P1, P2, P3, P4, UL1, UL2, DSE)
 * - _sea_skill      : string  (reading, vocab, tenses, structure, age_grammar)
 * - _sea_correct    : string  (single letter or comma-separated)
 * - _sea_options    : JSON    (array of answer options)
 */
class SEA_Question_CPT {

    private static $instance = null;

    public static function instance() {
        if ( null === self::$instance ) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    private function __construct() {
        add_action( 'init', [ $this, 'register_cpt' ] );
        add_action( 'add_meta_boxes', [ $this, 'add_meta_boxes' ] );
        add_action( 'save_post_assessment_question', [ $this, 'save_meta' ] );
    }

    public function register_cpt() {
        $labels = [
            'name'               => __( 'Assessment Questions', 'simply-english-assessment' ),
            'singular_name'      => __( 'Question', 'simply-english-assessment' ),
            'add_new'            => __( 'Add New Question', 'simply-english-assessment' ),
            'add_new_item'       => __( 'Add New Question', 'simply-english-assessment' ),
            'edit_item'          => __( 'Edit Question', 'simply-english-assessment' ),
            'new_item'           => __( 'New Question', 'simply-english-assessment' ),
            'view_item'          => __( 'View Question', 'simply-english-assessment' ),
            'search_items'       => __( 'Search Questions', 'simply-english-assessment' ),
            'not_found'          => __( 'No questions found', 'simply-english-assessment' ),
            'not_found_in_trash' => __( 'No questions found in Trash', 'simply-english-assessment' ),
            'menu_name'          => __( 'Assessment Questions', 'simply-english-assessment' ),
        ];

        $args = [
            'labels'        => $labels,
            'public'        => false,
            'show_ui'       => true,
            'show_in_menu'  => true,
            'capability_type' => 'post',
            'hierarchical'  => false,
            'supports'      => [ 'title', 'editor' ],
            'menu_position' => 20,
            'menu_icon'     => 'dashicons-welcome-learn-more',
        ];

        register_post_type( 'assessment_question', $args );
    }

    public function add_meta_boxes() {
        add_meta_box(
            'sea_question_meta',
            __( 'Question Details', 'simply-english-assessment' ),
            [ $this, 'render_meta_box' ],
            'assessment_question',
            'normal',
            'high'
        );
    }

    public function render_meta_box( $post ) {
        wp_nonce_field( 'sea_save_meta', 'sea_meta_nonce' );

        $cefr    = get_post_meta( $post->ID, '_sea_cefr', true );
        $age_tag = get_post_meta( $post->ID, '_sea_age_tag', true );
        $skill   = get_post_meta( $post->ID, '_sea_skill', true );
        $correct = get_post_meta( $post->ID, '_sea_correct', true );
        $opts    = get_post_meta( $post->ID, '_sea_options', true );
        $opts    = is_string( $opts ) ? json_decode( $opts, true ) : [];

        $cefr_opts  = [ 'A1', 'A2', 'B1', 'B2', 'C1', 'C2' ];
        $age_opts   = [ 'P1', 'P2', 'P3', 'P4', 'UL1', 'UL2', 'DSE' ];
        $skill_opts = [ 'reading', 'vocab', 'tenses', 'structure', 'age_grammar' ];

        ?>
        <p>
            <label for="sea_cefr"><strong><?php esc_html_e( 'CEFR Level', 'simply-english-assessment' ); ?></strong></label><br>
            <select name="sea_cefr" id="sea_cefr" required>
                <option value=""><?php esc_html_e( '— Select —', 'simply-english-assessment' ); ?></option>
                <?php foreach ( $cefr_opts as $opt ) : ?>
                    <option value="<?php echo esc_attr( $opt ); ?>" <?php selected( $cefr, $opt ); ?>><?php echo esc_html( $opt ); ?></option>
                <?php endforeach; ?>
            </select>
        </p>

        <p>
            <label for="sea_age_tag"><strong><?php esc_html_e( 'Age / Simply English Tag', 'simply-english-assessment' ); ?></strong></label><br>
            <select name="sea_age_tag" id="sea_age_tag" required>
                <option value=""><?php esc_html_e( '— Select —', 'simply-english-assessment' ); ?></option>
                <?php foreach ( $age_opts as $opt ) : ?>
                    <option value="<?php echo esc_attr( $opt ); ?>" <?php selected( $age_tag, $opt ); ?>><?php echo esc_html( $opt ); ?></option>
                <?php endforeach; ?>
            </select>
        </p>

        <p>
            <label for="sea_skill"><strong><?php esc_html_e( 'Skill Area', 'simply-english-assessment' ); ?></strong></label><br>
            <select name="sea_skill" id="sea_skill" required>
                <option value=""><?php esc_html_e( '— Select —', 'simply-english-assessment' ); ?></option>
                <?php foreach ( $skill_opts as $opt ) : ?>
                    <option value="<?php echo esc_attr( $opt ); ?>" <?php selected( $skill, $opt ); ?>><?php echo esc_html( ucwords( str_replace( '_', ' ', $opt ) ) ); ?></option>
                <?php endforeach; ?>
            </select>
        </p>

        <p>
            <label for="sea_options"><strong><?php esc_html_e( 'Answer Options (JSON array)', 'simply-english-assessment' ); ?></strong></label><br>
            <textarea name="sea_options" id="sea_options" rows="3" style="width:100%;"><?php echo esc_textarea( json_encode( $opts, JSON_PRETTY_PRINT ) ); ?></textarea>
            <small><?php esc_html_e( 'Example: ["A","B","C","D"]', 'simply-english-assessment' ); ?></small>
        </p>

        <p>
            <label for="sea_correct"><strong><?php esc_html_e( 'Correct Answer(s)', 'simply-english-assessment' ); ?></strong></label><br>
            <input type="text" name="sea_correct" id="sea_correct" value="<?php echo esc_attr( $correct ); ?>" class="regular-text" placeholder="<?php esc_attr_e( 'e.g. B or A,C', 'simply-english-assessment' ); ?>">
            <br><small><?php esc_html_e( 'Enter a single letter for MCQ or a comma-separated list for multiple-answer questions.', 'simply-english-assessment' ); ?></small>
        </p>
        <?php
    }

    public function save_meta( $post_id ) {
        if ( ! isset( $_POST['sea_meta_nonce'] ) || ! wp_verify_nonce( $_POST['sea_meta_nonce'], 'sea_save_meta' ) ) {
            return;
        }
        if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
            return;
        }
        if ( ! current_user_can( 'edit_post', $post_id ) ) {
            return;
        }

        $fields = [
            '_sea_cefr'    => sanitize_text_field( $_POST['sea_cefr'] ?? '' ),
            '_sea_age_tag' => sanitize_text_field( $_POST['sea_age_tag'] ?? '' ),
            '_sea_skill'   => sanitize_text_field( $_POST['sea_skill'] ?? '' ),
            '_sea_correct' => sanitize_text_field( $_POST['sea_correct'] ?? '' ),
        ];

        foreach ( $fields as $key => $value ) {
            update_post_meta( $post_id, $key, $value );
        }

        if ( ! empty( $_POST['sea_options'] ) ) {
            $json    = wp_unslash( $_POST['sea_options'] );
            $decoded = json_decode( $json, true );
            if ( json_last_error() === JSON_ERROR_NONE ) {
                update_post_meta( $post_id, '_sea_options', wp_json_encode( $decoded ) );
            }
        }
    }
}
