<?php

/**
 * bsTheme functions and definitions
 *
 * @link https://developer.wordpress.org/themes/basics/theme-functions/
 *
 * @package bsTheme
 */

if (!defined('_S_VERSION')) {
	// Replace the version number of the theme on each release.
	define('_S_VERSION', '1.0.0');
}

if (!function_exists('bstheme_setup')) :
	/**
	 * Sets up theme defaults and registers support for various WordPress features.
	 *
	 * Note that this function is hooked into the after_setup_theme hook, which
	 * runs before the init hook. The init hook is too late for some features, such
	 * as indicating support for post thumbnails.
	 */
	function bstheme_setup()
	{
		/*
		 * Make theme available for translation.
		 * Translations can be filed in the /languages/ directory.
		 * If you're building a theme based on bsTheme, use a find and replace
		 * to change 'bstheme' to the name of your theme in all the template files.
		 */
		load_theme_textdomain('bstheme', get_template_directory() . '/languages');

		// Add default posts and comments RSS feed links to head.
		add_theme_support('automatic-feed-links');

		/*
		 * Let WordPress manage the document title.
		 * By adding theme support, we declare that this theme does not use a
		 * hard-coded <title> tag in the document head, and expect WordPress to
		 * provide it for us.
		 */
		add_theme_support('title-tag');

		/*
		 * Enable support for Post Thumbnails on posts and pages.
		 * @link https://developer.wordpress.org/themes/functionality/featured-images-post-thumbnails/
		 */
		add_theme_support('post-thumbnails');

		// This theme uses wp_nav_menu() in one location.
		register_nav_menus(
			array(
				'menu-1' => esc_html__('Primary', 'bstheme'),
			)
		);

		/*
		 * Switch default core markup for search form, comment form, and comments
		 * to output valid HTML5.
		 */
		add_theme_support(
			'html5',
			array(
				'search-form',
				'comment-form',
				'comment-list',
				'gallery',
				'caption',
				'style',
				'script',
			)
		);

		// Set up the WordPress core custom background feature.
		add_theme_support(
			'custom-background',
			apply_filters(
				'bstheme_custom_background_args',
				array(
					'default-color' => 'ffffff',
					'default-image' => '',
				)
			)
		);

		// Add theme support for selective refresh for widgets.
		add_theme_support('customize-selective-refresh-widgets');

		/**
		 * Add support for core custom logo.
		 *
		 * @link https://codex.wordpress.org/Theme_Logo
		 */
		add_theme_support(
			'custom-logo',
			array(
				'height'      => 250,
				'width'       => 250,
				'flex-width'  => true,
				'flex-height' => true,
			)
		);
	}
endif;
add_action('after_setup_theme', 'bstheme_setup');

/**
 *   Load functions for core changes
 */
require get_template_directory() . '/functions-core.php';

/**
 * Set the content width in pixels, based on the theme's design and stylesheet.
 * Priority 0 to make it available to lower priority callbacks.
 * @global int $content_width
 */
function bstheme_content_width()
{
	$GLOBALS['content_width'] = apply_filters('bstheme_content_width', 640);
}
add_action('after_setup_theme', 'bstheme_content_width', 0);

// Enqueue scripts and styles ---------------------------------------------
function bstheme_scripts()
{
	global $wp_scripts;
	$wp_scripts->registered['jquery-core']->src = get_template_directory_uri() . '/libs/jQuery/jquery-3.6.0.min.js';
	$wp_scripts->registered['jquery']->deps = ['jquery-core'];

	/** Enqueue Bootstrap */
	wp_enqueue_script('bootstrap', get_template_directory_uri() . '/libs/bootstrap/js/bootstrap.min.js', array('jquery'), null, true);
	wp_enqueue_style('bootstrap', get_template_directory_uri() . '/libs/bootstrap/css/bootstrap.min.css');

	/** Enqueue AoS */
	wp_enqueue_script('aos', get_template_directory_uri() . '/libs/aos/aos.js', array('jquery'), null, true);
	wp_enqueue_style('aos-css', get_template_directory_uri() . '/libs/aos/aos.css');

	/** Enqueue Swiper */
	wp_enqueue_script('swiper', get_template_directory_uri() . '/libs/swiperJS/swiper-bundle.min.js', array('jquery'), null, true);
	wp_enqueue_style('swiper-css', get_template_directory_uri() . '/libs/swiperJS/swiper-bundle.min.css');

	/** Enqueue normalize.css */
	wp_enqueue_style('normalize-styles-css', get_template_directory_uri() . '/normalize.css');

	/** Enqueue style.css */
	wp_enqueue_style('bstheme-style', get_stylesheet_uri(), array(), '1.0');
	wp_style_add_data('bstheme-style', 'rtl', 'replace');


	/** Enqueue all custom css */
	$cssDir = get_stylesheet_directory() . '/css/'; // Directory where CSS files are located
	$cssDirUri = get_template_directory_uri() . '/css/'; // URI for the CSS directory

	// Read all CSS files from the directory
	foreach (glob($cssDir . "*.css") as $file) {
		// Extract the filename without extension to use as a handle
		$filename = basename($file, '.css');

		// Enqueue each CSS file with a handle that matches its filename
		wp_enqueue_style($filename, $cssDirUri . $filename . '.css?v=2.0.0');
	}

	/** Enqueue global.css */
	wp_enqueue_style('global-styles-css', get_template_directory_uri() . '/global.css');

	/** Enqueue global.js */
	wp_enqueue_script('bstheme-global', get_template_directory_uri() . '/js/global.js', array(), _S_VERSION, true);
}

add_action('wp_enqueue_scripts', 'bstheme_scripts');

// Add custom text formatting for WYSIWYG editor ---------------------------------------------
function theme_editor_custom_styles($init_array)
{

	$style_formats = array(
		// These are the custom styles
		array(
			'title' => 'Sektions-Indikator',
			'block' => 'span',
			'classes' => 'is-style-secInd',
			'wrapper' => true,
		),
		array(
			'title' => 'Große Überschrift',
			'block' => 'span',
			'classes' => 'is-style-mainHeadline',
		),
	);
	// Insert the array, JSON ENCODED, into 'style_formats'
	$init_array['style_formats'] = json_encode($style_formats);

	return $init_array;
}

// Register custom formats
function add_style_select_buttons($buttons)
{
	array_unshift($buttons, 'styleselect');
	return $buttons;
}

// Register our callback to the appropriate filter
add_filter('mce_buttons_2', 'add_style_select_buttons');

// Attach callback to 'tiny_mce_before_init' 
add_filter('tiny_mce_before_init', 'theme_editor_custom_styles');


// Add custom alt text edit field in Media Library ---------------------------------------------
function add_alt_text_column($columns)
{
	$columns['alt_text'] = 'Alt Text';
	return $columns;
}
add_filter('manage_media_columns', 'add_alt_text_column');

function display_alt_text_column($column_name, $post_id)
{
	if ('alt_text' == $column_name) {
		$alt_text = get_post_meta($post_id, '_wp_attachment_image_alt', true);
		echo '<input type="text" value="' . esc_attr($alt_text) . '" data-post-id="' . $post_id . '">';
	}
}
add_action('manage_media_custom_column', 'display_alt_text_column', 10, 2);

function update_alt_text()
{
	$post_id = isset($_POST['post_id']) ? intval($_POST['post_id']) : 0;
	$alt_text = isset($_POST['alt_text']) ? sanitize_text_field($_POST['alt_text']) : '';

	if ($post_id) {
		update_post_meta($post_id, '_wp_attachment_image_alt', $alt_text);
		echo 'Alt text updated';
	}
	wp_die();
}
add_action('wp_ajax_update_alt_text', 'update_alt_text');

function enqueue_custom_admin_js()
{
	wp_enqueue_script('update-alt-text', get_template_directory_uri() . '/js/ajaxAltMediaTxt.js', array('jquery'), null, true);
	// Correct way to pass data to scripts
	$data = array('ajaxurl' => admin_url('admin-ajax.php'));
	wp_localize_script('update-alt-text', 'myScriptData', $data);
}
add_action('admin_enqueue_scripts', 'enqueue_custom_admin_js');

// Add custom maintenance mode in Theme Global ---------------------------------------------
function check_maintenance_mode()
{
	// Check if the ACF function exists to prevent errors in case ACF is deactivated
	if (function_exists('get_field')) {
		// Adjust 'option' if your field is saved elsewhere
		$isMaintenance = get_field('isMaintenance', 'option');

		// Check if 'isMaintenance' is true and the user is not logged in
		if ($isMaintenance && !is_user_logged_in()) {
			// Define the path to your maintenance file
			$maintenance_file = get_template_directory() . '/maintenance.php';

			if (file_exists($maintenance_file)) {

				global $maintenanceMessage;
				global $fontLinks;
				global $maintIcon;
				$maintenanceMessage = get_field('txtMaintenance', 'option');
				$fontsRepeater = get_field('font-sources-link', 'option');
				$maintIcon = get_field('mainticon', 'option');
				if ($fontsRepeater != false) {
					$fontLinks = '';

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

// Hook the function into WordPress before it sends any output to the browser
add_action('template_redirect', 'check_maintenance_mode');
