<?php

namespace MovieEngine\Frontend;

if (! defined("ABSPATH")) {
    exit; // Exit if accessed directly
}

class ReviewRouter {

    public function __construct() {
        add_action('init', [$this, 'add_rewrite_endpoints']);
        add_action('template_redirect', [$this, 'force_load_reviews_template']);
        add_action('admin_init', [$this, 'maybe_flush_rewrite_rules']);
    }

    public function maybe_flush_rewrite_rules() {
        if (get_option('movie_engine_flush_rewrite_rules')) {
            flush_rewrite_rules();
            delete_option('movie_engine_flush_rewrite_rules');
        }
    }


    public function add_rewrite_endpoints() {
        add_rewrite_endpoint('reviews', EP_ALL);
    }


    public function force_load_reviews_template() {
        global $wp_query;

        if (isset($wp_query->query_vars['reviews']) && is_singular(['movie_engine_movie', 'movie_engine_series', 'movie_engine_episode'])) {

            $custom_template = MOVIE_ENGINE_PATH . 'templates/pages/single-reviews.php';

            if (file_exists($custom_template)) {
                include $custom_template;
                exit;
            }
        }
    }
}
