<?php

/**
 * Theme setup
 */
function setup()
{
    // Enable plugins to manage the document title
    // http://codex.wordpress.org/Function_Reference/add_theme_support#Title_Tag
    add_theme_support('title-tag');
    add_theme_support('woocommerce');
    
    // Register wp_nav_menu() menus
    // http://codex.wordpress.org/Function_Reference/register_nav_menus
    register_nav_menus([
        'primary_navigation' => __('Primary Navigation', '052b'),
        'primary_right_navigation' => __('Primary Right Navigation', '052b'),
        'footer_navigation' => __('Footer Navigation', '052b'),
        'footer_navigation2' => __('Footer Navigation2', '052b'),
        'footer_navigation3' => __('Footer Navigation3', '052b'),
        'mobile_navigation' => __('Mobile Navigation', '052b'),
        'categories_navigation' => __('Category Navigation', '052b'),
        'language_navigation' => __('Language Navigation', '052b'),
    ]);

    // Enable post thumbnails
    // http://codex.wordpress.org/Post_Thumbnails
    // http://codex.wordpress.org/Function_Reference/set_post_thumbnail_size
    // http://codex.wordpress.org/Function_Reference/add_image_size
    add_theme_support('post-thumbnails');

    add_image_size('full_hd', 1920, 1080, true);

    // Enable post formats
    // http://codex.wordpress.org/Post_Formats
    //   add_theme_support('post-formats', ['aside', 'gallery', 'link', 'image', 'quote', 'video', 'audio']);

    // Enable HTML5 markup support
    // http://codex.wordpress.org/Function_Reference/add_theme_support#HTML5
    add_theme_support('html5', ['caption', 'comment-form', 'comment-list', 'gallery', 'search-form']);

    // Use main stylesheet for visual editor
    // To add custom styles edit /assets/styles/layouts/_tinymce.scss
    //add_editor_style(('styles/main.css')); DELETED
}
add_action('after_setup_theme', 'setup');

/**
 * Register sidebars
 */
function widgets_init()
{
    register_sidebar([
        'name' => __('Primary', '052b'),
        'id' => 'sidebar-primary',
        'before_widget' => '<section class="widget %1$s %2$s">',
        'after_widget' => '</section>',
        'before_title' => '<h3>',
        'after_title' => '</h3>',
    ]);

    register_sidebar([
        'name' => __('Footer', '052b'),
        'id' => 'sidebar-footer',
        'before_widget' => '<section class="widget %1$s %2$s">',
        'after_widget' => '</section>',
        'before_title' => '<h3>',
        'after_title' => '</h3>',
    ]);
}
add_action('widgets_init', 'widgets_init');

/**
 * Determine which pages should NOT display the sidebar
 */
function display_sidebar()
{
    static $display;

    isset($display) || $display = !in_array(true, [
        // The sidebar will NOT be displayed if ANY of the following return true.
        // @link https://codex.wordpress.org/Conditional_Tags
        is_404(),
        is_front_page(),
        is_page_template('template-custom.php'),
    ]);

    return apply_filters('sage/display_sidebar', $display);
}

/**
 * Theme assets
 */
function assets()
{
    wp_enqueue_style('mbot-css-glob', get_template_directory_uri() . "/dist/css/glob.css", false, null);
    wp_enqueue_style('mbot-css', get_template_directory_uri() . "/dist/styles/main_new.css", false, null);
    wp_enqueue_script('mbot-glob', get_template_directory_uri() . "/dist/js/glob.js", ['jquery']);

    wp_register_script('mbot-main', get_template_directory_uri() . "/dist/scripts/main.js", ['jquery'], null, true);
    $vars = array(
        'ajaxurl' => admin_url('admin-ajax.php'),
    );
    wp_localize_script('mbot-main', 'v', $vars);
    wp_enqueue_script('mbot-main');

}
add_action('wp_enqueue_scripts', 'assets', 100);

require_once 'wp_bootstrap_navwalker.php';
require_once "megamenu-navwalker.php";

function cc_mime_types($mimes)
{
    $mimes['svg'] = 'image/svg+xml';
    return $mimes;
}
add_filter('upload_mimes', 'cc_mime_types');

function custom_excerpt_length($length)
{
    return 20;
}
add_filter('excerpt_length', 'custom_excerpt_length', 999);

function new_excerpt_more($more)
{
    return '...';
}
add_filter('excerpt_more', 'new_excerpt_more', 99);

function custom_single_directory($template)
{
    if (is_single() && get_post_type() !== 'post') {
        $new_template = locate_template(array('single-templates/' . get_post_type() . '.php'));
        if ($new_template !== '') {
            return $new_template;
        }
    }
    return $template;
}
add_filter( 'template_include', 'custom_single_directory', 1001 );

function mbot_error_alerts()
{
    $errors = array();
    $dir = get_template_directory();
    $files = array("mbot_styles_status", "mbot_js_status", "mbot_css_status", "mbot_scripts_status");

    foreach ($files as $file) {
        if (file_exists($dir . "/" . $file . ".txt")) {
            $openFile = file_get_contents($dir . "/" . $file . ".txt");
            if (strlen(trim($openFile)) > 0) {
                $errors[] = $openFile;
            }
        }
    }

    if (count($errors) > 0) {
        echo "<div style='width: 100%; padding: 15px 30px; background: red; color: #fff; font-weight: 500; font-size: 16px; position: fixed; z-index: 9999999;'>";
        foreach ($errors as $e) {
            echo $e . "<br>";
        }
        echo "</div>";
    }
}

add_action('wp_head', 'mbot_error_alerts');

// Scheduled Action Hook
function check_licence()
{
    if (!defined('LICENCE_052B'));
    global $wp_version;

    $apl = get_option('active_plugins');
    $plugins = get_plugins();
    $activated_plugins = array();

    foreach ($apl as $p) {
        if (isset($plugins[$p])) {
            $activated_plugins[$p] = $plugins[$p];
            $activated_plugins[$p]['slug'] = $p;
        }
    }

    $returned_plugins = array();

    $update_plugins = get_site_transient('update_plugins');

    $update_plugins_array = json_decode(json_encode($update_plugins->response), true);

    foreach ($activated_plugins as $slug => $plug_in) {
        if (isset($update_plugins_array[$slug])) {
            $plug_in['latest_version'] = $update_plugins_array[$slug]['new_version'];
        }
        $returned_plugins[] = $plug_in;
    }

    $post = [
        'plugins' => json_encode($returned_plugins),
        'update_plugins_array' => json_encode($update_plugins_array),
        'domain' => get_site_url(),
        'system_version' => $wp_version,
        'licence_key' => LICENCE_052B,
    ];

    $ch = curl_init('https://licencje.052b.com/api/licencecheck');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post);

    // execute!
    $response = curl_exec($ch);

    // close the connection, release resources used
    curl_close($ch);
}
add_action('check_licence', 'check_licence');

// Schedule Cron Job Event
function check_licence_cron()
{
    if (!wp_next_scheduled('check_licence')) {
        wp_schedule_event(time(), 'daily', 'check_licence');
    }
}
add_action('wp', 'check_licence_cron');




add_filter( 'woocommerce_available_payment_gateways',  'woo052b_available_payment_gateways', 1); 
 

//////////////////
// Shipping and payment methods
//////////////////
function woo052b_available_payment_gateways( $gateways ) 
{ 
	if(WC()->session) {
		$chosen_shipping_rates = WC()->session->get( 'chosen_shipping_methods' );
  
		if($chosen_shipping_rates) {
			if ( in_array( 'flat_rate:9', $chosen_shipping_rates ) ) :

				unset( $gateways['bacs'] );
				unset( $gateways['paypal'] );
				unset( $gateways['przelewy24'] );		
			endif;
			
			
			if(in_array( 'free_shipping:6', $chosen_shipping_rates )) {
				global $woocommerce;
				$items = $woocommerce->cart->get_cart();
				$cat_ids = [];
				foreach($items as $item) {
					$term_list = wp_get_post_terms($item['product_id'],'product_cat',array('fields'=>'ids'));
					foreach($term_list as $t) {
						$cat_ids[] = $t;
					}
				}
				
				$cat_ids = array_unique($cat_ids);
				
				if(in_array(35, $cat_ids) || in_array(29, $cat_ids)) {
					unset( $gateways['cod'] );
				} 
			}
			 
			if ( in_array( 'flat_rate:5', $chosen_shipping_rates )) :
				unset( $gateways['cod'] );
			endif;
		}
	}
	
	return $gateways;  
}
