<?php

namespace MovieEngine\Frontend;

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

/**
 * Handle redirections for Official Pages
 */
class Redirects {

    public function __construct() {
        add_action('template_redirect', [$this, 'handle_archive_redirection']);
    }

    public function handle_archive_redirection() {
        if (!is_archive() && !is_post_type_archive()) {
            return;
        }

        if (defined('MOVIE_ENGINE_DOING_REDIRECT')) {
            return;
        }

        global $wp;
        $current_url = home_url(add_query_arg([], $wp->request));
        $options = get_option('movie_engine_design_settings', []);
        $current_id = get_queried_object_id();

        if (is_post_type_archive('movie_engine_movie')) {
            $movie_page_id = isset($options['movie_archive_page']) ? absint($options['movie_archive_page']) : 0;
            if ($movie_page_id && get_post_status($movie_page_id) === 'publish' && $current_id !== $movie_page_id) {
                $redirect_url = get_permalink($movie_page_id);
                if ($redirect_url && rtrim($current_url, '/') !== rtrim($redirect_url, '/')) {
                    define('MOVIE_ENGINE_DOING_REDIRECT', true);
                    wp_safe_redirect($redirect_url, 301);
                    exit;
                }
            }
        }

        if (is_post_type_archive('movie_engine_series')) {
            $series_page_id = isset($options['series_archive_page']) ? absint($options['series_archive_page']) : 0;
            if ($series_page_id && get_post_status($series_page_id) === 'publish' && $current_id !== $series_page_id) {
                $redirect_url = get_permalink($series_page_id);
                if ($redirect_url && rtrim($current_url, '/') !== rtrim($redirect_url, '/')) {
                    define('MOVIE_ENGINE_DOING_REDIRECT', true);
                    wp_safe_redirect($redirect_url, 301);
                    exit;
                }
            }
        }

        if (is_post_type_archive('movie_engine_person')) {
            $person_page_id = isset($options['person_archive_page']) ? absint($options['person_archive_page']) : 0;
            if ($person_page_id && get_post_status($person_page_id) === 'publish' && $current_id !== $person_page_id) {
                $redirect_url = get_permalink($person_page_id);
                if ($redirect_url && rtrim($current_url, '/') !== rtrim($redirect_url, '/')) {
                    define('MOVIE_ENGINE_DOING_REDIRECT', true);
                    wp_safe_redirect($redirect_url, 301);
                    exit;
                }
            }
        }
    }
}
