<?php
/**
 * Template Functions
 *
 * @package Author_Website_Templates
 */

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

class AWT_Template_Functions
{

    /**
     * Register Canvas Page Template
     */
    public static function register_canvas_template($templates)
    {
        $templates['awt-canvas'] = __('AWT Canvas (No Header/Footer)', 'author-website-templates');
        return $templates;
    }

    /**
     * Unified Template Loader
     */
    public static function unified_template_loader($template)
    {
        // Canvas Page Template
        if (is_page_template('awt-canvas')) {
            $canvas_template = RSWPTHEMES_AWT_PLUGIN_PATH . 'includes/templates/canvas.php';
            if (file_exists($canvas_template)) {
                return $canvas_template;
            }
        }

        $awt_settings = get_option('awt_global_settings', []);


        // Theme Side Implementation Example:
        $single_book_template_id = $awt_settings['awt_book_single_template_id'] ?? '';
        // Single Book Template
        if ($single_book_template_id && is_singular('book')) {
            $book_template = RSWPTHEMES_AWT_PLUGIN_PATH . 'includes/templates/single-book.php';
            if (file_exists($book_template)) {
                return $book_template;
            }
        }

        $archive_book_template_id = $awt_settings['awt_book_archive_template_id'] ?? '';

        // Book Archive Template
        if ((is_post_type_archive('book') || is_tax('book-category') || is_tax('book-author') || is_tax('book-series')) && !empty($archive_book_template_id)) {
            $archive_template = RSWPTHEMES_AWT_PLUGIN_PATH . 'includes/templates/archive-book.php';
            if (file_exists($archive_template)) {
                return $archive_template;
            }
        }

        return $template;
    }

    /**
     * Canvas Template Assets
     */
    public static function canvas_assets()
    {
        if (is_page_template('awt-canvas')) {
            // Ensure block CSS is loaded for Gutenberg blocks
            wp_enqueue_style('awt-blocks-css');

            // Optional: Dequeue common theme stylesheets
            // wp_dequeue_style( 'theme-style' );
        }
    }
}


function rswpthemes_awt_is_plugin_template_active()
{

    if (is_page_template('awt-canvas')) {
        return true;
    }

    // Theme Side Implementation Example:
    if (is_singular('book')) {
        return true;
    }

    if (is_post_type_archive('book') || is_tax('book-category') || is_tax('book-author') || is_tax('book-series')) {
        return true;
    }


    if (is_404()) {
        return true;
    }

    // Theme Side Implementation Example:
    if (is_home() || is_category() || is_search() || is_tag() || is_author() || is_date()) {
        return true;
    }


    if (is_single()) {
        return true;
    }


    return false;
}



/**
 * Get all configured template IDs and settings
 * * Returns an array of assigned reusable block slugs for various template parts.
 * Useful for frontend logic to determine which block to render.
 * * @return array
 */
function rswpthemes_awt_get_all_template_settings()
{
    $options = get_option('awt_global_settings', []);

    $templates = [
        'book_archive' => isset($options['awt_book_archive_template_id']) ? $options['awt_book_archive_template_id'] : '',
        'book_single' => isset($options['awt_book_single_template_id']) ? $options['awt_book_single_template_id'] : '',
        'blog_archive' => isset($options['awt_blog_template_id']) ? $options['awt_blog_template_id'] : '',
        'blog_single' => isset($options['awt_blog_single_template_id']) ? $options['awt_blog_single_template_id'] : '',
        'page_title' => isset($options['awt_page_title_template_id']) ? $options['awt_page_title_template_id'] : '',
        '404_page' => isset($options['awt_404_template_id']) ? $options['awt_404_template_id'] : '',

        // Header Configuration
        'header' => [
            'block_id' => isset($options['awt_global_header_block']) ? $options['awt_global_header_block'] : '',
            'force_global' => isset($options['awt_header_force_global']) && $options['awt_header_force_global'] === '1',
        ],

        // Footer Configuration
        'footer' => [
            'block_id' => isset($options['awt_global_footer_block']) ? $options['awt_global_footer_block'] : '',
            'force_global' => isset($options['awt_footer_force_global']) && $options['awt_footer_force_global'] === '1',
        ],
    ];

    return $templates;
}

/**
 * Check if ALL template options are set/configured.
 * * @return boolean True if all templates including header/footer have IDs, False otherwise.
 */
function rswpthemes_awt_are_all_templates_configured()
{
    $templates = rswpthemes_awt_get_all_template_settings();

    $required_keys = [
        'book_archive',
        'book_single',
        'blog_archive',
        'blog_single',
        'page_title',
        '404_page'
    ];

    foreach ($required_keys as $key) {
        if (empty($templates[$key])) {
            return false;
        }
    }

    if (empty($templates['header']['block_id'])) {
        return false;
    }

    if (empty($templates['footer']['block_id'])) {
        return false;
    }

    return true;
}

function rswpthemes_awt_unwanted_only(array $assets)
{
    return array_values($assets);
}

function rswpthemes_awt_get_unwanted_assets()
{
    $settings = get_option('awt_global_settings', []);

    // ১. শুরুতে একটা "Master List" তৈরি করি যা আমরা সব জায়গা থেকে রিমুভ করতে চাই।
    // আমরা ধরে নেব বাই ডিফল্ট এগুলো সব পেজেই আনলোড হবে।
    $master_unwanted_list = [
        // 'rswpbs-grid',
        // 'rswpbs-style',
        // 'fontawesome-v6',
        // 'author-portfolio-style',
        // 'block-style',
        // 'bootstrap-grid',
        // 'book-review-blog-style',
        // 'author-personal-blog-style',
        // 'writers-portfolio-style',
        // 'rswpthemes-icons',
    ];

    // কপি করে একটি ভেরিয়েবলে নিই যা আমরা মডিফাই করব
    $unwanted = $master_unwanted_list;

    /* * লজিক:
     * যদি আমরা নির্দিষ্ট পেজে থাকি AND ইউজার কোনো টেমপ্লেট সিলেক্ট না করে থাকে (empty),
     * তাহলে ওই পেজের প্রয়োজনীয় স্টাইলগুলো $unwanted লিস্ট থেকে রিমুভ করে দেব (যাতে সেগুলো লোড হয়)।
     */

    if (is_page_template('awt-canvas.php')) {
        return array_values($unwanted);
    }

    /* ---------- Book Single ---------- */
    // যদি বইয়ের পেজ হয় এবং কাস্টম টেমপ্লেট সেট করা না থাকে
    if (is_singular('book') && empty($settings['awt_book_single_template_id'])) {
        // এই পেজে যেই স্টাইলগুলো দেখানো দরকার, সেগুলো আনলোড লিস্ট থেকে বাদ দিচ্ছি
        $unwanted = array_diff($unwanted, [
            'rswpbs-grid',
            'rswpbs-style',
            'fontawesome-v6',
        ]);
    }

    /* ---------- Book Archive ---------- */
    if (
        (is_post_type_archive('book')
            || is_tax('book-category')
            || is_tax('book-author')
            || is_tax('book-series'))
        && empty($settings['awt_book_archive_template_id'])
    ) {
        $unwanted = array_diff($unwanted, [
            'rswpbs-grid',
            'rswpbs-style',
            'fontawesome-v6',
        ]);
    }

    /* ---------- Blog Archive ---------- */
    if (
        (is_home() || is_category() || is_search() || is_tag() || is_author() || is_date())
        && empty($settings['awt_blog_template_id'])
    ) {
        $unwanted = array_diff($unwanted, [
            'author-portfolio-style',
            'block-style',
            'bootstrap-grid',
            'fontawesome-v6',
        ]);
    }

    /* ---------- Blog Single ---------- */
    if (is_singular('post') && empty($settings['awt_blog_single_template_id'])) {
        $unwanted = array_diff($unwanted, [
            'author-portfolio-style',
            'block-style',
            'bootstrap-grid',
            'fontawesome-v6',
        ]);
    }

    /* ---------- 404 ---------- */
    if (is_404() && empty($settings['awt_404_template_id'])) {
        $unwanted = array_diff($unwanted, [
            'author-portfolio-style',
            'block-style',
            'bootstrap-grid',
        ]);
    }

    // ফাইনালি, অ্যারে রি-ইনডেক্স করে রিটার্ন করা
    return array_values($unwanted);
}


/**
 * Dequeue unwanted assets if AWT Canvas template is active
 */
function rswpthemes_awt_dequeue_assets()
{


    if (
        function_exists('rswpthemes_awt_is_plugin_template_active')
        && rswpthemes_awt_is_plugin_template_active()
    ) {
        foreach (rswpthemes_awt_get_unwanted_assets() as $handle) {

            wp_dequeue_style($handle);
            wp_deregister_style($handle);
            wp_dequeue_script($handle);
            wp_deregister_script($handle);
        }
    }

    // Check for editor screen
    $screen = function_exists('get_current_screen') ? get_current_screen() : false;

    if ($screen && 'post' === $screen->base) {

        $post_id = isset($_GET['post']) ? intval($_GET['post']) : 0;
        $template = get_post_meta($post_id, '_wp_page_template', true);

        // Editor: only when awt-canvas active
        if ($template === 'awt-canvas' || $template === 'awt-canvas.php') {

            foreach (rswpthemes_awt_get_unwanted_assets() as $handle) {
                wp_dequeue_style($handle);
                wp_deregister_style($handle);
                wp_dequeue_script($handle);
                wp_deregister_script($handle);
            }
        }
    }


}

add_action('wp_enqueue_scripts', 'rswpthemes_awt_dequeue_assets', 999);
add_action('enqueue_block_editor_assets', 'rswpthemes_awt_dequeue_assets', 999);


/**
 * Add custom options to Advanced Export plugin
 */
add_filter('advanced_export_include_options', 'rswpthemes_awt_include_demo_options');

function rswpthemes_awt_include_demo_options($included_options)
{
    $my_options = array(
        'awt_global_settings',
        'blogname',
        'blogdescription',
        'site_icon',
        'show_on_front',
        'page_on_front',
        'page_for_posts',
        'posts_per_page',
        'date_format',
        'time_format',
        'start_of_week',
        'thumbnail_size_w',
        'thumbnail_size_h',
        'thumbnail_crop',
        'medium_size_w',
        'medium_size_h',
        'medium_large_size_w',
        'medium_large_size_h',
        'large_size_w',
        'large_size_h',
        'avatar_default',
        'woocommerce_shop_page_id',
        'woocommerce_cart_page_id',
        'woocommerce_checkout_page_id',
        'woocommerce_myaccount_page_id',
        'woocommerce_terms_page_id',
        'permalink_structure',
    );

    return array_unique(array_merge($included_options, $my_options));
}

add_action('wp_head', function () {

    $settings = get_option('awt_global_settings', []);
    $should_remove_kirki = false;

    if (is_page_template('awt-canvas.php') || is_page_template('awt-canvas')) {
        $should_remove_kirki = true;
    }



    // Book Single
    elseif (is_singular('book') && !empty($settings['awt_book_single_template_id'])) {
        $should_remove_kirki = true;
    }
    // Book Archive
    elseif (
        (is_post_type_archive('book') || is_tax('book-category') || is_tax('book-author') || is_tax('book-series'))
        && !empty($settings['awt_book_archive_template_id'])
    ) {
        $should_remove_kirki = true;
    }
    // Blog Archive
    elseif (
        (is_home() || is_category() || is_search() || is_tag() || is_author() || is_date())
        && !empty($settings['awt_blog_template_id'])
    ) {
        $should_remove_kirki = true;
    }
    // Blog Single
    elseif (is_singular('post') && !empty($settings['awt_blog_single_template_id'])) {
        $should_remove_kirki = true;
    }
    // 404 Page
    elseif (is_404() && !empty($settings['awt_404_template_id'])) {
        $should_remove_kirki = true;
    }

    if ($should_remove_kirki) {
        ob_start(function ($html) {
            return preg_replace(
                '/<style id="kirki-inline-styles">.*?<\/style>/s',
                '',
                $html
            );
        });
    }

}, 0);