<?php
/**
 * Main Loader Class
 *
 * @package Author_Website_Templates
 */

if (!defined('ABSPATH')) {
    exit;
}

final class Rswpthemes_Author_Website_Templates
{

    /**
     * Plugin Version
     */
    const VERSION = '1.0.7';

    /**
     * Minimum Elementor Version
     */
    const MINIMUM_ELEMENTOR_VERSION = '2.0.0';

    /**
     * Minimum PHP Version
     */
    const MINIMUM_PHP_VERSION = '7.0';

    /**
     * Instance
     */
    private static $_instance = null;

    /**
     * Instance
     */
    public static function instance()
    {
        if (is_null(self::$_instance)) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    /**
     * Constructor
     */
    public function __construct()
    {
        add_action('plugins_loaded', [$this, 'init']);
    }

    /**
     * Initialize the plugin
     */
    public function init()
    {

        // Check for required PHP version
        if (version_compare(PHP_VERSION, self::MINIMUM_PHP_VERSION, '<')) {
            add_action('admin_notices', ['AWT_Admin_Init', 'admin_notice_minimum_php_version']);
            return;
        }

        // Load Core Components
        $this->load_components();

        // Elementor-specific features
        if (did_action('elementor/loaded')) {
            // Check for required Elementor version
            if (!version_compare(ELEMENTOR_VERSION, self::MINIMUM_ELEMENTOR_VERSION, '>=')) {
                add_action('admin_notices', ['AWT_Admin_Init', 'admin_notice_minimum_elementor_version']);
                return;
            }

            // Register Elementor widgets
            add_action('elementor/widgets/register', [$this, 'init_widgets']);
        }

        // Core features
        add_action('wp_enqueue_scripts', [$this, 'enqueue_scripts'], 10);

        // Patterns
        add_action('init', [$this, 'register_pattern_category']);
        add_action('init', [$this, 'register_patterns']);

        // Templates
        add_filter('theme_page_templates', ['AWT_Template_Functions', 'register_canvas_template']);
        add_filter('template_include', ['AWT_Template_Functions', 'unified_template_loader'], 99);
        add_action('wp_enqueue_scripts', ['AWT_Template_Functions', 'canvas_assets'], 999);
    }

    /**
     * Load Components
     */
    private function load_components()
    {
        require_once RSWPTHEMES_AWT_PLUGIN_PATH . 'includes/helpers/utility-functions.php';
        require_once RSWPTHEMES_AWT_PLUGIN_PATH . 'includes/helpers/template-functions.php';

        require_once RSWPTHEMES_AWT_PLUGIN_PATH . 'includes/core/class-awt-blocks.php';
        require_once RSWPTHEMES_AWT_PLUGIN_PATH . 'includes/admin/admin-init.php';

        // Legacy / Current Includes (Keep these for now as per user instruction to only refactor specific parts or if needed)
        // The user instruction was "Modularize the code... New Structure Plan".
        // I will keep the existing requires that were not explicitly moved in the plan but are needed.
        require_once RSWPTHEMES_AWT_PLUGIN_PATH . 'includes/recommended-plugins-installer/plugins-installer.php';
        require_once RSWPTHEMES_AWT_PLUGIN_PATH . 'includes/download-image-from-url.php';
        require_once RSWPTHEMES_AWT_PLUGIN_PATH . 'includes/posts-shortcode/posts-shortcode.php';
        require_once RSWPTHEMES_AWT_PLUGIN_PATH . 'includes/header-helpers.php';
        require_once RSWPTHEMES_AWT_PLUGIN_PATH . 'includes/admin-settings.php';
        require_once RSWPTHEMES_AWT_PLUGIN_PATH . 'includes/context-manager.php';
        require_once RSWPTHEMES_AWT_PLUGIN_PATH . 'includes/meta-boxes.php';
        require_once RSWPTHEMES_AWT_PLUGIN_PATH . 'includes/book-list-renderer.php';
        require_once RSWPTHEMES_AWT_PLUGIN_PATH . 'includes/ajax-handler.php';
        require_once RSWPTHEMES_AWT_PLUGIN_PATH . 'includes/layout-renderers.php';
        require_once RSWPTHEMES_AWT_PLUGIN_PATH . 'includes/blog-helpers.php';
        require_once RSWPTHEMES_AWT_PLUGIN_PATH . 'themes-demoes/demo-setup.php';
    }

    public function enqueue_scripts()
    {
        // Common assets
        wp_register_style('owl-carousel', RSWPTHEMES_AWT_PLUGIN_URL . 'includes/assets/owl-carousel/owl-carousel.min.css', array(), '1.0.0');
        wp_register_script('owl-carousel', RSWPTHEMES_AWT_PLUGIN_URL . 'includes/assets/owl-carousel/owl-carousel.min.js', array('jquery'), '1.0.0');
        wp_enqueue_style('rswpthemes-awt-common-style', RSWPTHEMES_AWT_PLUGIN_URL . 'includes/assets/css/common.css', array(), '1.0.0');

        // Elementor assets
        if (did_action('elementor/loaded')) {
            // ... (Copying existing registration logic)
            wp_register_style('rswpthemes-awt-full-width-book-slider', RSWPTHEMES_AWT_PLUGIN_URL . 'elementor-widgets/full-width-book-slider/full-width-book-slider.css', array(), '1.0.0');
            wp_register_style('rswpthemes-awt-books-gallery', RSWPTHEMES_AWT_PLUGIN_URL . 'elementor-widgets/books-gallery/books-gallery.css', array(), '1.0.0');
            wp_register_style('rswpthemes-awt-posts-full-width-slider', RSWPTHEMES_AWT_PLUGIN_URL . 'elementor-widgets/posts-slider/slider.css', array(), '1.0.0');
            wp_register_style('rswpthemes-awt-posts-carousel', RSWPTHEMES_AWT_PLUGIN_URL . 'elementor-widgets/posts-carousel/posts-carousel.css', array(), '1.0.0');
            wp_register_style('rswpthemes-awt-about-section', RSWPTHEMES_AWT_PLUGIN_URL . 'elementor-widgets/about-section/about-section.css', array(), '1.0.0');
            wp_register_style('rswpthemes-awt-email-signup', RSWPTHEMES_AWT_PLUGIN_URL . 'elementor-widgets/signup-section/signup-section.css', array(), '1.0.0');
            wp_register_script('rswpthemes-awt-full-width-book-slider', RSWPTHEMES_AWT_PLUGIN_URL . 'elementor-widgets/full-width-book-slider/full-width-book-slider.js', array('jquery'), '1.0.0');
            wp_register_script('rswpthemes-awt-posts-full-width-slider', RSWPTHEMES_AWT_PLUGIN_URL . 'elementor-widgets/posts-slider/post-slider.js', array('jquery'), '1.0.0');
            wp_register_script('rswpthemes-awt-posts-carousel', RSWPTHEMES_AWT_PLUGIN_URL . 'elementor-widgets/posts-carousel/posts-carousel.js', array('jquery'), '1.0.0');
        }
    }

    public function register_pattern_category()
    {
        if (function_exists('register_block_pattern_category')) {
            register_block_pattern_category(
                'author-website-templates',
                array('label' => __('Author Website Templates', 'author-website-templates'))
            );
        }
    }

    public function register_patterns()
    {
        $patterns_dir = RSWPTHEMES_AWT_PLUGIN_PATH . 'patterns/';

        if (!is_dir($patterns_dir)) {
            return;
        }

        $category_dirs = glob($patterns_dir . '*', GLOB_ONLYDIR);

        if (empty($category_dirs)) {
            return;
        }

        foreach ($category_dirs as $category_dir) {

            $category_slug = basename($category_dir);

            $pattern_files = glob($category_dir . '/*.php');

            if (empty($pattern_files)) {
                continue;
            }

            foreach ($pattern_files as $pattern_file) {

                $pattern_data = get_file_data($pattern_file, array(
                    'title'       => 'Title',
                    'slug'        => 'Slug',
                    'description' => 'Description',
                    'categories'  => 'Categories',
                    'keywords'    => 'Keywords',
                ));

                ob_start();
                include $pattern_file;
                $pattern_content = ob_get_clean();

                // slug auto-generate
                if (empty($pattern_data['slug'])) {
                    $pattern_data['slug'] =
                        'author-website-templates/' .
                        $category_slug . '/' .
                        basename($pattern_file, '.php');
                }

                // categories priority:
                // 1) file header
                // 2) folder name
                $categories = !empty($pattern_data['categories'])
                    ? array_map('trim', explode(',', $pattern_data['categories']))
                    : array($category_slug);

                if (function_exists('register_block_pattern') && !empty($pattern_content)) {
                    register_block_pattern(
                        $pattern_data['slug'],
                        array(
                            'title'       => !empty($pattern_data['title'])
                                ? $pattern_data['title']
                                : basename($pattern_file, '.php'),

                            'description' => $pattern_data['description'],
                            'content'     => $pattern_content,
                            'categories'  => $categories,
                            'keywords'    => !empty($pattern_data['keywords'])
                                ? array_map('trim', explode(',', $pattern_data['keywords']))
                                : array(),
                        )
                    );
                }
            }
        }
    }


    public function init_widgets()
    {
        // Include Widget files (Relative to plugin root)
        require_once RSWPTHEMES_AWT_PLUGIN_PATH . 'elementor-widgets/full-width-book-slider/rswpthemes-awt-full-width-book-slider.php';
        require_once RSWPTHEMES_AWT_PLUGIN_PATH . 'elementor-widgets/about-section/rswpthemes-awt-about-section.php';
        require_once RSWPTHEMES_AWT_PLUGIN_PATH . 'elementor-widgets/signup-section/rswpthemes-awt-signup-section.php';
        require_once RSWPTHEMES_AWT_PLUGIN_PATH . 'elementor-widgets/books-gallery/rswpthemes-awt-books-gallery.php';
        require_once RSWPTHEMES_AWT_PLUGIN_PATH . 'elementor-widgets/book-reviews/rswpthemes-awt-book-reviews-slider.php';
        require_once RSWPTHEMES_AWT_PLUGIN_PATH . 'elementor-widgets/image/rswpthemes-awt-image-widget.php';
        require_once RSWPTHEMES_AWT_PLUGIN_PATH . 'elementor-widgets/posts-slider/rswpthemes-awt-posts-slider.php';
        require_once RSWPTHEMES_AWT_PLUGIN_PATH . 'elementor-widgets/posts-carousel/rswpthemes-awt-posts-carousel.php';
        require_once RSWPTHEMES_AWT_PLUGIN_PATH . 'elementor-widgets/book-carousel/rswpthemes-awt-book-carousel.php';

        // Register widgets
        if (class_exists('\Elementor\Plugin')) {
            \Elementor\Plugin::instance()->widgets_manager->register(new \Rswpthemes_Awt_Full_Width_Book_Slider());
            \Elementor\Plugin::instance()->widgets_manager->register(new \Rswpthemes_Awt_About_Section());
            \Elementor\Plugin::instance()->widgets_manager->register(new \Rswpthemes_Awt_Email_Signup_Widget());
            \Elementor\Plugin::instance()->widgets_manager->register(new \Rswpthemes_Awt_Book_Gallery());
            \Elementor\Plugin::instance()->widgets_manager->register(new \Rswpthemes_Awt_Book_Reviews_Slider());
            \Elementor\Plugin::instance()->widgets_manager->register(new \Rswpthemes_Awt_Widget_Image());
            \Elementor\Plugin::instance()->widgets_manager->register(new \Rswpthemes_Awt_Post_Sliders());
            \Elementor\Plugin::instance()->widgets_manager->register(new \Rswpthemes_Awt_Posts_Carousel());
            \Elementor\Plugin::instance()->widgets_manager->register(new \Rswpthemes_Awt_Book_Carousel());
        }
    }
}
