<?php

require_once get_template_directory() . '/vendor/autoload.php';

/**
 * Array with all the styles that can be selected
 * 
 * 1st level: unique identifier
 * 2nd level: array with name, src and favicon url; all are required
 */
$theme_styles = array(
  "digiexist" => array(
    "name" => "Digi Exist",
    "src" => "/css/style.digiexist.css",
    "favicon" => "/images/digiexist.ico",
  ),

  "aok" => array(
    "name" => "AOK",
    "src" => "/css/style.aok.css",
    "favicon" => "/images/c4c-icon.png",
  ),

  "eregiowerk" => array(
    "name" => "E-Regiowerk",
    "src" => "/css/style.eregiowerk.css",
    "favicon" => "/images/eregiowerk.ico",
  ),

  "digisounds" => array(
    "name" => "DigitalSoundscapes",
    "src" => "/css/style.digisounds.css",
    "favicon" => "/images/digisounds.png",
  ),

  "jolanda" => array(
    "name" => "Jolanda",
    "src" => "/css/style.jolanda.css",
    "favicon" => "/images/jolanda-favicon.png",
  ),

  "geton" => array(
    "name" => "GETON",
    "src" => "/css/style.geton.css",
    "favicon" => "/images/geton-favicon.png",
  ),

  "isleep" => array(
    "name" => "iSleep",
    "src" => "/css/style.isleep.css",
    "favicon" => "/images/digiexist.ico",
  ),

  "mdzsh" => array(
    "name" => "Mittelstand-Digital Zentrum Schleswig-Holstein",
    "src" => "/css/style.mdzsh.css",
    "favicon" => "/images/digiexist.ico",
  ),

  "studycoach" => array(
    "name" => "STUDYCoach",
    "src" => "/css/style.studycoach.css",
    "favicon" => "/images/digiexist.ico",
  ),
  
);

function add_favicon() {
  
  global $theme_styles;
  $selected_theme = get_theme_mod('style_selection');

  if($selected_theme == "") {
    $selected_theme = sizeof($theme_styles) > 0 ? array_keys($theme_styles)[0] : '';
  }
  if(get_site_icon_url() != null){
    $favicon_url = get_site_icon_url();
    ?>
    <link rel="shortcut icon" href="<?php echo $favicon_url;?>"/>
    <?php 
  }else{
    if(isset($theme_styles[$selected_theme])) {
      if(is_file(dirname(__FILE__) . $theme_styles[$selected_theme]['favicon'])) {
        $favicon_url = $theme_styles[$selected_theme]['favicon'];
      } else {
        wp_die("Favicon not found!", "Fehler!");
      }
    } else {
      wp_die("No stylesheet selected and array is empty!", "Fehler!");
    }
    ?>
    <link rel="shortcut icon" href="<?php echo get_stylesheet_directory_uri() . $favicon_url;?>"/>
    <?php 
  }
}
add_action('wp_head','add_favicon');

include 'customizer.php';

use YahnisElsts\PluginUpdateChecker\v5\PucFactory;
$myUpdateChecker = PucFactory::buildUpdateChecker(
  'https://devprojects1.th-luebeck.de/updateserver/wp-update-server/?action=get_metadata&slug=coachlightv2',
	__FILE__,
	'coachlightv2'
);

// *** LOGIN ÄNDERN ***
add_action( 'login_head', 'namespace_login_style' );

//Seiten-Logo als Login-Logo
function namespace_login_style() {
    if( function_exists('get_custom_header') ){
        $width = get_custom_header()->width;
        $height = get_custom_header()->height;
    } else {
        $width = HEADER_IMAGE_WIDTH;
        $height = HEADER_IMAGE_HEIGHT;
    }
    echo '<style>'.PHP_EOL;
    echo '.login h1 a {'.PHP_EOL;
    echo '  background-image: url( '; header_image(); echo ' ) !important; '.PHP_EOL;
    echo '  width: '.$width.'px !important;'.PHP_EOL;
    echo '  height: '.$height.'px !important;'.PHP_EOL;
    echo '  background-size: '.$width.'px '.$height.'px !important;'.PHP_EOL;
    echo '}'.PHP_EOL;
    echo '</style>'.PHP_EOL;
}

//Login Link ändern
add_filter( 'login_headerurl', 'namespace_login_headerurl' );
function namespace_login_headerurl( $url ) {
    $url = home_url( '/' );
    return $url;
}

//Login Title ändern
//add_filter( 'login_headertitle', 'namespace_login_headertitle' ); //nicht mehr unterstützt seit version 5.2
add_filter( 'login_headertext',  'namespace_login_headertitle' );

function namespace_login_headertitle( $title ) {
    $title = get_bloginfo( 'name' );
    return $title;
}



// *** LOGIN ÄNDERN ENDE***

function cwd_wp_bootstrap_scripts_styles() {

  global $theme_styles;

   wp_enqueue_script('customjs', get_template_directory_uri().'/js/custom.js', array('jquery'));
   wp_enqueue_script('burgerjs', get_template_directory_uri().'/js/burger.js', array('jquery'));

   // Loads our main stylesheet.
   wp_enqueue_style('style', get_stylesheet_directory_uri() . '/style.css', array());

   $selected_theme = get_theme_mod('style_selection');
   if($selected_theme == "") {
    $selected_theme = sizeof($theme_styles) > 0 ? array_keys($theme_styles)[0] : '';
   }
   if(isset($theme_styles[$selected_theme])) {
     if(is_file(dirname(__FILE__) . $theme_styles[$selected_theme]['src'])) {
        echo wp_enqueue_style('style-themed', get_stylesheet_directory_uri() . $theme_styles[$selected_theme]['src'], array());
     } else {
       wp_die("Stylesheet not found! Check the array in your theme's functions.php file", "Fehler!");
     }
   } else {
      wp_die("No stylesheet selected and array is empty!", "Fehler!");
   }
 }

 add_action('wp_enqueue_scripts', 'cwd_wp_bootstrap_scripts_styles',15);

 function e_regio_werktheme_widgets_init() {
 	// register_sidebar( array(
 	// 	'name'          => 'Footermenu',
 	// 	'id'            => 'footer-2',
 	// 	'description'   => '',
 	// 	'before_widget' => '<aside id="%1$s" class="widget %2$s">',
 	// 	'after_widget'  => '</aside>',
 	// 	'before_title'  => '<h2 class="widget-title">',
 	// 	'after_title'   => '</h2>',
 	// ) );
  register_sidebar( array(
 		'name'          => 'Footer',
 		'id'            => 'footer-1',
 		'description'   => '',
 		'before_widget' => '<aside id="%1$s" class="widget %2$s">',
 		'after_widget'  => '</aside>',
 		'before_title'  => '<h2 class="widget-title">',
 		'after_title'   => '</h2>',
 	) );

  // register_sidebar( array(
 	// 	'name'          => 'Sidebar3',
 	// 	'id'            => 'sidebar-3',
 	// 	'description'   => '',
 	// 	/*'before_widget' => '<aside id="%1$s" class="widget %2$s">',
 	// 	'after_widget'  => '</aside>',
 	// 	'before_title'  => '<h2 class="widget-title">',
 	// 	'after_title'   => '</h2>',*/
 	// ) );


 }
 add_action( 'widgets_init', 'e_regio_werktheme_widgets_init' );



 function theme_prefix_setup() {

  $args = array(
    'width'         => 40,
    'height'        => 40,
    'default-image' => get_template_directory_uri() . '/images/header.jpg',
    'uploads'       => true,
  );
  add_theme_support( 'custom-header', $args );

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

//add_image_size('mytheme-logo', 160, 90);
add_theme_support('custom-logo', array(
    //'size' => 'mytheme-logo'
    'height'      => 500,
  	'width'       => 500,
  	'flex-height' => true,
  	'flex-width'  => true
));

add_theme_support( 'post-thumbnails' );

add_filter( 'get_custom_logo', 'wecodeart_com' );
// Filter the output of logo to fix Googles Error about itemprop logo
function wecodeart_com() {
    $custom_logo_id = get_theme_mod( 'custom_logo' );
    /*$html = sprintf( '<a href="%1$s" class="custom-logo-link" rel="home" itemprop="url">%2$s</a>',
            esc_url( home_url( '/' ) )
            wp_get_attachment_image( $custom_logo_id, 'full', false, array(
                'class'    => 'custom-logo',
            ) )
        );
    return $html;*/

    $html = sprintf( '<a href="%1$s" class="custom-logo-link" rel="home" itemprop="url"><img class ="img-responsive" src="%2$s"/></a>',
            esc_url( home_url( '/' ) ),
            wp_get_attachment_url( $custom_logo_id));

    return $html;

}
function register_my_menus(){
    register_nav_menus(
        array(
        'primary-menu' => __( 'Primary Menu' ),
        'secondary-menu' => __( 'Secondary Menu' )
        )
    );
}
add_action( 'init', 'register_my_menus' );


/*Translation filter for «Search results for» and «404 Not Found» in «admin-functions.php» (mystile, wootheme) */
function replace_search_notfound($trail) {
  $trail = str_replace ( "Search results for" , "Your translation" , $trail );
  $trail = str_replace ( "404 Not Found" , "404 Your translation" , $trail );
  return $trail;
}
add_filter( 'woo_breadcrumbs' , 'replace_search_notfound',10);



remove_filter( 'the_content', 'wpautop' );
remove_filter( 'the_excerpt', 'wpautop' );


// remove dimensions of video tag to fit it in its bootstrap-class
function override_video_dimensions( $out, $pairs, $atts) {
     $out['width'] = '';
     $out['height'] = '';
    return $out;
}
add_filter( 'shortcode_atts_video', 'override_video_dimensions', 10, 3 );

//override video shortcode  with bootstrap
function override_wp_video_shortcode( $attr, $content = '' ){
      $vid = array();
      $vid = shortcode_parse_atts($attr);
      $homeURL=get_home_url();

      $inputURL=$vid['src'];
      $cutpos=strpos($inputURL, '/wp-content/uploads');
      $outputURL=$homeURL.substr($inputURL ,$cutpos);

      if (isset ($vid['poster'])){
      $inputPosterURL=$vid['poster'];
      $cutposPoster=strpos($inputPosterURL, '/wp-content/uploads');
      $outputPosterURL=$homeURL.substr($inputPosterURL ,$cutposPoster);

      
      $content =  sprintf('<div class="embed-responsive embed-responsive-16by9">
      <video class="" controls=true poster="'.$outputPosterURL.'" src="'.$outputURL.'" onclick="this.paused?this.play():this.pause();" allowfullscreen></video>
      </div>');
    }
    else {
      $content =  sprintf('<div class="embed-responsive embed-responsive-16by9">
      <video class="" controls=true src="'.$outputURL.'" onclick="this.paused?this.play():this.pause();" allowfullscreen></video>
      </div>');
    }
    return $content;
}
add_filter( 'wp_video_shortcode', 'override_wp_video_shortcode', 10, 3 );


function bootstrap_responsive_images( $html ){
    $classes = 'img-fluid'; // separated by spaces, e.g. 'img image-link'
    // check if there are already classes assigned to the anchor
    if ( preg_match('/<img.*? class="/', $html) ) {
        $html = preg_replace('/(<img.*? class=".*?)(".*?\/>)/', '$1 ' . $classes . ' $2', $html);
    } else {
        $html = preg_replace('/(<img.*?)(\/>)/', '$1 test class="' . $classes . '" $2', $html);
    }
    $html = str_replace("alignleft","float-left",$html);
    $html = str_replace("alignright","float-right",$html);
    $html = str_replace("aligncenter","mx-auto",$html);

    //$html = preg_replace( '<img src', "<img width='100px' src", $html );

    //$html = preg_replace( '/(width|height)=\"\d*\"\s/', "", $html );

   //  $html = preg_replace( '/(width)=\"\d*\"\s/', 'width=100% ', $html );

    // remove dimensions from images,, does not need it!

    return $html;
}
add_filter( 'the_content','bootstrap_responsive_images',10 );
add_filter( 'post_thumbnail_html', 'bootstrap_responsive_images', 10 );


//zusammenfassung mit definierter länge
function limitexcerpt($limit) {
  $excerpt = explode(' ', get_the_excerpt(), $limit);
  if (count($excerpt)>=$limit) {
    array_pop($excerpt);
    $excerpt = implode(" ",$excerpt).'...';
  } else {
    $excerpt = implode(" ",$excerpt);
  }
  $excerpt = preg_replace('`\[[^\]]*\]`','',$excerpt);
  return $excerpt;
}

/**
 * Register Custom Navigation Walker
 */
function register_navwalker(){
	require_once get_template_directory() . '/inc/class-wp-bootstrap-navwalker.php';
}
add_action( 'after_setup_theme', 'register_navwalker' );

function trainingssystem_plugin_active_menu_item($atts, $item, $args) {
  global $post;

  if(is_a($item, 'WP_Post')) { // Only for Custom created Menu Items, Frontend menu is handled in TS Plugin
    if(get_permalink($post) == $item->url) {
      $atts['class'] .= " menu-item-text-underlined";
    }
  }
  return $atts;
}

add_filter("nav_menu_link_attributes", "trainingssystem_plugin_active_menu_item", 20, 3);

//dequeue css from plugins
function unhook_parent_style() {

  wp_dequeue_style( 'nf-display');
  wp_deregister_style( 'nf-display');
}
add_action( 'wp_enqueue_scripts', 'unhook_parent_style', 20);



// Function to change email address
function hn_sender_email( $original_email_address ) {
    $admin_mail = get_bloginfo('admin_email');
    return $admin_mail;
}
// Function to change sender name
function hn_sender_name( $original_email_from ) {
    $site_name = get_bloginfo('name');
    return $site_name;
}
// Hooking up our functions to WordPress filters
add_filter( 'wp_mail_from', 'hn_sender_email' );
add_filter( 'wp_mail_from_name', 'hn_sender_name' );

/**
 * Remove type Attribute for Validator
*/
add_filter('style_loader_tag', 'codeless_remove_type_attr', 10, 2);
add_filter('script_loader_tag', 'codeless_remove_type_attr', 10, 2);

function codeless_remove_type_attr($tag, $handle) {
    return preg_replace( "/type=['\"]text\/(javascript|css)['\"]?/", '', $tag );
}

add_filter( 'random_password', 'disable_password_suggestion', 10, 2 );
function disable_password_suggestion( $password ) {
    $action = isset( $_GET['action'] ) ? $_GET['action'] : '';
    if ( 'wp-login.php' === $GLOBALS['pagenow'] && ( 'rp' == $action  || 'resetpass' == $action ) ) {
        return '';
    }
    return $password;
}

?>
