<?php
/**
 * ST_ProQyz_Post_Permalinks
 *
 * @package ProQyz
 * @since   1.0.0
 */

defined( 'ABSPATH' ) || exit;

/**
 * Class ProQyz_Post_Permalinks
 */
class ST_ProQyz_Post_Permalinks {

    /**
     * ST_ProQyz_Post_Permalinks version.
     * @var string
     */
    public $version = '1.0.0';

    protected static $_instance = null;

    /**
     * The main base slug for the plugin's URLs.
     * @var string
     */
    protected $base_slug;

    /**
     * The slug for the course pages.
     * @var string
     */
    protected $course_slug;

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

    /**
     * Constructor method to initialize the plugin.
     */
    public function __construct() {
        // Initialize slugs from the database with default fallbacks.
        $this->base_slug   = get_option('proqyz_permalink_base', 'proqyz');
        $this->course_slug = get_option('proqyz_permalink_course', 'proqyz-course');

        add_filter('query_vars', [$this, 'proqyz_query_vars']);
        add_action('init', [$this, 'proqyz_add_rewrite_rule']);
        add_filter('template_include', [$this, 'custom_template_include']);
        
        // Hook for activation to set default options and flush rules.
        register_activation_hook(__FILE__, [$this, 'on_activation']);
        // Hook for deactivation to flush rules.
        register_deactivation_hook(__FILE__, [$this, 'flush_rewrite_rules']);
    }

    /**
     * Set default options on plugin activation.
     */
    public function on_activation() {
        // Add options only if they don't already exist to avoid overwriting user settings.
        add_option('proqyz_permalink_base', 'proqyz');
        add_option('proqyz_permalink_course', 'proqyz-course');
        $this->flush_rewrite_rules();
    }


    /**
     * Add custom query variables to WordPress.
     */
    public function proqyz_query_vars($query_vars) {
        $query_vars[] = 'action';
        $query_vars[] = 'page';
        $query_vars[] = 'page_type';
        $query_vars[] = 'lesson_id';
        $query_vars[] = 'course_id';
        $query_vars[] = 'course_type';
        $query_vars[] = 'quiz_category';
        $query_vars[] = 'quiz_id';
        $query_vars[] = 'quiz_slug';
        $query_vars[] = 'result_id';
        $query_vars[] = 'proqyz_course_id';
        $query_vars[] = 'type';
        return $query_vars;
    }

    /**
     * Add all custom rewrite rules.
     */
    public function proqyz_add_rewrite_rule() {
        $base   = $this->base_slug;
        $course = $this->course_slug;

        // Standalone quiz URL
        add_rewrite_rule(
            '^' . $base . '/quiz/([^/]+)/([^/]+)/([^/]+)/?([^/]*)$',
            'index.php?post_type=proqyz-quiz&quiz_category=$matches[1]&quiz_slug=$matches[2]&quiz_id=$matches[3]&action=$matches[4]&page=$matches[5]',
            'top'
        );

        // pre post result url
        add_rewrite_rule(
            '^' . $base . '/result-analyize/([^/]+)/([^/]+)/([^/]+)/([^/]+)/?$',
            'index.php?post_type=proqyz-quiz&quiz_category=$matches[1]&quiz_slug=$matches[2]&quiz_id=$matches[3]&result_id=$matches[4]',
            'top'
        );

        // Result and Review URLs
        add_rewrite_rule(
            '^' . $base . '/result/([^/]+)/([^/]+)/([^/]+)/([^/]+)/?$',
            'index.php?post_type=proqyz-quiz&quiz_category=$matches[1]&quiz_slug=$matches[2]&quiz_id=$matches[3]&result_id=$matches[4]',
            'top'
        );
        add_rewrite_rule(
            '^' . $base . '/review/([^/]+)/([^/]+)/([^/]+)/([^/]+)/?$',
            'index.php?post_type=proqyz-quiz&quiz_category=$matches[1]&quiz_slug=$matches[2]&quiz_id=$matches[3]&result_id=$matches[4]',
            'top'
        );
        
        // Main course page URL (using custom slugs)
        add_rewrite_rule(
            '^' . $base . '/' . $course . '/([^/]+)$',
            'index.php?post_type=proqyz-course&course_id=$matches[1]',
            'top'
        );
        
        // --- REFACTORED QUIZ-IN-COURSE RULES ---
        // The old generic rule has been replaced by the two specific rules below.

        // Rule #1: For your CUSTOM course type using the customizable slug.
        // It sets 'course_type' to 'proqyz-course' for your template logic.
        add_rewrite_rule(
            '^' . $base . '/course/' . $course . '/([^/]+)/([^/]+)/([^/]+)/([^/]+)/([^/]+)/?([^/]*)$',
            'index.php?post_type=proqyz-course&course_type=proqyz-course&course_id=$matches[1]&lesson_id=$matches[2]&quiz_category=$matches[3]&quiz_slug=$matches[4]&quiz_id=$matches[5]&action=$matches[6]',
            'top'
        );

        // Rule #2: For the STATIC LearnDash 'sfwd-course' type.
        // It uses the hardcoded 'sfwd-course' slug and sets the correct course_type.
        add_rewrite_rule(
            '^' . $base . '/course/sfwd-course/([^/]+)/([^/]+)/([^/]+)/([^/]+)/([^/]+)/?([^/]*)$',
            'index.php?post_type=proqyz-course&course_type=sfwd-course&course_id=$matches[1]&lesson_id=$matches[2]&quiz_category=$matches[3]&quiz_slug=$matches[4]&quiz_id=$matches[5]&action=$matches[6]',
            'top'
        );
        // --- END REFACTOR ---

        // Full mock test rules (updated to use custom slugs)
        add_rewrite_rule(
            '^' . $base . '/' . $course . '/([^/]+)/([^/]+)/simulation/general-guidance',
            'index.php?post_type=proqyz-course&page_type=proqyz-fullmock-test&course_id=$matches[1]&lesson_id=$matches[2]',
            'top'
        );
        add_rewrite_rule(
            '^' . $base . '/' . $course . '/([^/]+)/([^/]+)/simulation/quiz/([^/]+)/([^/]+)?$',
            'index.php?post_type=proqyz-course&page_type=proqyz-fullmock-test&course_id=$matches[1]&lesson_id=$matches[2]&quiz_category=$matches[3]&quiz_id=$matches[4]',
            'top'
        );
        add_rewrite_rule(
            '^' . $base . '/' . $course . '/([^/]+)/([^/]+)/simulation/result',
            'index.php?post_type=proqyz-course&page_type=proqyz-fullmock-test&course_id=$matches[1]&lesson_id=$matches[2]',
            'top'
        );

        add_rewrite_rule(
            '^' . $base . '/' . $course . '/([^/]+)/([^/]+)/simulation/result-analyize/([^/]+)/([^/]+)/?$',
            'index.php?post_type=proqyz-course&page_type=proqyz-fullmock-test&course_id=$matches[1]&lesson_id=$matches[2]&step=$matches[3]&result_id=$matches[4]',
            'top'
        );

        // Static URLs
        add_rewrite_rule(
            '^' . $base . '/result-message',
            'index.php?post_type=result-message',
            'top'
        );
        add_rewrite_rule(
            '^signup/complete-profile',
            'index.php?post_type=signup',
            'top'
        );
    }

    /**
     * Function to flush rewrite rules.
     */
    public function flush_rewrite_rules() {
        flush_rewrite_rules();
    }

    /**
     * Callback function to include the correct template file based on query variables.
     * This function doesn't need changes as it relies on query_vars, not the URL structure.
     */
    public function custom_template_include($template) {
        global $wp_query;

        $post_type = get_query_var('post_type');
        $page_type = get_query_var('page_type');

        if ( $post_type == "proqyz-course" ) {
            if ( $page_type == "proqyz-fullmock-test" ) {
                $custom_template = ST_PROQYZ_TEMPLATE_DIR . '/public/full-mock-test/full-mock-test-template.php';
                if (file_exists($custom_template)) {
                    return $custom_template;
                }
            } else {
                $custom_template = ST_PROQYZ_TEMPLATE_DIR . '/public/course/proqyz-course-frontend.php';
                if (file_exists($custom_template)) {
                    return $custom_template;
                }
            }
        } elseif ( $post_type == "proqyz-quiz" ) {
            $custom_template = ST_PROQYZ_TEMPLATE_DIR . '/public/quiz/proqyz-quiz-frontend.php';
            if (file_exists($custom_template)) {
                return $custom_template;
            }
        } elseif ( $post_type == "signup" ) {
            $custom_template = ST_PROQYZ_TEMPLATE_DIR . '/public/signup/signup-page-template.php';
            if (file_exists($custom_template)) {
                return $custom_template;
            }
        } elseif ( $post_type == "result-message") {
            $custom_template = ST_PROQYZ_TEMPLATE_DIR . '/public/result-page/proqyz-result-page-template.php';
            if (file_exists($custom_template)) {
                return $custom_template;
            }
        }

        return $template;
    }
}

// Instantiate the plugin class
return ST_ProQyz_Post_Permalinks::instance();