<?php

/**
 * Setup WordPress theme
 * @category Functions
 * @author Krik
 */

// General options for theme
add_action('after_setup_theme', 'krik_theme_setup');

// Disable Categories
// add_action('init', 'krik_disable_categories_taxonomy');

// Disable Tags
// add_action('init', 'krik_disable_tags_taxonomy');

// Excerpt support for Pages
// add_action('init', 'krik_page_excerpt');

// Set custom excerpt more
add_filter('excerpt_more', 'krik_excerpt_more');

// Set custom excerpt length
add_filter('excerpt_length', 'krik_excerpt_length');

// Allow SVG
add_filter('wp_check_filetype_and_ext', 'krik_allow_svg', 10, 4);
add_filter('upload_mimes', 'krik_mime_types');

// Disable access to author page
add_action('template_redirect', 'krik_redirect_author_page');

// Disable REST endpoints to hide users
add_filter('rest_endpoints', 'krik_disable_rest_endpoints');

function krik_theme_setup()
{
	// Remove support for post formats
	remove_theme_support('post-formats');

	// Add support for post formats
	// add_theme_support('post-formats', ['aside', 'audio', 'gallery', 'image', 'link', 'quote', 'video']);

	// Let WordPress manage the document title
	add_theme_support('title-tag');

	// Enable support for Post Thumbnails on posts and pages
	add_theme_support('post-thumbnails');

	// Enable support for Wide Images
	add_theme_support('align-wide');

	// Valid HTML5 output
	add_theme_support('html5',
		array(
			// 'search-form',
			// 'comment-form',
			// 'comment-list',
			// 'caption',
			'gallery'
		)
	);
}

function krik_disable_categories_taxonomy()
{
	register_taxonomy('category', array());
}

function krik_disable_tags_taxonomy()
{
	register_taxonomy('post_tag', array());
}

function krik_page_excerpt()
{
	add_post_type_support('page', 'excerpt');
}

function krik_excerpt_more()
{
	return '...';
}

function krik_excerpt_length()
{
	return 100;
}

function krik_allow_svg($data, $file, $filename, $mimes)
{
	$filetype = wp_check_filetype($filename, $mimes);
	return [
		'ext' => $filetype['ext'],
		'type' => $filetype['type'],
		'proper_filename' => $data['proper_filename']
	];
}

function krik_mime_types($mimes)
{
	$mimes['svg'] = 'image/svg+xml';
	return $mimes;
}

function krik_redirect_author_page()
{
	$is_author_set = get_query_var('author', '');
	if ($is_author_set != '' && !is_admin()) {
		wp_redirect(home_url(), 301);
		exit;
	}
}

function krik_disable_rest_endpoints($endpoints)
{
	if (isset($endpoints['/wp/v2/users'])) {
		unset($endpoints['/wp/v2/users']);
	}
	if (isset($endpoints['/wp/v2/users/(?P<id>[\d]+)'])) {
		unset($endpoints['/wp/v2/users/(?P<id>[\d]+)']);
	}
	return $endpoints;
}
