<?php
/**
 * Optical Glasses functions and definitions
 *
 * @package Optical Glasses
 * @subpackage optical_glasses
 */

function optical_glasses_setup() {

	load_theme_textdomain( 'optical-glasses', get_template_directory() . '/languages' );
	add_theme_support( 'automatic-feed-links' );
	add_theme_support( 'woocommerce' );
	add_theme_support( 'title-tag' );
	add_theme_support( "responsive-embeds" );
	add_theme_support( 'wp-block-styles' );
	add_theme_support( 'align-wide' );
	add_theme_support( 'post-thumbnails' );
	add_image_size( 'optical-glasses-featured-image', 2000, 1200, true );
	add_image_size( 'optical-glasses-thumbnail-avatar', 100, 100, true );

	// Set the default content width.
	$GLOBALS['content_width'] = 525;

	// This theme uses wp_nav_menu() in two locations.
	register_nav_menus( array(
		'primary-menu'    => __( 'Primary Menu', 'optical-glasses' ),
	) );

	// Add theme support for Custom Logo.
	add_theme_support( 'custom-logo', array(
		'width'       => 250,
		'height'      => 250,
		'flex-width'  => true,
    	'flex-height' => true,
	) );

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

	add_theme_support( 'custom-background', array(
		'default-color' => 'ffffff'
	) );

	/*
	 * Enable support for Post Formats.
	 *
	 * See: https://codex.wordpress.org/Post_Formats
	 */
	add_theme_support( 'post-formats', array('image','video','gallery','audio',) );

	add_theme_support( 'html5', array('comment-form','comment-list','gallery','caption',) );

	add_theme_support( 'custom-header', apply_filters( 'optical_glasses_custom_header_args', array(
        'default-text-color' => 'fff',
        'header-text'        => false,
        'width'              => 1600,
        'height'             => 400,
        'flex-width'         => true,
        'flex-height'        => true,
        'wp-head-callback'   => 'optical_glasses_header_style',
        'default-image'      => get_template_directory_uri() . '/assets/images/sliderimage.png',
    ) ) );

	/**
	 * Implement the Custom Header feature.
	 */
	require get_parent_theme_file_path( '/inc/custom-header.php' );

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

// Add function after setup:
function optical_glasses_conditional_editor_styles() {
	
	add_editor_style( array( 'assets/css/editor-style.css', optical_glasses_fonts_url() ) );
}
add_action( 'after_setup_theme', 'optical_glasses_conditional_editor_styles', 11 );

function optical_glasses_fonts_url() {

	$optical_glasses_font_family = array();

	$optical_glasses_font_family[] = 'Satisfy';
	$optical_glasses_font_family[] = 'DM+Sans:ital,opsz,wght@0,9..40,100..1000;1,9..40,100..1000';
	$optical_glasses_font_family[] = 'Montserrat:ital,wght@0,100..900;1,100..900';
	$optical_glasses_font_family[] = 'Sora:wght@100..800';
	$optical_glasses_font_family[] = 'Outfit:wght@100..900';
	$optical_glasses_font_family[] = 'League+Spartan:wght@100..900';
	$optical_glasses_font_family[] = 'Protest+Strike';
	$optical_glasses_font_family[] = 'Inter:wght@100..900';
	$optical_glasses_font_family[] = 'DM+Serif+Display:ital@0;1';
	$optical_glasses_font_family[] = 'Open+Sans:ital,wght@0,300..800;1,300..800';
	$optical_glasses_font_family[] = 'Karla:ital,wght@0,200..800;1,200..800';

	$optical_glasses_font_url = 'https://fonts.googleapis.com/css2?family=' . implode( '&family=', $optical_glasses_font_family ) . '&display=swap';

	return esc_url_raw( $optical_glasses_font_url );
}
/**
 * Register widget area.
 */
function optical_glasses_widgets_init() {
	register_sidebar( array(
		'name'          => __( 'Blog Sidebar', 'optical-glasses' ),
		'id'            => 'sidebar-1',
		'description'   => __( 'Add widgets here to appear in your sidebar on blog posts and archive pages.', 'optical-glasses' ),
		'before_widget' => '<section id="%1$s" class="widget %2$s">',
		'after_widget'  => '</section>',
		'before_title'  => '<h3 class="widget-title">',
		'after_title'   => '</h3>',
	) );

	register_sidebar( array(
		'name'          => __( 'Page Sidebar', 'optical-glasses' ),
		'id'            => 'sidebar-2',
		'description'   => __( 'Add widgets here to appear in your sidebar on pages.', 'optical-glasses' ),
		'before_widget' => '<section id="%1$s" class="widget %2$s">',
		'after_widget'  => '</section>',
		'before_title'  => '<h3 class="widget-title">',
		'after_title'   => '</h3>',
	) );

	register_sidebar( array(
		'name'          => __( 'Sidebar 3', 'optical-glasses' ),
		'id'            => 'sidebar-3',
		'description'   => __( 'Add widgets here to appear in your sidebar on blog posts and archive pages.', 'optical-glasses' ),
		'before_widget' => '<section id="%1$s" class="widget %2$s">',
		'after_widget'  => '</section>',
		'before_title'  => '<h3 class="widget-title">',
		'after_title'   => '</h3>',
	) );

	register_sidebar( array(
		'name'          => __( 'Footer 1', 'optical-glasses' ),
		'id'            => 'footer-1',
		'description'   => __( 'Add widgets here to appear in your footer.', 'optical-glasses' ),
		'before_widget' => '<section id="%1$s" class="widget %2$s">',
		'after_widget'  => '</section>',
		'before_title'  => '<h3 class="widget-title">',
		'after_title'   => '</h3>',
	) );

	register_sidebar( array(
		'name'          => __( 'Footer 2', 'optical-glasses' ),
		'id'            => 'footer-2',
		'description'   => __( 'Add widgets here to appear in your footer.', 'optical-glasses' ),
		'before_widget' => '<section id="%1$s" class="widget %2$s">',
		'after_widget'  => '</section>',
		'before_title'  => '<h3 class="widget-title">',
		'after_title'   => '</h3>',
	) );

	register_sidebar( array(
		'name'          => __( 'Footer 3', 'optical-glasses' ),
		'id'            => 'footer-3',
		'description'   => __( 'Add widgets here to appear in your footer.', 'optical-glasses' ),
		'before_widget' => '<section id="%1$s" class="widget %2$s">',
		'after_widget'  => '</section>',
		'before_title'  => '<h3 class="widget-title">',
		'after_title'   => '</h3>',
	) );

	register_sidebar( array(
		'name'          => __( 'Footer 4', 'optical-glasses' ),
		'id'            => 'footer-4',
		'description'   => __( 'Add widgets here to appear in your footer.', 'optical-glasses' ),
		'before_widget' => '<section id="%1$s" class="widget %2$s">',
		'after_widget'  => '</section>',
		'before_title'  => '<h3 class="widget-title">',
		'after_title'   => '</h3>',
	) );
}
add_action( 'widgets_init', 'optical_glasses_widgets_init' );
/**
 * Enqueue scripts and styles.
 */
function optical_glasses_scripts() {
	$optical_glasses_theme_version = wp_get_theme()->get( 'Version' );

	// Add custom fonts, used in the main stylesheet.
	wp_enqueue_style( 'optical-glasses-fonts', optical_glasses_fonts_url(), array(), $optical_glasses_theme_version );

	// Bootstrap
	wp_enqueue_style( 'bootstrap-css', get_theme_file_uri( '/assets/css/bootstrap.css' ), array(), $optical_glasses_theme_version );

	// owl
	wp_enqueue_style( 'owl-carousel-css', get_theme_file_uri( '/assets/css/owl.carousel.css' ) );

	// Theme stylesheet.
	wp_enqueue_style( 'optical-glasses-style', get_stylesheet_uri(), array(), $optical_glasses_theme_version );
	require get_parent_theme_file_path( '/tp-theme-color.php' );
	wp_add_inline_style( 'optical-glasses-style', $optical_glasses_tp_theme_css );
	wp_style_add_data( 'optical-glasses-style', 'rtl', 'replace' );

	require get_parent_theme_file_path( '/tp-body-width-layout.php' );
	wp_add_inline_style( 'optical-glasses-style', $optical_glasses_tp_theme_css );
	wp_style_add_data( 'optical-glasses-style', 'rtl', 'replace' );

	// Theme block stylesheet.
	wp_enqueue_style( 'optical-glasses-block-style', get_theme_file_uri( '/assets/css/blocks.css' ), array( 'optical-glasses-style' ), $optical_glasses_theme_version );

	// Fontawesome
	wp_enqueue_style( 'fontawesome-css', get_theme_file_uri( '/assets/css/fontawesome-all.css' ), array(), $optical_glasses_theme_version );

	wp_enqueue_style('swiper-css', esc_url(get_template_directory_uri())."/assets/css/swiper-bundle.css");

	// Scripts
	wp_enqueue_script( 'optical-glasses-custom-scripts', get_template_directory_uri() . '/assets/js/optical-glasses-custom.js', array( 'jquery' ), $optical_glasses_theme_version, true );
	
	wp_enqueue_script( 'owl-carousel-js', get_theme_file_uri( '/assets/js/owl.carousel.js' ), array( 'jquery' ), true );
	
	wp_enqueue_script( 'bootstrap-js', get_theme_file_uri( '/assets/js/bootstrap.js' ), array( 'jquery' ), $optical_glasses_theme_version, true );

	wp_enqueue_script( 'optical-glasses-focus-nav', get_template_directory_uri() . '/assets/js/focus-nav.js', array( 'jquery' ), $optical_glasses_theme_version, true );

	if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) {
		wp_enqueue_script( 'comment-reply' );
	}

    wp_enqueue_script('swiper-js', esc_url(get_template_directory_uri()). '/assets/js/swiper-bundle.js', array('jquery'));

	// ==========================
	// INLINE CSS (WORKING FIX)
	// ==========================

	$optical_glasses_tp_theme_css = '';

	// Theme Color CSS
	$optical_glasses_tp_theme_css_temp = '';
	require get_parent_theme_file_path( '/tp-theme-color.php' );
	if ( isset( $optical_glasses_tp_theme_css ) ) {
		$optical_glasses_tp_theme_css_temp .= $optical_glasses_tp_theme_css;
	}

	// Body Width Layout CSS
	$optical_glasses_tp_theme_css = '';
	require get_parent_theme_file_path( '/tp-body-width-layout.php' );
	if ( isset( $optical_glasses_tp_theme_css ) ) {
		$optical_glasses_tp_theme_css_temp .= $optical_glasses_tp_theme_css;
	}

	// Assign final CSS
	$optical_glasses_tp_theme_css = $optical_glasses_tp_theme_css_temp;

	// Font family CSS
	$optical_glasses_body_font_family    = get_theme_mod( 'optical_glasses_body_font_family', '' );
	$optical_glasses_heading_font_family = get_theme_mod( 'optical_glasses_heading_font_family', '' );

	$optical_glasses_tp_theme_css .= '
		body, p.simplep, .more-btn a{
			font-family: ' . esc_html( $optical_glasses_body_font_family ) . ';
		}
		h1,h2,h3,h4,h5,h6,.menubar,.logo h1,.logo p.site-title,
		p.simplep a,#slider p.slidertop-title,.more-btn a,
		.wc-block-checkout__actions_row .wc-block-components-checkout-place-order-button,
		.wc-block-cart__submit-container a,
		.woocommerce #respond input#submit,
		.woocommerce a.button,
		.woocommerce button.button,
		.woocommerce input.button,
		.woocommerce #respond input#submit.alt,
		.woocommerce a.button.alt,
		.woocommerce button.button.alt,
		.woocommerce input.button.alt,
		#theme-sidebar button[type="submit"],
		#footer button[type="submit"]{
			font-family: ' . esc_html( $optical_glasses_heading_font_family ) . ';
		}
	';

	// Add inline CSS ONCE
	wp_add_inline_style( 'optical-glasses-style', $optical_glasses_tp_theme_css );
}
add_action( 'wp_enqueue_scripts', 'optical_glasses_scripts' );

/*radio button sanitization*/
function optical_glasses_sanitize_choices( $input, $setting ) {
    global $wp_customize;
    $control = $wp_customize->get_control( $setting->id );
    if ( array_key_exists( $input, $control->choices ) ) {
        return $input;
    } else {
        return $setting->default;
    }
}

// Sanitize Sortable control.
function optical_glasses_sanitize_sortable( $val, $setting ) {
	if ( is_string( $val ) || is_numeric( $val ) ) {
		return array(
			esc_attr( $val ),
		);
	}
	$sanitized_value = array();
	foreach ( $val as $item ) {
		if ( isset( $setting->manager->get_control( $setting->id )->choices[ $item ] ) ) {
			$sanitized_value[] = esc_attr( $item );
		}
	}
	return $sanitized_value;
}
/* Excerpt Limit Begin */
function optical_glasses_excerpt_function($excerpt_count = 35) {
    $optical_glasses_excerpt = get_the_excerpt();

    $optical_glasses_TEXT_excerpt = wp_strip_all_tags($optical_glasses_excerpt);

    $optical_glasses_excerpt_limit = esc_attr(get_theme_mod('optical_glasses_excerpt_count', $excerpt_count));

    $optical_glasses_theme_excerpt = implode(' ', array_slice(explode(' ', $optical_glasses_TEXT_excerpt), 0, $optical_glasses_excerpt_limit));

    return $optical_glasses_theme_excerpt;
}

// Change number or products per row to 3
add_filter('loop_shop_columns', 'optical_glasses_loop_columns');
if (!function_exists('optical_glasses_loop_columns')) {
	function optical_glasses_loop_columns() {
		$columns = get_theme_mod( 'optical_glasses_per_columns', 3 );
		return $columns;
	}
}

// Category count 
function optical_glasses_display_post_category_count() {
    $optical_glasses_category = get_the_category();
    $optical_glasses_category_count = ($optical_glasses_category) ? count($optical_glasses_category) : 0;
    $optical_glasses_category_text = ($optical_glasses_category_count === 1) ? 'category' : 'categories'; // Check for pluralization
    echo $optical_glasses_category_count . ' ' . $optical_glasses_category_text;
}

//post tag
function optical_glasses_custom_tags_filter($optical_glasses_tag_list) {
    // Replace the comma (,) with an empty string
    $optical_glasses_tag_list = str_replace(', ', '', $optical_glasses_tag_list);

    return $optical_glasses_tag_list;
}
add_filter('the_tags', 'optical_glasses_custom_tags_filter');

function optical_glasses_sanitize_dropdown_pages( $page_id, $setting ) {
  // Ensure $input is an absolute integer.
  $page_id = absint( $page_id );
  // If $page_id is an ID of a published page, return it; otherwise, return the default.
  return ( 'publish' == get_post_status( $page_id ) ? $page_id : $setting->default );
}

function optical_glasses_custom_output_tags() {
    $optical_glasses_tags = get_the_tags();

    if ( $optical_glasses_tags ) {
        $optical_glasses_tags_output = '<div class="post_tag">Tags: ';

        $optical_glasses_first_tag = reset( $optical_glasses_tags );

        foreach ( $optical_glasses_tags as $tag ) {
            $optical_glasses_tags_output .= '<a href="' . esc_url( get_tag_link( $tag ) ) . '" rel="tag" class="me-2">' . esc_html( $tag->name ) . '</a>';

            if ( $tag !== $optical_glasses_first_tag ) {
                $optical_glasses_tags_output .= ' ';
            }
        }

        $optical_glasses_tags_output .= '</div>';

        echo wp_kses_post( $optical_glasses_tags_output );
    }
}

//Change number of products that are displayed per page (shop page)
add_filter( 'loop_shop_per_page', 'optical_glasses_per_page', 20 );
function optical_glasses_per_page( $optical_glasses_cols ) {
  	$optical_glasses_cols = get_theme_mod( 'optical_glasses_product_per_page', 9 );
	return $optical_glasses_cols;
}

function optical_glasses_sanitize_number_range( $number, $setting ) {

	// Ensure input is an absolute integer.
	$number = absint( $number );

	// Get the input attributes associated with the setting.
	$atts = $setting->manager->get_control( $setting->id )->input_attrs;

	// Get minimum number in the range.
	$min = ( isset( $atts['min'] ) ? $atts['min'] : $number );

	// Get maximum number in the range.
	$max = ( isset( $atts['max'] ) ? $atts['max'] : $number );

	// Get step.
	$step = ( isset( $atts['step'] ) ? $atts['step'] : 1 );

	// If the number is within the valid range, return it; otherwise, return the default
	return ( $min <= $number && $number <= $max && is_int( $number / $step ) ? $number : $setting->default );
}

function optical_glasses_sanitize_checkbox( $input ) {
	// Boolean check
	return ( ( isset( $input ) && true == $input ) ? true : false );
}

function optical_glasses_sanitize_number_absint( $number, $setting ) {
	// Ensure $number is an absolute integer (whole number, zero or greater).
	$number = absint( $number );

	// If the input is an absolute integer, return it; otherwise, return the default
	return ( $number ? $number : $setting->default );
}

function optical_glasses_sanitize_select( $input, $setting ) {
	$input = sanitize_key( $input );
	$choices = $setting->manager->get_control( $setting->id )->choices;
	return ( array_key_exists( $input, $choices ) ? $input : $setting->default );
}

/**
 * Use front-page.php when Front page displays is set to a static page.
 */
function optical_glasses_front_page_template( $template ) {
	return is_home() ? '' : $template;
}
add_filter( 'frontpage_template','optical_glasses_front_page_template' );

// logo
function optical_glasses_logo_width(){

	$optical_glasses_logo_width   = get_theme_mod( 'optical_glasses_logo_width', 80 );

	echo "<style type='text/css' media='all'>"; ?>
		img.custom-logo{
		    width: <?php echo absint( $optical_glasses_logo_width ); ?>px;
		    max-width: 100%;
		}
	<?php echo "</style>";
}

add_action( 'wp_head', 'optical_glasses_logo_width' );

function optical_glasses_theme_setup() {

	define('OPTICAL_GLASSES_CREDIT',__('https://www.themespride.com/products/optical-glasses', 'optical-glasses') );
	if ( ! function_exists( 'OPTICAL_GLASSES_CREDIT' ) ) {
		function OPTICAL_GLASSES_CREDIT(){
			echo "<a href=".esc_url(OPTICAL_GLASSES_CREDIT)." target='_blank'>".esc_html__(get_theme_mod('optical_glasses_footer_text',__('Optical Glasses WordPress Theme','optical-glasses')))."</a>";
		}
	}

	/**
	 * Custom template tags for this theme.
	 */
	require get_parent_theme_file_path( '/inc/template-tags.php' );

	/**
	 * Additional features to allow styling of the templates.
	 */
	require get_parent_theme_file_path( '/inc/template-functions.php' );

	/**
	 * Customizer additions.
	 */
	require get_parent_theme_file_path( '/inc/customizer.php' );

	/**
	 * Load Theme Web File
	 */
	require get_parent_theme_file_path('/inc/wptt-webfont-loader.php' );
	/**
	 * Load Theme Web File
	 */
	require get_parent_theme_file_path( '/inc/controls/customize-control-toggle.php' );
	/**
	 * load sortable file
	 */
	require get_parent_theme_file_path( '/inc/controls/sortable-control.php' );

	/**
	 * TGM Recommendation
	 */
	require get_parent_theme_file_path( '/inc/TGM/tgm.php' );

	/**
	 * About Theme Page
	 */
	require get_parent_theme_file_path( '/inc/about-theme.php' );

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



//Admin Enqueue for Admin
function optical_glasses_admin_enqueue_scripts(){
	wp_enqueue_style('optical-glasses-admin-style', get_template_directory_uri() . '/assets/css/admin.css');
	wp_register_script( 'optical-glasses-admin-script', get_template_directory_uri() . '/assets/js/optical-glasses-admin.js', array( 'jquery' ), '', true );

	wp_localize_script(
		'optical-glasses-admin-script',
		'optical_glasses',
		array(
			'admin_ajax'	=>	admin_url('admin-ajax.php'),
			'wpnonce'			=>	wp_create_nonce('optical_glasses_dismissed_notice_nonce')
		)
	);
	wp_enqueue_script('optical-glasses-admin-script');

    wp_localize_script( 'optical-glasses-admin-script', 'optical_glasses_ajax_object',
        array( 'ajax_url' => admin_url( 'admin-ajax.php' ) )
    );
}
add_action( 'admin_enqueue_scripts', 'optical_glasses_admin_enqueue_scripts' );


// get started
add_action( 'wp_ajax_optical_glasses_dismissed_notice_handler', 'optical_glasses_ajax_notice_handler' );

function optical_glasses_ajax_notice_handler() {
	if (!wp_verify_nonce($_POST['wpnonce'], 'optical_glasses_dismissed_notice_nonce')) {
		exit;
	}
    if ( isset( $_POST['type'] ) ) {
        $type = sanitize_text_field( wp_unslash( $_POST['type'] ) );
        update_option( 'dismissed-' . $type, TRUE );
    }
}

function optical_glasses_activation_notice() { 

	if ( ! get_option('dismissed-get_started', FALSE ) ) { ?>

    <div class="optical-glasses-notice-wrapper updated notice notice-get-started-class is-dismissible" data-notice="get_started">
        <div class="optical-glasses-getting-started-notice clearfix">
        	<div class="row-top">
	            <div class="optical-glasses-theme-notice-content">
	                <h2 class="optical-glasses-notice-h2">
	                    <?php
	                printf(
	                /* translators: 1: welcome page link starting html tag, 2: welcome page link ending html tag. */
	                    esc_html__( 'Install the Demo Import Plugin now to instantly set up your site like the live preview.', 'optical-glasses' ), '<strong>'. wp_get_theme()->get('Name'). '</strong>' );
	                ?>
	                </h2>
	                <?php 
					$optical_glasses_theme = wp_get_theme();
					?>
					<a class="optical-glasses-btn-get-started button button-primary button-hero optical-glasses-button-padding" href="<?php echo esc_url( admin_url( 'themes.php?page=optical-glasses-about' ) ); ?>">
					    <?php 
					    echo sprintf(
					        esc_html__( 'Get Started with %s Theme', 'optical-glasses' ),
					        esc_html( $optical_glasses_theme->get( 'Name' ) )
					    ); 
					    ?>
					</a>
	            </div>
	            <div class="image-box">
			    	<img src="<?php echo esc_url( get_template_directory_uri() . '/assets/images/theme-notice.png' ); ?>" alt="<?php echo esc_attr__( 'Optical Glasses', 'optical-glasses' ); ?>" />
				</div>
	        </div>
        </div>
    </div>
<?php }

}
add_action( 'admin_notices', 'optical_glasses_activation_notice' );

add_action('after_switch_theme', 'optical_glasses_setup_options');
function optical_glasses_setup_options () {
    update_option('dismissed-get_started', FALSE );
}

// Get Started Detail Notice - Dismiss permanently
function optical_glasses_dismissed_get_started_detail_notice() {
    update_option( 'dismissed-get_started-detail', true );
    wp_send_json_success();
}
add_action( 'wp_ajax_optical_glasses_dismissed_get_started_detail_notice', 'optical_glasses_dismissed_get_started_detail_notice' );
add_action( 'wp_ajax_nopriv_optical_glasses_dismissed_get_started_detail_notice', 'optical_glasses_dismissed_get_started_detail_notice' );

// Reset on theme switch
add_action('after_switch_theme', 'optical_glasses_setup_settings');
function optical_glasses_setup_settings() {
    update_option('dismissed-get_started', false );
    update_option('dismissed-get_started-detail', false );
}

add_action( 'wp_ajax_optical_glasses_popup_done', 'optical_glasses_popup_done' );
function optical_glasses_popup_done() {
	$theme_slug = get_stylesheet();
	update_option( $theme_slug . '_demo_popup_shown', true );
	wp_die();
}