<?php
/**
 * Thehoot theme
 * custom functions.php file
 */

 function thehoot_scripts() {
  // Add compiled SASS styles to the theme
  wp_enqueue_style('styles', get_template_directory_uri() . '/src/dist/css/styles.min.css?v=1.0.0', array(), null, 'all');

  // Add JS to theme (ensure correct order)
  wp_enqueue_script('popper', get_template_directory_uri() . '/src/dist/js/popper.min.js', array(), null, true);
  wp_enqueue_script('bootstrap', get_template_directory_uri() . '/src/dist/js/bootstrap.min.js', array('jquery', 'popper'), '1.0.0', true);
  wp_enqueue_script('main', get_template_directory_uri() . '/src/dist/js/main.js', array('jquery', 'bootstrap'), '1.0.0', true);
}

add_action('wp_enqueue_scripts', 'thehoot_scripts');

// Register Custom Navigation Walker
require_once get_template_directory() . '/inc/class-wp-bootstrap-navwalker.php';

//add menu support
  register_nav_menus(array(
    'primary' => 'main-menu',
    'footer' => 'footer-menu',
  ));

//Start theme customizer
  function thehoot_theme_customizer($wp_customize)
  {

//Add custom logo to design
      $wp_customize->add_section('thehoot_logo_section', array(
      'title'       => __('Logo', 'thehoot'),
      'priority'    => 30,
      'description' => 'Upload a logo to replace the default site name and description in the header (200x60px)',
  ));

      $wp_customize->add_setting('thehoot_logo', array(
      'priority'       => 0,
      'sanitize_callback' => 'thehoot_sanitize_image',
  ));

      $wp_customize->add_control(new WP_Customize_Image_Control($wp_customize, 'thehoot_logo', array(
      'label'    => __('Logo', 'thehoot'),
      'section'  => 'thehoot_logo_section',
      'settings' => 'thehoot_logo',
  )));

  //Add custom logo to design
        $wp_customize->add_section('thehoot_footer_logo_section', array(
        'title'       => __('Footer Logo', 'thehoot'),
        'priority'    => 30,
        'description' => 'Upload a logo to replace the default site name and description in the header (200x60px)',
    ));

        $wp_customize->add_setting('thehoot_footer_logo', array(
        'priority'       => 0,
        'sanitize_callback' => 'thehoot_sanitize_image',
    ));

        $wp_customize->add_control(new WP_Customize_Image_Control($wp_customize, 'thehoot_footer_logo', array(
        'label'    => __('Footer Logo', 'thehoot'),
        'section'  => 'thehoot_footer_logo_section',
        'settings' => 'thehoot_footer_logo',
    )));

  add_theme_support('automatic-feed-links');
      require_once(get_stylesheet_directory().'/inc/social-media-controls.php');
  }
  add_action('customize_register', 'thehoot_theme_customizer');
  add_theme_support('html5', array('search-form'));
  add_theme_support('automatic-feed-links')
;
// remove junk from head
remove_action('wp_head', 'rsd_link');
remove_action('wp_head', 'wp_generator');
remove_action('wp_head', 'feed_links', 2);
remove_action('wp_head', 'index_rel_link');
remove_action('wp_head', 'wlwmanifest_link');
remove_action('wp_head', 'feed_links_extra', 3);
remove_action('wp_head', 'start_post_rel_link', 10, 0);
remove_action('wp_head', 'parent_post_rel_link', 10, 0);
remove_action('wp_head', 'adjacent_posts_rel_link', 10, 0);

/*  DISABLE GUTENBERG STYLE IN HEADER| WordPress 5.9 */
function wps_deregister_styles() {
    wp_dequeue_style( 'global-styles' );
}
add_action( 'wp_enqueue_scripts', 'wps_deregister_styles', 100 );

/**
 * Disable the emoji's
 */
function disable_emojis() {
	remove_action( 'wp_head', 'print_emoji_detection_script', 7 );
	remove_action( 'admin_print_scripts', 'print_emoji_detection_script' );
	remove_action( 'wp_print_styles', 'print_emoji_styles' );
	remove_action( 'admin_print_styles', 'print_emoji_styles' );
	remove_filter( 'the_content_feed', 'wp_staticize_emoji' );
	remove_filter( 'comment_text_rss', 'wp_staticize_emoji' );
	remove_filter( 'wp_mail', 'wp_staticize_emoji_for_email' );

	// Remove from TinyMCE
	add_filter( 'tiny_mce_plugins', 'disable_emojis_tinymce' );
}
add_action( 'init', 'disable_emojis' );

/**
 * Filter out the tinymce emoji plugin.
 */
function disable_emojis_tinymce( $plugins ) {
	if ( is_array( $plugins ) ) {
		return array_diff( $plugins, array( 'wpemoji' ) );
	} else {
		return array();
	}
}

if( function_exists('acf_add_options_page') ) {

	acf_add_options_page();

}

add_theme_support( 'post-thumbnails' );
add_theme_support('title-tag');

//Add custom sidebars
function thehoot_widgets_init()
{
    register_sidebar(array(
      'name' => __('Main Sidebar', 'thehoot'),
      'id' => 'sidebar-main',
      'description' => __('The main sidebar appears on the right of each page.', 'thehoot'),
      'before_widget' => '<aside id="%1$s" class="widget %2$s ">',
      'after_widget' => '</aside>',
      'before_title' => '<h3 class="widget-title">',
      'after_title' => '</h3>',
    ));

    register_sidebar(array(
      'name' =>__('Footer First Column', 'thehoot'),
      'id' => 'footer-first',
      'before_widget' => '<div class="widget %2$s">',
      'after_widget' => '</div>',
      'description' => __('Appears in the first column of the footer', 'thehoot'),
      'before_title' => '<h3 class="widget-title">',
      'after_title' => '</h3>',
  ));

    register_sidebar(array(
      'name' =>__('Footer Second Column', 'thehoot'),
      'id' => 'footer-second',
      'before_widget' => '<div class="widget %2$s text-center">',
      'after_widget' => '</div>',
      'description' => __('Appears in the second column of the footer', 'thehoot'),
      'before_title' => '<h3 class="widget-title">',
      'after_title' => '</h3>',
));
  }
add_action('widgets_init', 'thehoot_widgets_init');

remove_filter( 'get_the_excerpt', 'wp_trim_excerpt' );

//Text entry sanitization
  function thehoot_sanitize_text($input)
  {
      return wp_kses_post(force_balance_tags($input));
  }
//Checkbox sanitization
  function thehoot_sanitize_checkbox($input)
  {
      if ($input == 1) {
          return 1;
      } else {
          return '';
      }
  }
//Image upload sanitizer
    function thehoot_sanitize_image($input)
    {
        /* default output */
        $output = '';
        /* check file type */
        $filetype = wp_check_filetype($input);
        $mime_type = $filetype['type'];
        /* only mime type "image" allowed */
        if (strpos($mime_type, 'image') !== false) {
            $output = $input;
        }
        return $output;
    ;
  }

  function limit_words($text, $limit) {
    if (str_word_count($text, 0) > $limit) {
      $words = str_word_count($text, 2);
      $pos = array_keys($words);
      $text = substr($text, 0, $pos[$limit]) . '...';
    }

    return $text;
  }



    function defer_parsing_of_js($url)
    {
        if (is_user_logged_in()) {
            return $url;
        } //don't break WP Admin
        if (false === strpos($url, '.js')) {
            return $url;
        }
        if (strpos($url, 'jquery.js')) {
            return $url;
        }
        return str_replace(' src', ' defer src', $url);
    }
        add_filter('script_loader_tag', 'defer_parsing_of_js', 10);

add_filter( 'wpseo_metabox_prio', function() { return 'low'; } );



// bootstrap 5 wp_nav_menu walker
        class bootstrap_5_wp_nav_menu_walker extends Walker_Nav_menu
        {
          private $current_item;
          private $dropdown_menu_alignment_values = [
            'dropdown-menu-start',
            'dropdown-menu-end',
            'dropdown-menu-sm-start',
            'dropdown-menu-sm-end',
            'dropdown-menu-md-start',
            'dropdown-menu-md-end',
            'dropdown-menu-lg-start',
            'dropdown-menu-lg-end',
            'dropdown-menu-xl-start',
            'dropdown-menu-xl-end',
            'dropdown-menu-xxl-start',
            'dropdown-menu-xxl-end'
          ];

          function start_lvl(&$output, $depth = 0, $args = null)
          {
            $dropdown_menu_class[] = '';
            foreach($this->current_item->classes as $class) {
              if(in_array($class, $this->dropdown_menu_alignment_values)) {
                $dropdown_menu_class[] = $class;
              }
            }
            $indent = str_repeat("\t", $depth);
            $submenu = ($depth > 0) ? ' sub-menu' : '';
            $output .= "\n$indent<ul class=\"dropdown-menu$submenu " . esc_attr(implode(" ",$dropdown_menu_class)) . " depth_$depth\">\n";
          }

          function start_el(&$output, $item, $depth = 0, $args = null, $id = 0)
          {
            $this->current_item = $item;

            $indent = ($depth) ? str_repeat("\t", $depth) : '';

            $li_attributes = '';
            $class_names = $value = '';

            $classes = empty($item->classes) ? array() : (array) $item->classes;

            $classes[] = ($args->walker->has_children) ? 'dropdown' : '';
            $classes[] = 'nav-item';
            $classes[] = 'nav-item-' . $item->ID;
            if ($depth && $args->walker->has_children) {
                $classes[] = 'dropdown-menu-child-item dropdown-menu-end';
            }

            $class_names =  join(' ', apply_filters('nav_menu_css_class', array_filter($classes), $item, $args));
            $class_names = ' class="' . esc_attr($class_names) . '"';

            $id = apply_filters('nav_menu_item_id', 'menu-item-' . $item->ID, $item, $args);
            $id = strlen($id) ? ' id="' . esc_attr($id) . '"' : '';

            $output .= $indent . '<li ' . $id . $value . $class_names . $li_attributes . '>';

            $attributes = !empty($item->attr_title) ? ' title="' . esc_attr($item->attr_title) . '"' : '';
            $attributes .= !empty($item->target) ? ' target="' . esc_attr($item->target) . '"' : '';
            $attributes .= !empty($item->xfn) ? ' rel="' . esc_attr($item->xfn) . '"' : '';
            $attributes .= !empty($item->url) ? ' href="' . esc_attr($item->url) . '"' : '';

            $active_class = ($item->current || $item->current_item_ancestor || in_array("current_page_parent", $item->classes, true) || in_array("current-post-ancestor", $item->classes, true)) ? 'active' : '';
            $nav_link_class = ( $depth > 0 ) ? 'dropdown-item ' : 'nav-link ';
            $attributes .= ( $args->walker->has_children ) ? ' class="'. $nav_link_class . $active_class . ' dropdown-toggle" aria-haspopup="true" aria-expanded="false"' : ' class="'. $nav_link_class . $active_class . '"';

            $item_output = $args->before;
            $item_output .= '<a' . $attributes . '>';
            $item_output .= $args->link_before . apply_filters('the_title', $item->title, $item->ID) . $args->link_after;
            $item_output .= '</a>';
            $item_output .= $args->after;

            $output .= apply_filters('walker_nav_menu_start_el', $item_output, $item, $depth, $args);
          }
        }

//Add img-fluid to all images

function add_bootstrap_img_class($attr) {
  if (!isset($attr['class'])) {
      $attr['class'] = 'img-fluid';
  } else {
      $attr['class'] .= ' img-fluid';
  }
  return $attr;
}
add_filter('wp_get_attachment_image_attributes', 'add_bootstrap_img_class', 10, 1);

//Remove Category, tag, author $words

add_filter('get_the_archive_title', function ($title) {
    if (is_category()) {
        $title = single_cat_title('', false);
    } elseif (is_tag()) {
        $title = single_tag_title('', false);
    } elseif (is_author()) {
        $title = '<span class="vcard">' . get_the_author() . '</span>';
    } elseif (is_tax()) { //for custom post types
        $title = sprintf(__('%1$s'), single_term_title('', false));
    } elseif (is_post_type_archive()) {
        $title = post_type_archive_title('', false);
    }
    return $title;
});


function cptui_register_my_cpts_job_listing() {

	/**
	 * Post Type: Job Listings.
	 */

	$labels = [
		"name" => __( "Job Listings", "custom-post-type-ui" ),
		"singular_name" => __( "Job Listing", "custom-post-type-ui" ),
		"menu_name" => __( "Job Listings", "custom-post-type-ui" ),
		"all_items" => __( "All Job Listings", "custom-post-type-ui" ),
		"add_new" => __( "Add new", "custom-post-type-ui" ),
		"add_new_item" => __( "Add new Job Listing", "custom-post-type-ui" ),
		"edit_item" => __( "Edit Job Listing", "custom-post-type-ui" ),
		"new_item" => __( "New Job Listing", "custom-post-type-ui" ),
		"view_item" => __( "View Job Listing", "custom-post-type-ui" ),
		"view_items" => __( "View Job Listings", "custom-post-type-ui" ),
		"search_items" => __( "Search Job Listings", "custom-post-type-ui" ),
		"not_found" => __( "No Job Listings found", "custom-post-type-ui" ),
		"not_found_in_trash" => __( "No Job Listings found in trash", "custom-post-type-ui" ),
		"parent" => __( "Parent Job Listing:", "custom-post-type-ui" ),
		"featured_image" => __( "Featured image for this Job Listing", "custom-post-type-ui" ),
		"set_featured_image" => __( "Set featured image for this Job Listing", "custom-post-type-ui" ),
		"remove_featured_image" => __( "Remove featured image for this Job Listing", "custom-post-type-ui" ),
		"use_featured_image" => __( "Use as featured image for this Job Listing", "custom-post-type-ui" ),
		"archives" => __( "Job Listing archives", "custom-post-type-ui" ),
		"insert_into_item" => __( "Insert into Job Listing", "custom-post-type-ui" ),
		"uploaded_to_this_item" => __( "Upload to this Job Listing", "custom-post-type-ui" ),
		"filter_items_list" => __( "Filter Job Listings list", "custom-post-type-ui" ),
		"items_list_navigation" => __( "Job Listings list navigation", "custom-post-type-ui" ),
		"items_list" => __( "Job Listings list", "custom-post-type-ui" ),
		"attributes" => __( "Job Listings attributes", "custom-post-type-ui" ),
		"name_admin_bar" => __( "Job Listing", "custom-post-type-ui" ),
		"item_published" => __( "Job Listing published", "custom-post-type-ui" ),
		"item_published_privately" => __( "Job Listing published privately.", "custom-post-type-ui" ),
		"item_reverted_to_draft" => __( "Job Listing reverted to draft.", "custom-post-type-ui" ),
		"item_scheduled" => __( "Job Listing scheduled", "custom-post-type-ui" ),
		"item_updated" => __( "Job Listing updated.", "custom-post-type-ui" ),
		"parent_item_colon" => __( "Parent Job Listing:", "custom-post-type-ui" ),
	];

	$args = [
		"label" => __( "Job Listings", "custom-post-type-ui" ),
		"labels" => $labels,
		"description" => "",
		"public" => true,
		"publicly_queryable" => true,
		"show_ui" => true,
		"show_in_rest" => true,
		"rest_base" => "",
		"rest_controller_class" => "WP_REST_Posts_Controller",
		"has_archive" => false,
		"show_in_menu" => true,
		'menu_icon' => 'dashicons-portfolio',
		"show_in_nav_menus" => true,
		"delete_with_user" => false,
		"exclude_from_search" => true,
		"capability_type" => "post",
		"map_meta_cap" => true,
		"hierarchical" => false,
		"rewrite" => [ "slug" => "job-listing", "with_front" => true ],
		"query_var" => true,
		"supports" => [ "title" ],
		"show_in_graphql" => false,
	];

	register_post_type( "job-listing", $args );
}

function cptui_register_my_cpts_properties() {

	/**
	 * Post Type: Property Listings.
	 */

	$labels = [
		"name" => __( "Property Listings", "custom-post-type-ui" ),
		"singular_name" => __( "Property  Listing", "custom-post-type-ui" ),
		"menu_name" => __( "Property Listings", "custom-post-type-ui" ),
		"all_items" => __( "All Property Listings", "custom-post-type-ui" ),
		"add_new" => __( "Add new", "custom-post-type-ui" ),
		"add_new_item" => __( "Add new Property Listing", "custom-post-type-ui" ),
		"edit_item" => __( "Edit Property Listing", "custom-post-type-ui" ),
		"new_item" => __( "New Property Listing", "custom-post-type-ui" ),
		"view_item" => __( "View Property Listing", "custom-post-type-ui" ),
		"view_items" => __( "View Property Listings", "custom-post-type-ui" ),
		"search_items" => __( "Search Property Listings", "custom-post-type-ui" ),
		"not_found" => __( "No Property Listings found", "custom-post-type-ui" ),
		"not_found_in_trash" => __( "No Property Listings found in trash", "custom-post-type-ui" ),
		"parent" => __( "Parent Property Listing:", "custom-post-type-ui" ),
		"featured_image" => __( "Featured image for this Property Listing", "custom-post-type-ui" ),
		"set_featured_image" => __( "Set featured image for this Property Listing", "custom-post-type-ui" ),
		"remove_featured_image" => __( "Remove featured image for this Property Listing", "custom-post-type-ui" ),
		"use_featured_image" => __( "Use as featured image for this Property Listing", "custom-post-type-ui" ),
		"archives" => __( "Property Listing archives", "custom-post-type-ui" ),
		"insert_into_item" => __( "Insert into Property Listing", "custom-post-type-ui" ),
		"uploaded_to_this_item" => __( "Upload to this Property Listing", "custom-post-type-ui" ),
		"filter_items_list" => __( "Filter Property Listings list", "custom-post-type-ui" ),
		"items_list_navigation" => __( "Property Listings list navigation", "custom-post-type-ui" ),
		"items_list" => __( "Property Listings list", "custom-post-type-ui" ),
		"attributes" => __( "Property Listings attributes", "custom-post-type-ui" ),
		"name_admin_bar" => __( "Property Listing", "custom-post-type-ui" ),
		"item_published" => __( "Property Listing published", "custom-post-type-ui" ),
		"item_published_privately" => __( "Property Listing published privately.", "custom-post-type-ui" ),
		"item_reverted_to_draft" => __( "Property Listing reverted to draft.", "custom-post-type-ui" ),
		"item_scheduled" => __( "Property Listing scheduled", "custom-post-type-ui" ),
		"item_updated" => __( "Property Listing updated.", "custom-post-type-ui" ),
		"parent_item_colon" => __( "Parent Property Listing:", "custom-post-type-ui" ),
	];

	$args = [
		"label" => __( "Property Listings", "custom-post-type-ui" ),
		"labels" => $labels,
		"description" => "",
		"public" => true,
		"publicly_queryable" => true,
		"show_ui" => true,
		"show_in_rest" => true,
		"rest_base" => "",
		"rest_controller_class" => "WP_REST_Posts_Controller",
		"has_archive" => false,
		"show_in_menu" => true,
		'menu_icon' => 'dashicons-admin-home',
		"show_in_nav_menus" => true,
		"delete_with_user" => false,
		"exclude_from_search" => true,
		"capability_type" => "post",
		"map_meta_cap" => true,
		"hierarchical" => false,
		"rewrite" => [ "slug" => "property-listing", "with_front" => true ],
		"query_var" => true,
		"supports" => [ "title" ],
		"show_in_graphql" => false,
	];

	register_post_type( "property-listing", $args );
}

add_action( 'init', 'cptui_register_my_cpts_properties' );

add_action( 'init', 'cptui_register_my_cpts_job_listing' );


add_filter('manage_edit-category_columns', 'add_category_id_column');
function add_category_id_column($columns) {
    $columns['category_id'] = 'ID';
    return $columns;
}

add_action('manage_category_custom_column', 'show_category_id_column', 10, 3);
function show_category_id_column($empty, $column_name, $term_id) {
    if ($column_name == 'category_id') {
        return $term_id;
    }
    return $empty;
}

