<?php
/**
 * Functions which enhance the theme by hooking into WordPress
 *
 * @package Portfolio_One
 */

/**
 * Adds custom classes to the array of body classes.
 *
 * @param array $classes Classes for the body element.
 * @return array
 */
function portfolio_one_body_classes( $classes ) {

    $defaults                  = portfolio_one_customizer_defaults();
    

	// Adds a class of hfeed to non-singular pages.
	if ( ! is_singular() ) {
		$classes[] = 'hfeed';
	}

	// Adds a class of no-sidebar when there is no sidebar present.
	if ( ! is_active_sidebar( 'sidebar-1' ) ) {
		$classes[] = 'no-sidebar';
	}
    // Header layout class
    $classes[] = 'header-layout-one';

	return $classes;
}
add_filter( 'body_class', 'portfolio_one_body_classes' );

/**
 * Add a pingback url auto-discovery header for single posts, pages, or attachments.
 */
function portfolio_one_pingback_header() {
	if ( is_singular() && pings_open() ) {
		printf( '<link rel="pingback" href="%s">', esc_url( get_bloginfo( 'pingback_url' ) ) );
	}
}
add_action( 'wp_head', 'portfolio_one_pingback_header' );




/**
* Strip whitespace in dynamic style
*/
if( !function_exists('portfolio_one_strip_css_whitespace') ){
    function portfolio_one_strip_css_whitespace($css){
        $replace = array(
        "#/\*.*?\*/#s" => "",  // Strip C style comments.
        "#\s\s+#"      => " ", // Strip excess whitespace.
        );
        $search = array_keys($replace);
        $css = preg_replace($search, $replace, $css);
        
        $replace = array(
        ": "  => ":",
        "; "  => ";",
        " {"  => "{",
        " }"  => "}",
        ", "  => ",",
        "{ "  => "{",
        ";}"  => "}", // Strip optional semicolons.
        ",\n" => ",", // Don't wrap multiple selectors.
        "\n}" => "}", // Don't wrap closing braces.
        //"} "  => "}\n", // Put each rule on it's own line.
        );
        $search = array_keys($replace);
        $css = str_replace($search, $replace, $css);
        
        return trim($css);
    }
}


if( ! function_exists( 'portfolio_one_excerpt_content' ) ):
    function portfolio_one_excerpt_content( $limit ) {

        $striped_contents   = strip_shortcodes( get_the_excerpt() );
        $striped_content    = strip_tags( $striped_contents );
        $limit_content      = mb_substr( $striped_content, 0 , $limit );
       
        return $limit_content;
    }
endif;



/**
* Display numeric pagination for blogs
*/
if( ! function_exists('portfolio_one_numeric_posts_nav')){
    function portfolio_one_numeric_posts_nav() {
     
        if( is_singular() )
            return;
     
        global $wp_query;
     
        /** Stop execution if there's only 1 page */
        if( $wp_query->max_num_pages <= 1 )
            return;
     
        $paged = get_query_var( 'paged' ) ? absint( get_query_var( 'paged' ) ) : 1;
        $max   = intval( $wp_query->max_num_pages );
     
        /** Add current page to the array */
        if ( $paged >= 1 )
            $links[] = $paged;
     
        /** Add the pages around the current page to the array */
        if ( $paged >= 3 ) {
            $links[] = $paged - 1;
            $links[] = $paged - 2;
        }
     
        if ( ( $paged + 2 ) <= $max ) {
            $links[] = $paged + 2;
            $links[] = $paged + 1;
        }
     
        echo '<div class="add-archive-navigation">';
     
        /** Previous Post Link */
        if ( get_previous_posts_link() )
            printf( '<span class="prev">%s</span>' . "\n", get_previous_posts_link() );

        echo '<ul>';
        /** Link to first page, plus ellipses if necessary */
        if ( ! in_array( 1, $links ) ) {
            $class = 1 == $paged ? ' class="active"' : '';
     
            printf( '<li%s><a href="%s">%s</a></li>' . "\n", $class, esc_url( get_pagenum_link( 1 ) ), '1' );
     
            if ( ! in_array( 2, $links ) )
                echo '<li>...</li>';
        }
     
        /** Link to current page, plus 2 pages in either direction if necessary */
        sort( $links );
        foreach ( (array) $links as $link ) {
            $class = $paged == $link ? ' class="active"' : '';
            printf( '<li%s><a href="%s">%s</a></li>' . "\n", $class, esc_url( get_pagenum_link( $link ) ), $link );
        }
     
        /** Link to last page, plus ellipses if necessary */
        if ( ! in_array( $max, $links ) ) {
            if ( ! in_array( $max - 1, $links ) )
                echo '<li>...</li>' . "\n";
     
            $class = $paged == $max ? ' class="active"' : '';
            printf( '<li%s><a href="%s">%s</a></li>' . "\n", $class, esc_url( get_pagenum_link( $max ) ), $max );
        }
        echo '</ul>';
        /** Next Post Link */
        if ( get_next_posts_link() )
            printf( '<span class="next">%s</span>' . "\n", get_next_posts_link() );
     
        echo '</div>' . "\n";
     
    }
}


 /**
   * Get all registered widget areas list
   * 
   */
/* Creating a function that will return an array of all the registered widget areas. */
if ( ! function_exists('portfolio_one_get_widget_areas')):
    function portfolio_one_get_widget_areas(){
        global $wp_registered_sidebars;
        $widgets_areas 		= array();
        $get_widget_areas 	= $wp_registered_sidebars;
        if ( ! empty( $get_widget_areas ) ) {
            foreach ( $get_widget_areas as $widget_area ) {
                $name 	= isset ( $widget_area['name'] ) ? $widget_area['name'] : '';
                $id 	= isset ( $widget_area['id'] ) ? $widget_area['id'] : '';
                if ( $name && $id ) {
                    $widgets_areas[$id] = $name;
                }
            }
        }
        return $widgets_areas;
    }
  endif;


  /**
   * Sidebar body class Controller function
   * 
   */
  add_filter( 'body_class', 'portfolio_one_sidebar_body_class' );
  if( ! function_exists( 'portfolio_one_sidebar_body_class' ) ):
    function portfolio_one_sidebar_body_class($classes) {
        global $post;
        $defaults                   = portfolio_one_customizer_defaults();
        $portfolio_one_inner_single_sidebar 	= get_theme_mod( 'portfolio_one_inner_single_sidebar', $defaults['portfolio_one_inner_single_sidebar']);
        $portfolio_one_inner_blog_sidebar    = get_theme_mod( 'portfolio_one_inner_blog_sidebar', $defaults['portfolio_one_inner_blog_sidebar']);


        if(!is_search() && is_singular()){
	
            
        $classes[] 	=  $portfolio_one_inner_single_sidebar;   
            
        }
        if ( is_archive() || is_home()  || is_search() ) {
            $classes[] 	=  $portfolio_one_inner_blog_sidebar;
        }

        return $classes;

    }
    endif;


/**
* Retrieve post meta and default value of metabox
* @since 1.0.0
*/
function portfolio_one_get_post_meta( $key, $defaults = '' ){
    global $post;
  
    if(! $post )
      return;
      
      $default = $defaults;
      $meta_val =  get_post_meta( $post->ID, $key , true ); 
  
      if( empty($meta_val) && ($defaults != '') ){
          $meta_val = $default;
      }
  
      return $meta_val;
  
  }

/**
* Dark mode
*/
add_action('wp_footer','portfolio_one_dark_mode_toggle' );
function portfolio_one_dark_mode_toggle(){
    $defaults                  = portfolio_one_customizer_defaults();
    $cww_dark_mode_enable      = get_theme_mod('cww_dark_mode_enable', $defaults['cww_dark_mode_enable']);
    $cww_dark_mode_position    = get_theme_mod('cww_dark_mode_position', $defaults['cww_dark_mode_position']);

    if( $cww_dark_mode_enable == false ){
        return;
    }
    ?>
    
    <button class="portfolio-one-dark-mode-toggle <?php echo esc_attr( 'position-'.$cww_dark_mode_position ); ?>" aria-label="<?php esc_attr_e('Toggle Dark Mode','portfolio-one')?>">
        <span class="light">
            <?php echo portfolio_one_get_icon_svg('sun',14) ?> 
        </span>
        <span class="dark">
            <?php echo portfolio_one_get_icon_svg('moon',14) ?>
        </span>
    </button>
<?php 
}


add_action('wp_head','portfolio_one_head_scripts' );
function portfolio_one_head_scripts()
{
    $defaults                  = portfolio_one_customizer_defaults();
    $cww_dark_mode_enable      = get_theme_mod('cww_dark_mode_enable', $defaults['cww_dark_mode_enable']);
    
    if( $cww_dark_mode_enable == false ){
        return;
    }

    ?>
    <script type="text/javascript">

        let portfolio_one_storageKey = 'theme-preference';
        
        // Check if Dark Reader is enabled.
        const isEnabled = DarkReader.isEnabled();

        let portfolio_one_getColorPreference = function () {
      if (localStorage.getItem(portfolio_one_storageKey))
          return localStorage.getItem(portfolio_one_storageKey);
      else
          return window.matchMedia('(prefers-color-scheme: dark)').matches
              ? 'dark'
              : 'light';
    };

    let portfolio_one_theme = {
      value: portfolio_one_getColorPreference()
    };

    let portfolio_one_setPreference = function () {
      localStorage.setItem(portfolio_one_storageKey, portfolio_one_theme.value);
      portfolio_one_reflectPreference();
    };

    let portfolio_one_reflectPreference = function () {
        document.firstElementChild.setAttribute("data-theme", portfolio_one_theme.value);
        document.querySelector(".portfolio-one-dark-mode-toggle")?.setAttribute("aria-label", portfolio_one_theme.value);
        if( portfolio_one_theme.value == 'dark'){
            DarkReader.setFetchMethod(window.fetch)
            DarkReader.enable({
                brightness: 100,
                contrast: 85,
                sepia: 10,
            });
        }else{
            DarkReader.disable();
        }
    };
    // Set early so no page flashes / CSS is made aware
    portfolio_one_reflectPreference();

    window.addEventListener('load', function () {
      portfolio_one_reflectPreference();
      let toggleBtn = document.querySelector(".portfolio-one-dark-mode-toggle");
      if (toggleBtn) {
          toggleBtn.addEventListener("click", function () {
              portfolio_one_theme.value = portfolio_one_theme.value === 'light' ? 'dark' : 'light';
              if( portfolio_one_theme.value == 'dark'){
                DarkReader.setFetchMethod(window.fetch)
                  DarkReader.enable({
                    brightness: 100,
                    contrast: 85,
                    sepia: 10,
                  });
              }else{
                DarkReader.disable();
              }
             
              portfolio_one_setPreference();
          });
      }
  });

  // Sync with system changes
  window
      .matchMedia('(prefers-color-scheme: dark)')
      .addEventListener('change', ({matches: isDark}) => {
          portfolio_one_theme.value = isDark ? 'dark' : 'light';
          portfolio_one_setPreference();
      });

    </script>
    <?php
}

/**
 * Portfolio meta details
 */
add_action('portfolio_one_portfolio_meta_info','portfolio_one_portfolio_meta_info' );
function portfolio_one_portfolio_meta_info($post){
    $portfolio_client_name          = get_post_meta( $post->ID, 'portfolio_client_name', true );
    $portfolip_skills          		= get_post_meta( $post->ID, 'portfolip_skills', true );
    $portfolio_company_website      = get_post_meta( $post->ID, 'portfolio_company_website', true );
    $portfolio_date          		= get_post_meta( $post->ID, 'portfolio_date', true );

    if( $portfolio_client_name || $portfolip_skills || $portfolio_company_website || $portfolio_date ): ?>
        <div class="portfolio-meta-info">
            <h3><?php esc_html_e('Project Details','portfolio-one'); ?></h3>
            <ul class="meta-info">
                <?php if($portfolio_client_name): ?>
                    <li>
                        <span class="title"><?php esc_html_e('Client:','portfolio-one'); ?></span>
                        <span><?php echo esc_html($portfolio_client_name);?></span>
                    </li>
                <?php endif; ?>

                <?php if($portfolip_skills): ?>
                    <li>
                        <span class="title"><?php esc_html_e('Tasks:','portfolio-one'); ?></span>
                        <span><?php echo esc_html($portfolip_skills);?></span>
                    </li>
                <?php endif; ?>

                <?php if($portfolio_date): ?>
                    <li>
                        <span class="title"><?php esc_html_e('Date:','portfolio-one'); ?></span>
                        <span><?php echo esc_html($portfolio_date);?></span>
                    </li>
                <?php endif; ?>

            </ul>
            <?php if($portfolio_company_website): ?>
            <div class="btn-view">
                <a href="<?php echo esc_url($portfolio_company_website)?>">
                    <span><?php esc_html_e('Visit Website','portfolio-one'); ?></span>
                </a>
            </div>
            <?php endif;?>
        </div> 
    <?php endif;
}