<?php
if (!defined('ABSPATH')) exit;

class WPBS_Template {

    public static function init() {
        add_filter('template_include', [__CLASS__, 'maybe_override_template']);
        add_filter('theme_page_templates', [__CLASS__, 'register_template']);
        add_filter('theme_post_templates', [__CLASS__, 'register_template']);
    }

    /**
     * Add "Bootstrap Studio" to the page/post template dropdown
     */
    public static function register_template($templates) {
        $templates['bootstrap-studio'] = 'Bootstrap Studio';
        return $templates;
    }

    /**
     * Use our template when selected from the dropdown or when _wpbs_enabled is checked
     */
    public static function maybe_override_template($template) {
        if (!is_singular()) return $template;

        $post_id = get_the_ID();

        // Check if our template was selected from the dropdown
        $selected = get_page_template_slug($post_id);
        $use_ours = ($selected === 'bootstrap-studio');

        // Also check the legacy _wpbs_enabled checkbox
        if (!$use_ours) {
            $use_ours = (bool) get_post_meta($post_id, '_wpbs_enabled', true);
        }

        if (!$use_ours) return $template;

        $custom_template = WPBS_PLUGIN_DIR . 'templates/bootstrap-page.php';
        if (file_exists($custom_template)) {
            return $custom_template;
        }

        return $template;
    }
}
