<?php

namespace MovieEngine\Utils;

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

class PageTemplates {
    private $templates;
    public function __construct() {
        add_filter('theme_page_templates', [$this, 'add_new_template']);

        add_filter('template_include', [$this, 'view_project_template']);
    }

    public function add_new_template($posts_templates) {
        $templates = [
            'page-dashboard.php'           => esc_html__('MovieEngine Dashboard', 'cine-movie-engine'),
            'template-container.php'       => esc_html__('MovieEngine Container', 'cine-movie-engine'),
            'template-container-fluid.php' => esc_html__('MovieEngine Container Fluid', 'cine-movie-engine'),
            'template-fullwidth.php'       => esc_html__('MovieEngine Full Width', 'cine-movie-engine'),
        ];
        $posts_templates = array_merge($posts_templates, $templates);
        return $posts_templates;
    }

    public function view_project_template($template) {
        $post_id = get_the_ID();
        if (!$post_id) {
            return $template;
        }

        $page_template = get_post_meta($post_id, '_wp_page_template', true);

        if (!$page_template) {
            return $template;
        }

        $valid_templates = [
            'page-dashboard.php',
            'template-container.php',
            'template-container-fluid.php',
            'template-fullwidth.php'
        ];

        if (!in_array($page_template, $valid_templates)) {
            return $template;
        }

        $file = '';
        if ($page_template === 'page-dashboard.php') {
            $file = MOVIE_ENGINE_PATH . 'templates/dashboard/page-dashboard.php';
        } elseif ($page_template === 'template-container.php') {
            $file = MOVIE_ENGINE_PATH . 'templates/page-templates/container.php';
        } elseif ($page_template === 'template-container-fluid.php') {
            $file = MOVIE_ENGINE_PATH . 'templates/page-templates/container-fluid.php';
        } elseif ($page_template === 'template-fullwidth.php') {
            $file = MOVIE_ENGINE_PATH . 'templates/page-templates/fullwidth.php';
        }

        if ($file && file_exists($file)) {
            return $file;
        }

        return $template;
    }
}
