<?php

// Required b&s theme functionalities ---------------------------------------------
// Plugins Init
require get_template_directory() . '/plugins/plugins-init.php';

// CPT register.php
require get_template_directory() . '/entities/register.php';

// Blocks register.php
require get_template_directory() . '/blocks/register.php';

// Default blocks register.php
require get_template_directory() . '/blocks/register-defaults.php';

// GB Custom register.php
require get_template_directory() . '/gb-custom/register.php';

// Framework CPT
require get_template_directory() . '/framework/cpt-framework.php';

// Standard Patterns 
require get_template_directory() . '/pattern.php';

// DEV Area
require get_template_directory() . '/backend/devarea/overview.php';

// Custom shortcodes
require get_template_directory() . '/bs-shortcodes.php';

// Required Underscore theme functionalities ---------------------------------------------
// Custom template tags
require get_template_directory() . '/inc/template-tags.php';

// Custom template functions
require get_template_directory() . '/inc/template-functions.php';

// Jetpack compatibility file
if (defined('JETPACK__VERSION')) {
    require get_template_directory() . '/inc/jetpack.php';
}

// Disable/Filter unwanted WordPress Features ---------------------------------------------
// Emoji's
function disable_emojis()
{
    remove_action('wp_head', 'print_emoji_detection_script', 7);
    remove_action('admin_print_scripts', 'print_emoji_detection_script');
    remove_action('wp_print_styles', 'print_emoji_styles');
    remove_action('admin_print_styles', 'print_emoji_styles');
    remove_filter('the_content_feed', 'wp_staticize_emoji');
    remove_filter('comment_text_rss', 'wp_staticize_emoji');
    remove_filter('wp_mail', 'wp_staticize_emoji_for_email');

    // Remove from TinyMCE
    add_filter('tiny_mce_plugins', 'disable_emojis_tinymce');
}
add_action('init', 'disable_emojis');

// Tinymce emoji plugin
function disable_emojis_tinymce($plugins)
{
    if (is_array($plugins)) {
        return array_diff($plugins, array('wpemoji'));
    } else {
        return array();
    }
}

// Comments throughout the site
add_action('admin_init', function () {
    // Redirect any user trying to access comments page
    global $pagenow;

    if ($pagenow === 'edit-comments.php') {
        wp_redirect(admin_url());
        exit;
    }
    // Remove comments metabox from dashboard
    remove_meta_box('dashboard_recent_comments', 'dashboard', 'normal');
    // Disable support for comments and trackbacks in post types
    foreach (get_post_types() as $post_type) {
        if (post_type_supports($post_type, 'comments')) {
            remove_post_type_support($post_type, 'comments');
            remove_post_type_support($post_type, 'trackbacks');
        }
    }
});

// Close comments on the front-end
add_filter('comments_open', '__return_false', 20, 2);
add_filter('pings_open', '__return_false', 20, 2);

// Hide existing comments
add_filter('comments_array', '__return_empty_array', 10, 2);

// Remove comments page in menu
add_action('admin_menu', function () {
    remove_menu_page('edit-comments.php');
});

// Remove comments links from admin bar
add_action('init', function () {
    if (is_admin_bar_showing()) {
        remove_action('admin_bar_menu', 'wp_admin_bar_comments_menu', 60);
    }
});

// Remove 'Customize' link from the Appearance menu
add_action('admin_menu', function () {
    global $submenu;

    if (isset($submenu['themes.php'])) {
        foreach ($submenu['themes.php'] as $index => $menu_item) {
            if (in_array('customize', $menu_item)) {
                unset($submenu['themes.php'][$index]);
            }
        }
    }
});

add_action('wp_before_admin_bar_render', function () {
    global $wp_admin_bar;

    // Remove 'Customize' link from the admin bar
    $wp_admin_bar->remove_menu('customize');
});

// Enable excerpts ---------------------------------------------
add_post_type_support('page', 'excerpt');

// Custom styling ---------------------------------------------
// Admin CSS
function bs_admin_style()
{
    wp_enqueue_style('admin-css', get_template_directory_uri() . '/backend/admin-style.css');
}
add_action('admin_head', 'bs_admin_style');

// Editor CSS
add_editor_style();

// Login CSS
function bs_custom_login()
{
    ob_start(); // begin collecting output
    include get_template_directory() . '/gb-custom/blockcss.php';
    include get_template_directory() . '/backend/logincss.php';
    $result = ob_get_clean();
    echo "<style>" . $result . "</style>";
}
add_action('login_head', 'bs_custom_login');

// Wizard functions // b&s Theme Option Page ---------------------------------------------
/** 
 * SET DEFAULT WORDPRESS SETTING AFTER ACTIVATION (ONLY ONCE) 
 * */
function setWPSettingsOnceFunction()
{
    if (get_option('setWPSettingsOnce') != 'completed') {
        // Create Home page
        $homePageID = wp_insert_post(array(
            'post_type'    => 'page',
            'post_status'  => 'publish',
            'post_title'   => 'Home',
            'post_content' => 'Home page content goes here.',
        ));

        // Create Impressum page
        wp_insert_post(array(
            'post_type'    => 'page',
            'post_status'  => 'publish',
            'post_title'   => 'Impressum',
            'post_content' => 'Legal disclosure content goes here.',
        ));

        // Publish the default Privacy Policy page if it exists
        $privacy_page_id = get_option('wp_page_for_privacy_policy');
        if ($privacy_page_id && get_post_status($privacy_page_id) !== 'publish') {
            wp_update_post(array(
                'ID' => $privacy_page_id,
                'post_status' => 'publish',
            ));
        }

        update_option('require_name_email', '1');
        update_option('comments_notify', '1');
        update_option('moderation_notify', '1');
        update_option('permalink_structure', '/%postname%/');
        update_option('uploads_use_yearmonth_folders', '');
        update_option('show_on_front', 'page');
        update_option('close_comments_days_old', '0');
        update_option('show_avatars', '');
        update_option('page_on_front', $homePageID);
        update_option('comment_registration', '1');
        update_option('comment_moderation', '1');
        update_option('setWPSettingsOnce', 'completed');
    }
}

add_action('admin_init', 'setWPSettingsOnceFunction');

// Theme Global ---------------------------------------------
add_action('acf/init', 'my_acf_op_init');

function my_acf_op_init()
{
    if (function_exists('acf_add_options_page')) {
        acf_add_options_page(array(
            'page_title'     => 'Theme Global',
            'menu_title'    => 'Theme Global',
            'menu_slug'     => 'theme-general-settings',
            'capability'    => 'edit_posts',
            'redirect'        => false
        ));
        acf_add_options_sub_page(array(
            'page_title'     => 'Theme Styles',
            'menu_title'    => 'Styles',
            'parent_slug'    => 'theme-general-settings',
        ));
        acf_add_options_sub_page(array(
            'page_title'     => 'Sidebar',
            'menu_title'    => 'Sidebar',
            'parent_slug'    => 'theme-general-settings',
        ));
        acf_add_options_sub_page(array(
            'page_title'     => 'Framwork',
            'menu_title'    => 'Framework',
            'parent_slug'    => 'theme-general-settings',
        ));
    }
}

add_filter('acf/settings/load_json', 'my_acf_json_load_point');

function my_acf_json_load_point($paths)
{

    // remove original path (optional)
    unset($paths[0]);

    // append path
    $paths[] = get_template_directory() . '/plugins/acf-jsons';


    // return
    return $paths;
}

add_filter('acf/settings/save_json', 'my_acf_json_save_point');

function my_acf_json_save_point($path)
{
    // update path
    $path = get_template_directory() . '/plugins/acf-jsons';

    // return
    return $path;
}

// Custom admin menu links ---------------------------------------------
// Block patterns
function custom_admin_menu_links()
{
    add_menu_page(
        'Block Patterns',            // Page title
        'Block Patterns',            // Menu title
        'edit_posts',                // Capability required to see this menu item
        'edit.php?post_type=wp_block', // The 'slug' - file to display when clicking the menu item
        '',                          // Function used to display the page content. Empty string for none or a function name.
        'dashicons-schedule',        // Icon URL (use a WordPress Dashicon)
        92                            // Position in the menu order
    );
}

add_action('admin_menu', 'custom_admin_menu_links');

// Custom Gutenberg Color Palette ---------------------------------------------
function add_custom_gutenberg_color_palette()
{
    $colorArray = array();
    if (have_rows('site_colors', 'option')) :
        while (have_rows('site_colors', 'option')) : the_row();
            $name = get_sub_field('name');
            $class = get_sub_field('class');
            $color = get_sub_field('color');

            $cColor = array(
                'name' => esc_html__($name, 'bsTheme'),
                'slug' => $class,
                'color' => $color
            );

            array_push($colorArray, $cColor);

        endwhile;
    endif;

    add_theme_support(
        'editor-color-palette',
        $colorArray

    );
}
add_action('after_setup_theme', 'add_custom_gutenberg_color_palette');

// Theme category for custom blocks
function themeCustomBlockCategory($categories, $post)
{
    return array_merge(
        array(
            array(
                'slug'  => 'theme_custom', // A unique slug for your category.
                'title' => __('Theme Custom', 'text-domain'), // The title of your category.
                'icon'  => 'wordpress', // Optionally you can set an icon (Dashicon) for your category.
            ),
        ),
        $categories
    );
}

add_filter('block_categories_all', 'themeCustomBlockCategory', 10, 2);

// Defer scripts ---------------------------------------------
function mind_defer_scripts($tag, $handle, $src)
{
    $defer = array(
        'bootstrap',
        'aos',
        'swiper',
        'shuffleJS',

    );
    if (in_array($handle, $defer)) {
        return '<script src="' . $src . '" defer="defer" type="text/javascript"></script>' . "\n";
    }

    return $tag;
}
add_filter('script_loader_tag', 'mind_defer_scripts', 10, 3);

// TinyMCE Color Change ---------------------------------------------
function change_tinymce_colors($init)
{
    $default_colours =
        '"000000", "Black",
        "0000FF", "Blue",
        "FF0000", "Red",
        "800080", "Purple",
        "FF00FF", "Magenta",
        "FFFF00", "Yellow",
        "FFFFFF", "White"';
    $custom_colours = "";
    $colors = get_field('site_colors', 'options');
    foreach ($colors as $c) {
        $color = str_replace('#', '', $c['color']);
        $custom_colours .= '"' . $color . '", "' .   $c["name"] . '",';
    }

    $init['textcolor_map'] = '[' . $default_colours . ',' . $custom_colours . ']';
    $init['textcolor_rows'] = 6; // expand colour grid to 6 rows
    return $init;
}
add_filter('tiny_mce_before_init', 'change_tinymce_colors');

// Block patterns ---------------------------------------------
function bsTheme_register_block_patterns_from_json()
{
    if (function_exists('register_block_pattern')) {
        $pattern_dir = get_template_directory() . '/block-patterns';
        $pattern_files = glob($pattern_dir . '/*.json');

        foreach ($pattern_files as $file) {
            $pattern_data = json_decode(file_get_contents($file), true);
            if ($pattern_data) {
                register_block_pattern('bsTheme/' . basename($file, '.json'), array(
                    'title' => $pattern_data['title'],
                    'content' => $pattern_data['content'],
                    // Include other properties if available
                ));
            }
        }
    }
}
add_action('init', 'bsTheme_register_block_patterns_from_json');

// System functions ---------------------------------------------
function fontsViaCDNRepeater()
{
    $fontsRepeater = get_field('font-sources-link', 'option');

    if ($fontsRepeater != false) {
        $fontLinks = '';

        foreach ($fontsRepeater as $font) {
            if (!empty($font['fontlink'])) {
                $fontLinks .= '<link rel="stylesheet" href="' . $font['fontlink'] . '">';
            }
        }

        echo $fontLinks;
    }
}

// Device Type ---------------------------------------------
$is_mobile = wp_is_mobile();
$device_type = 'desktop';

if ($is_mobile) {
    $device_type = 'mobile';
}

//  Add a body class for easy CSS targeting.
function add_device_body_class($classes)
{
    global $device_type;  // Access the variable

    $classes[] = 'device-' . $device_type;
    return $classes;
}

add_filter('body_class', 'add_device_body_class');

// Core HTML output for header, menu and footer ---------------------------------------------
function coreHTMLOutput($type = 'header')
{
    $coreHTMLType = get_post(get_field($type, 'option'));
    $result = $coreHTMLType->post_content;
    $result = apply_filters('the_content', $result);
    $result = str_replace(']]>', ']]&gt;', $result);

    echo $result;
}

// Enqueue an admin script that, in conjunction with this, populates the ACF color picker fields with the colors from the Theme Styles option repeater ---------------------------------------------
add_action('acf/input/admin_enqueue_scripts', 'enqueue_acf_color_palette_script');
function enqueue_acf_color_palette_script()
{
    // Pull the colors from your ACF options repeater
    $colors = get_field('site_colors', 'option') ?: [];
    $hexes = [];

    foreach ($colors as $color_row) {
        if (!empty($color_row['color'])) {
            $hexes[] = $color_row['color'];
        }
    }

    wp_enqueue_script('custom-acf-color-palette', get_template_directory_uri() . '/js/acf-color-palette.js', ['acf-input'], '1.0', true);

    wp_localize_script('custom-acf-color-palette', 'acfCustomPalette', [
        'colors' => $hexes,
    ]);
}

// Populate the Theme Style colors with brot & salz defaults ---------------------------------------------
add_filter('acf/load_value/name=site_colors', function ($value, $post_id, $field) {
    if (!empty($value)) {
        return $value; // Do not override if already saved
    }

    // Prepare an array to map names to keys
    $subfield_keys = [];

    // Debug: Log all available subfields
    foreach ($field['sub_fields'] as $sub_field) {
        error_log('Subfield name: ' . $sub_field['name'] . ' | key: ' . $sub_field['key']);
        $subfield_keys[$sub_field['name']] = $sub_field['key'];
    }

    // Now build based on expected names
    if (!isset($subfield_keys['use'], $subfield_keys['class'], $subfield_keys['color'])) {
        error_log('Missing one or more required subfields: use, class, color');
        return $value; // Exit if any missing
    }

    // Default data
    return [
        [
            $subfield_keys['use']   => 'Default Dark',
            $subfield_keys['class'] => 'Def',
            $subfield_keys['color'] => '#121212',
        ],
        [
            $subfield_keys['use']   => 'Default Light',
            $subfield_keys['class'] => 'Light',
            $subfield_keys['color'] => '#faf9f8',
        ],
        [
            $subfield_keys['use']   => 'Accent',
            $subfield_keys['class'] => 'Pink',
            $subfield_keys['color'] => '#efa9be',
        ],
    ];
}, 10, 3);

// Update Checker ---------------------------------------------
require_once get_template_directory() . '/plugin-update-checker/load-v5p5.php';

use YahnisElsts\PluginUpdateChecker\v5\PucFactory;

$myUpdateChecker = PucFactory::buildUpdateChecker(
    'https://themeupdate.devbs.de/bsTheme-update.json', // JSON with version info
    __FILE__,                                            // Full path to this file
    'bsTheme'                                            // Theme slug (should match folder)
);
