<?php

if ( ! function_exists( 'wp_body_open' ) ) {

	function wp_body_open() {
		/**
		 * Triggered after the opening <body> tag.
		 */
		do_action( 'wp_body_open' );
	}
}

// Global variables define
define('SPASALON_TEMPLATE_DIR_URI' , get_template_directory_uri() . '/free' );
define('SPASALON_TEMPLATE_DIR' , get_template_directory() . '/free' );
define('SPASALON_THEME_FUNCTIONS_PATH' , SPASALON_TEMPLATE_DIR.'/functions');
$spasalon_theme = wp_get_theme();
// Theme functions file including
require( SPASALON_THEME_FUNCTIONS_PATH . '/customizer/customizer-pro-feature.php');
require( SPASALON_THEME_FUNCTIONS_PATH . '/spasalon_default_data.php');
require( SPASALON_THEME_FUNCTIONS_PATH . '/scripts/script.php');
require( SPASALON_THEME_FUNCTIONS_PATH . '/menu/default_menu_walker.php');
require( SPASALON_THEME_FUNCTIONS_PATH . '/menu/spasalon_nav_walker.php');
require( SPASALON_THEME_FUNCTIONS_PATH . '/widget/sidebars.php');
require( SPASALON_THEME_FUNCTIONS_PATH . '/customizer/banner-settings.php');
require( SPASALON_THEME_FUNCTIONS_PATH . '/customizer/general-settings.php');
require( SPASALON_THEME_FUNCTIONS_PATH . '/customizer/home-page.php');
require( SPASALON_THEME_FUNCTIONS_PATH . '/class-tgm-plugin-activation.php');

require( SPASALON_THEME_FUNCTIONS_PATH . '/customizer/customizer.php');
require( SPASALON_THEME_FUNCTIONS_PATH . '/customizer/customizer_recommended_plugin.php');
require( SPASALON_THEME_FUNCTIONS_PATH . '/font/font.php');
require( SPASALON_THEME_FUNCTIONS_PATH . '/meta-box/metabox.php');
require( SPASALON_THEME_FUNCTIONS_PATH . '/template-tag.php');
require( SPASALON_THEME_FUNCTIONS_PATH . '/widget/wbr-register-page-widget.php');
require( SPASALON_THEME_FUNCTIONS_PATH . '/widget/wbr-news-widget.php');
require( SPASALON_THEME_FUNCTIONS_PATH . '/widget/post-widget.php');
// Spasalon Info Page
//require( SPASALON_THEME_FUNCTIONS_PATH . '/spasalon-info/welcome-screen.php');

function spasalon_customizer_css() {
	wp_enqueue_style( 'spasalon-customizer-info', SPASALON_TEMPLATE_DIR_URI . '/css/pro-feature.css' );
}
add_action( 'admin_init', 'spasalon_customizer_css' );

if ( ! function_exists( 'spasalon_setup' ) ) :

function spasalon_setup() {
	
	/*
	 * Make theme available for translation.
	 * Translations can be filed in the /languages/ directory.
	 */
	
	load_theme_textdomain( 'spasalon', 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.
	 */
	 
	add_theme_support( 'title-tag' );	
	// supports featured image
	
	add_theme_support( 'post-thumbnails' );	
	// This theme uses wp_nav_menu() in two locations.	
	register_nav_menus( array(
	
		'primary' => esc_html__( 'Primary Menu', 'spasalon' ),		
		'footer'  => esc_html__( 'Footer Menu', 'spasalon' ),
		
	) );	
	// woocommerce support	
	add_theme_support( 'woocommerce' );	
	// Woocommerce Gallery Support
	add_theme_support( 'wc-product-gallery-zoom' );
	add_theme_support( 'wc-product-gallery-lightbox' );
	add_theme_support( 'wc-product-gallery-slider' );	
	//Custom logo	
	add_theme_support( 'custom-logo' , array(
	
	   'class'       => 'navbar-brand',	   
	   'width'       => 150,	   
	   'height'      => 35,	   
	   'flex-width' => true,	   
	   'flex-height' => true,
	   'header-text' => array( 'site-title', 'site-description' ),
	   
	) );
	add_editor_style();
	$spasalon_theme = wp_get_theme(); // gets the current theme
	if ( 'Spasalon' == $spasalon_theme->name || 'SpaSalon Pro' == $spasalon_theme->name || 'Spasalon Pro' == $spasalon_theme->name )
	{
	 	if ( is_admin() ) {
			require SPASALON_TEMPLATE_DIR . '/admin/admin-init.php';
		}
	}
}
endif; // spasalon_setup
add_action( 'after_setup_theme', 'spasalon_setup' );


// Replace logo Anchor class
add_filter('get_custom_logo', 'spasalon_custom_logo_output', 10);
function spasalon_custom_logo_output( $spasalon_html ){	
	$spasalon_html = str_replace( 'custom-logo-link', 'navbar-brand', $spasalon_html );	
	return $spasalon_html;
}

// excerpt length
function spasalon_excerpt_length( $length ) {
	return 20;	
}
add_filter( 'excerpt_length', 'spasalon_excerpt_length', 999 );


function spasalon_inline_style() {
	$spasalon_custom_css= '';	
	$spasalon_current_options = wp_parse_args(  get_option( 'spa_theme_options'));
	$spasalon_service_content = ! empty($spasalon_current_options['spasalon_service_content']) ? $spasalon_current_options['spasalon_service_content'] : json_encode(
			array(
				array(
					'color'      => '#f22853',
				),
				array(
					'color'      => '#00bcd4',
				),
				array(
					'color'      => '#fe8000',
				),
				array(
					'color'      => '#1abac8',
				),
			)
		);
	
	if ( ! empty( $spasalon_service_content ) ) {
		$spasalon_service_content = json_decode( $spasalon_service_content );
		
		foreach ( $spasalon_service_content as $spasalon_key => $spasalon_service_item ) {
			$spasalon_box_nb = $spasalon_key + 1;
			if ( ! empty( $spasalon_service_item->color ) ) {
				
				$spasalon_color = ! empty( $spasalon_service_item->color ) ? apply_filters( 'spasalon_translate_single_string', $spasalon_service_item->color, 'searvice section' ) : '';
				
				$spasalon_custom_css .= '.service-box:nth-child(' . esc_attr( $spasalon_box_nb ) . ') .service-icon i {
                            background-color: ' . esc_attr( $spasalon_color ) . ';
				}';
				
				
			}
		}
	}
	wp_add_inline_style( 'style', $spasalon_custom_css );
}

add_action( 'wp_enqueue_scripts', 'spasalon_inline_style' );

// Replaces the excerpt "more" text by a link
function spasalon_new_excerpt_more($more) {	
    global $post;	
	$spasalon_link = sprintf( '<p><a href="%1$s" class="more-link">%2$s</a></p>',
					esc_url( get_permalink( get_the_ID() ) ),		
					sprintf( esc_html__( 'Read More' , 'spasalon' ) )
		
	);
	return ' &hellip; ' . $spasalon_link;	
}
add_filter('excerpt_more', 'spasalon_new_excerpt_more');

function spasalon_modify_read_more_link() {
	
	global $post;	
	$spasalon_link = '<a class="more-link" href="'.esc_url(get_permalink()).'">'.esc_html__( 'Read More' , 'spasalon' ).'</a>';	
    return $spasalon_link;
}
add_filter( 'the_content_more_link', 'spasalon_modify_read_more_link' );

// content width
function spasalon_content_width() {	
	$GLOBALS['content_width'] = apply_filters( 'spasalon_content_width', 960 );
}
add_action( 'after_setup_theme', 'spasalon_content_width', 0 );


// custom css 
function spasalon_custom_css_function(){
	
	$spasalon_current_options = wp_parse_args(  get_option( 'spa_theme_options', array() ), spasalon_default_data() );
	echo '<style>';
	echo esc_html($spasalon_current_options['spa_custom_css']);
	echo '</style>';	
	}
add_action('wp_head','spasalon_custom_css_function');

the_tags();

add_action('admin_head', 'spasalon_remove_wiget');
function spasalon_remove_wiget() {
  echo '<style>
#sidebar-service {
    display: none !important;
}
</style>';
}

//Custom CSS compatibility
function spasalon_custom_css_compatibility() {
	$spasalon_options = spasalon_default_data();
	$spasalon_current_options = wp_parse_args(get_option('spa_theme_options', array()), $spasalon_options);
	if ($spasalon_current_options['spa_custom_css'] != '' && $spasalon_current_options['spa_custom_css'] != 'nomorenow') {
	    $spasalon_css = '';
	    $spasalon_css .= $spasalon_current_options['spa_custom_css'];
	    $spasalon_css .= (string) wp_get_custom_css(get_stylesheet());
	    $spasalon_current_options['spa_custom_css'] = 'nomorenow';
	    update_option('spa_theme_options', $spasalon_current_options);
	    wp_update_custom_css_post($spasalon_css, array());
	}
}
add_action('wp_loaded', 'spasalon_custom_css_compatibility');

if( $spasalon_theme->name == 'Spasalon' || $spasalon_theme->name == 'Spasalon child' || $spasalon_theme->name == 'Spasalon Child') {
    // Notice to add required plugin
    function spasalon_admin_plugin_notice_warn() {
        global $hook_suffix;
        $theme_name = wp_get_theme();
        if($hook_suffix === 'themes.php'){
            if ( get_option( 'dismissed-spasalon_comanion_plugin', false ) ) {
               return;
            }
            if ( function_exists('webriti_companion_activate')) {
                return;
            }?>
            <div class="updated notice is-dismissible spasalon-theme-notice">

                <div class="owc-header">
                    <h2 class="theme-owc-title">               
                        <svg height="60" width="60" id="Layer_1" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 70 70"><defs><style>.cls-1{font-size:33px;font-family:Verdana-Bold, Verdana;font-weight:700;}</style></defs><title>Artboard 1</title><text class="cls-1" transform="translate(-0.56 51.25)">WC</text></svg>
                        <?php echo esc_html('Webriti Companion','spasalon');?>
                    </h2>
                </div>
                <div class="spasalon-theme-content">
                    <h3><?php printf (esc_html__('Thank you for installing the %1$s theme.', 'spasalon'), esc_html($theme_name)); ?></h3>

                    <p><?php esc_html_e( 'We highly recommend you to install and activate the', 'spasalon' ); ?>
                        <b><?php esc_html_e( 'Webriti Companion', 'spasalon' ); ?></b> plugin.
                        <br>
                        <?php esc_html_e( 'This plugin will unlock enhanced features to build a beautiful website.', 'spasalon' ); ?>
                    </p>
                    <button id="install-plugin-button-welcome-page" data-plugin-url="<?php echo esc_url( 'https://webriti.com/extensions/webriti-companion.zip');?>"><?php echo esc_html__( 'Install', 'spasalon' ); ?></button>
                </div>
            </div>
            
            <script type="text/javascript">
                jQuery(function($) {
                $( document ).on( 'click', '.spasalon-theme-notice .notice-dismiss', function () {
                    var type = $( this ).closest( '.spasalon-theme-notice' ).data( 'notice' );
                    $.ajax( ajaxurl,
                      {
                        type: 'POST',
                        data: {
                          action: 'dismissed_notice_handler',
                          type: type,
                        }
                      } );
                  } );
              });
            </script>
       <?php
        }
    }
    add_action( 'admin_notices', 'spasalon_admin_plugin_notice_warn' );
    add_action( 'wp_ajax_dismissed_notice_handler', 'spasalon_ajax_notice_handler');

    function spasalon_ajax_notice_handler() {
        update_option( 'dismissed-spasalon_comanion_plugin', TRUE );
    }
}

// Hook the AJAX action for logged-in users
add_action('wp_ajax_spasalon_check_plugin_status', 'spasalon_check_plugin_status');

function spasalon_check_plugin_status() {
    if (!current_user_can('install_plugins')) {
        wp_send_json_error('You do not have permission to manage plugins.');
        return;
    }

    if (!isset($_POST['plugin_slug'])) {
        wp_send_json_error('No plugin slug provided.');
        return;
    }

    $plugin_slug = sanitize_text_field($_POST['plugin_slug']);
    $plugin_main_file = $plugin_slug . '/' . $plugin_slug . '.php'; // Adjust this based on your plugin structure

    // Check if the plugin exists
    $plugins = get_plugins();
    if (isset($plugins[$plugin_main_file])) {
        if (is_plugin_active($plugin_main_file)) {
            wp_send_json_success(array('status' => 'activated'));
        } else {
            wp_send_json_success(array('status' => 'installed'));
        }
    } else {
        wp_send_json_success(array('status' => 'not_installed'));
    }
}

// Existing AJAX installation function for installing and activating
add_action('wp_ajax_spasalon_install_activate_plugin', 'spasalon_install_and_activate_plugin');

function spasalon_install_and_activate_plugin() {
    if (!current_user_can('install_plugins')) {
        wp_send_json_error('You do not have permission to install plugins.');
        return;
    }

    if (!isset($_POST['plugin_url'])) {
        wp_send_json_error('No plugin URL provided.');
        return;
    }

    // Include necessary WordPress files for plugin installation
    include_once(ABSPATH . 'wp-admin/includes/file.php');
    include_once(ABSPATH . 'wp-admin/includes/misc.php');
    include_once(ABSPATH . 'wp-admin/includes/class-wp-upgrader.php');
    include_once(ABSPATH . 'wp-admin/includes/plugin.php');

    $plugin_url = esc_url($_POST['plugin_url']);
    $plugin_slug = sanitize_text_field($_POST['plugin_slug']);
    $plugin_main_file = $plugin_slug . '/' . $plugin_slug . '.php'; // Ensure this matches your plugin structure

    // Download the plugin file
    WP_Filesystem();
    $temp_file = download_url($plugin_url);

    if (is_wp_error($temp_file)) {
        wp_send_json_error($temp_file->get_error_message());
        return;
    }

    // Unzip the plugin to the plugins folder
    $plugin_folder = WP_PLUGIN_DIR;
    $result = unzip_file($temp_file, $plugin_folder);
    
    // Clean up temporary file
    unlink($temp_file);

    if (is_wp_error($result)) {
        wp_send_json_error($result->get_error_message());
        return;
    }

    // Activate the plugin if it was installed
    $activate_result = activate_plugin($plugin_main_file);

    

    // Return success with redirect URL
    wp_send_json_success(array('redirect_url' => admin_url('admin.php?page=spasalon-welcome')));
}

// Enqueue JavaScript for the button functionality
add_action('admin_enqueue_scripts', 'spasalon_enqueue_plugin_installer_script');

function spasalon_enqueue_plugin_installer_script() {
    global $hook_suffix;
    wp_enqueue_script('spasalon-plugin-installer-js',  SPASALON_TEMPLATE_DIR_URI . '/admin/assets/js/plugin-installer.js', array('jquery'), null, true);
    wp_localize_script('spasalon-plugin-installer-js', 'pluginInstallerAjax', array(
        'ajax_url' => admin_url('admin-ajax.php'),
        'hook_suffix' => $hook_suffix,
        'nonce' => wp_create_nonce('plugin_installer_nonce'),

    ));
}
?>