<?php

namespace MovieEngine\Utils;

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

class TemplateLoader {

    const THEME_TEMPLATE_FOLDER = 'movie-engine';
    public function __construct() {
        add_filter('template_include', [$this, 'template_loader'], 999);
        add_filter('theme_page_templates', [$this, 'register_page_templates']);
    }
    public function register_page_templates($templates) {
        $templates['template-container.php'] = esc_html__('MovieEngine Container', 'cine-movie-engine');
        $templates['template-container-fluid.php'] = esc_html__('MovieEngine Container Fluid', 'cine-movie-engine');
        $templates['template-fullwidth.php'] = esc_html__('MovieEngine Full Width', 'cine-movie-engine');
        return $templates;
    }

    public function template_loader($template) {
        $post_type = get_post_type();
        $movie_engine_taxonomies = [
            'movie_engine_genre',
            'movie_engine_year',
            'movie_engine_quality',
            'movie_engine_tv_quality',
            'movie_engine_cast',
            'movie_engine_director',
            'movie_engine_creator',
            'movie_engine_country',
            'movie_engine_language',
            'movie_engine_studio',
            'movie_engine_network',
            'movie_engine_tag'
        ];

        foreach ($movie_engine_taxonomies as $taxonomy) {
            if (is_tax($taxonomy)) {
                $tax_slug = str_replace('movie_engine_', '', $taxonomy);
                $specific_template = $this->get_template_path("taxonomy-{$tax_slug}.php");
                if (file_exists($specific_template)) {
                    return $specific_template;
                }
                $generic_tax_template = $this->get_template_path('taxonomy.php');
                if (file_exists($generic_tax_template)) {
                    return $generic_tax_template;
                }
            }
        }

        if (in_array($post_type, ['movie_engine_movie', 'movie_engine_series', 'movie_engine_episode', 'movie_engine_person'])) {
            $type_slug = str_replace('movie_engine_', '', $post_type);

            if (is_single()) {
                $new_template = $this->get_template_path("single-{$type_slug}.php");
                if (file_exists($new_template)) {
                    $template = $new_template;
                }
            } elseif (is_archive()) {
                $new_template = $this->get_template_path("archive-{$type_slug}.php");
                if (file_exists($new_template)) {
                    $template = $new_template;
                }
            }
        }

        $is_movie_search = false;

        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        if (is_search() || isset($_GET['s'])) {
            $is_movie_search = true;
        }

        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        if (isset($_GET['movie_engine_search']) && $_GET['movie_engine_search'] === '1') {
            $is_movie_search = true;
        }

        if ($is_movie_search) {
            $template = $this->get_template_path('search.php');
        }

        if (is_page()) {
            $page_template = get_post_meta(get_the_ID(), '_wp_page_template', true);
            $template_map = [
                'template-container.php' => 'page-templates/container.php',
                'template-container-fluid.php' => 'page-templates/container-fluid.php',
                'template-fullwidth.php' => 'page-templates/fullwidth.php'
            ];
            if (isset($template_map[$page_template])) {
                $new_template = $this->get_template_path($template_map[$page_template]);
                if (file_exists($new_template)) {
                    return $new_template;
                }
            }
        }
        return $template;
    }


    public static function get_template_path($template_name, $template_path = '') {
        if (! $template_path) {
            $template_path = self::THEME_TEMPLATE_FOLDER;
        }
        if (strpos($template_name, '..') !== false) {
            return '';
        }
        $safe_template_name = $template_name;

        if (substr($safe_template_name, -4) !== '.php') {
            return '';
        }
        $theme_template = locate_template([
            trailingslashit($template_path) . $safe_template_name,
        ]);

        if ($theme_template) {
            return $theme_template;
        }
        return MOVIE_ENGINE_PATH . 'templates/' . $safe_template_name;
    }

    public static function get_template_part($slug, $name = '', $args = []) {
        $template = '';
        if ($name && ! empty($slug)) {
            $template = self::get_template_path("{$slug}-{$name}.php");
        }
        if (! $template && ! empty($slug)) {
            $template = self::get_template_path("{$slug}.php");
        }
        $template = apply_filters('movie_engine_get_template_part', $template, $slug, $name);
        if ($template && file_exists($template)) {
            if (! empty($args) && is_array($args)) {
                extract($args, EXTR_SKIP);

                foreach ($args as $key => $value) {
                    set_query_var($key, $value);
                }
            }
            include $template;
        }
    }
}
