<?php

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

require_once get_stylesheet_directory() . '/inc/theme-data.php';
require_once get_stylesheet_directory() . '/inc/routes.php';
require_once get_stylesheet_directory() . '/inc/forms.php';

add_action( 'after_setup_theme', 'sev_tort_theme_setup' );
function sev_tort_theme_setup() {
	add_theme_support( 'title-tag' );
	add_theme_support( 'post-thumbnails' );
	remove_action( 'wp_head', 'rel_canonical' );
}

add_action( 'wp_enqueue_scripts', 'sev_tort_enqueue_assets' );
function sev_tort_enqueue_assets() {
	$theme_version = wp_get_theme()->get( 'Version' );
	$uri           = get_stylesheet_directory_uri();
	$page          = sev_tort_current_page_config();

	wp_enqueue_style( 'sev-tort-normalize', $uri . '/assets/css/normalize.min.css', array(), $theme_version );
	wp_enqueue_style( 'sev-tort-reset', $uri . '/assets/css/reset.min.css', array( 'sev-tort-normalize' ), $theme_version );
	wp_enqueue_style( 'sev-tort-core', $uri . '/assets/css/style-core.css', array( 'sev-tort-reset' ), $theme_version );
	wp_enqueue_style( 'sev-tort-layout', $uri . '/assets/css/layout.css', array( 'sev-tort-core' ), $theme_version );

	$responsive_dependencies = array( 'sev-tort-layout' );

	if ( $page ) {
		$style = 'portfolio' === $page['slug'] ? 'portfolio-page.css' : ( isset( $page['style'] ) ? $page['style'] : 'service-page.css' );
		wp_enqueue_style( 'sev-tort-page', $uri . '/assets/css/' . $style, array( 'sev-tort-layout' ), $theme_version );
		$responsive_dependencies = array( 'sev-tort-page' );
	} elseif ( is_front_page() ) {
		wp_enqueue_style( 'sev-tort-page', $uri . '/assets/css/home-page.css', array( 'sev-tort-layout' ), $theme_version );
		$responsive_dependencies = array( 'sev-tort-page' );
	}

	wp_enqueue_style( 'sev-tort-responsive', $uri . '/assets/css/responsive.css', $responsive_dependencies, $theme_version );
	wp_enqueue_script( 'sev-tort-site', $uri . '/assets/js/site.js', array(), $theme_version, true );
}

add_action( 'wp_enqueue_scripts', 'sev_tort_dequeue_parent_assets', 30 );
function sev_tort_dequeue_parent_assets() {
	$handles = array(
		'twentytwentyfive-style',
		'twentytwentyfive-custom-header',
		'twentytwentyfive-custom-footer',
		'twentytwentyfive-custom-home',
	);

	foreach ( $handles as $handle ) {
		wp_dequeue_style( $handle );
		wp_deregister_style( $handle );
		wp_dequeue_script( $handle );
		wp_deregister_script( $handle );
	}
}

add_filter( 'body_class', 'sev_tort_body_classes' );
function sev_tort_body_classes( $classes ) {
	$page = sev_tort_current_page_config();

	$classes[] = 'site-page';

	if ( $page ) {
		$classes[] = 'page-' . sanitize_html_class( $page['slug'] );
		$classes[] = 'sev-page--' . sanitize_html_class( $page['slug'] );
	} elseif ( is_front_page() ) {
		$classes[] = 'page-home';
		$classes[] = 'sev-page--home';
	}

	return $classes;
}

add_action( 'wp_head', 'sev_tort_meta_tags', 1 );
function sev_tort_meta_tags() {
	$page = sev_tort_current_page_config();

	if ( $page ) {
		$robots = ! empty( $page['indexable'] ) ? 'index, follow' : 'noindex, nofollow';
		printf( '<meta name="robots" content="%s">' . "\n", esc_attr( $robots ) );

		if ( ! empty( $page['description'] ) ) {
			$description = ! empty( $page['seo_description'] ) ? $page['seo_description'] : $page['description'];
			printf( '<meta name="description" content="%s">' . "\n", esc_attr( $description ) );
		}

		printf( '<link rel="canonical" href="%s">' . "\n", esc_url( home_url( '/' . $page['slug'] . '/' ) ) );
		return;
	}

	if ( is_front_page() ) {
		echo '<meta name="robots" content="index, follow">' . "\n";
		printf( '<meta name="description" content="%s">' . "\n", esc_attr( sev_tort_home_seo_description() ) );
		printf( '<link rel="canonical" href="%s">' . "\n", esc_url( home_url( '/' ) ) );
	}
}

add_filter( 'wp_robots', 'sev_tort_wp_robots', 100 );
function sev_tort_wp_robots( $robots ) {
	$page = sev_tort_current_page_config();

	if ( $page && ! empty( $page['indexable'] ) ) {
		unset( $robots['noindex'], $robots['nofollow'] );
		$robots['index']             = true;
		$robots['follow']            = true;
		$robots['max-image-preview'] = 'large';
		return $robots;
	}

	if ( ! $page && is_front_page() ) {
		unset( $robots['noindex'], $robots['nofollow'] );
		$robots['index']             = true;
		$robots['follow']            = true;
		$robots['max-image-preview'] = 'large';
	}

	return $robots;
}

add_action( 'wp_head', 'sev_tort_schema_markup', 20 );
function sev_tort_schema_markup() {
	$page   = sev_tort_current_page_config();
	$schema = array();

	$schema[] = array(
		'@context'     => 'https://schema.org',
		'@type'        => 'Bakery',
		'@id'          => home_url( '/#bakery' ),
		'name'         => 'Создаем повод для праздника',
		'description'  => 'Кондитерская студия в Севастополе: торты на заказ, бенто-торты, детские, свадебные и праздничные торты с доставкой.',
		'url'          => home_url( '/' ),
		'image'        => get_stylesheet_directory_uri() . '/assets/images/hero/bento-hero-main.png',
		'telephone'    => sev_tort_site_phone(),
		'priceRange'   => 'от 2 300 ₽',
		'address'      => array(
			'@type'           => 'PostalAddress',
			'addressLocality' => 'Севастополь',
			'addressCountry'  => 'RU',
		),
		'areaServed'   => array(
			'@type' => 'City',
			'name'  => 'Севастополь',
		),
		'openingHours' => 'Mo-Su 09:00-20:00',
	);

	$schema[] = array(
		'@context'        => 'https://schema.org',
		'@type'           => 'WebSite',
		'@id'             => home_url( '/#website' ),
		'name'            => 'Торты на заказ в Севастополе',
		'url'             => home_url( '/' ),
		'publisher'       => array( '@id' => home_url( '/#bakery' ) ),
		'inLanguage'      => 'ru-RU',
	);

	if ( ! $page && is_front_page() ) {
		$schema[] = sev_tort_faq_schema(
			array(
				array(
					'q' => 'За сколько дней лучше заказывать торт?',
					'a' => 'Оптимально оставить заявку за 2-4 дня до даты праздника. Срочные заказы возможны при свободном окне в графике.',
				),
				array(
					'q' => 'Можно ли сделать торт по фотографии или референсу?',
					'a' => 'Да, можно прислать фото, описание идеи, цветовую гамму и пожелания по надписи. После уточнения деталей предложим подходящий вариант.',
				),
				array(
					'q' => 'Есть ли доставка по Севастополю?',
					'a' => 'Да, доставляем по Севастополю в согласованный интервал. Также можно забрать заказ самостоятельно после подтверждения готовности.',
				),
			)
		);
	} elseif ( $page && ! empty( $page['indexable'] ) ) {
		$schema[] = array(
			'@context'    => 'https://schema.org',
			'@type'       => 'Service',
			'name'        => $page['h1'],
			'description' => ! empty( $page['seo_description'] ) ? $page['seo_description'] : $page['description'],
			'provider'    => array( '@id' => home_url( '/#bakery' ) ),
			'areaServed'  => array(
				'@type' => 'City',
				'name'  => 'Севастополь',
			),
			'offers'      => array(
				'@type'         => 'Offer',
				'priceCurrency' => 'RUB',
				'price'         => '2300',
				'url'           => home_url( '/' . $page['slug'] . '/' ),
			),
		);

		$schema[] = array(
			'@context'        => 'https://schema.org',
			'@type'           => 'BreadcrumbList',
			'itemListElement' => array(
				array(
					'@type'    => 'ListItem',
					'position' => 1,
					'name'     => 'Главная',
					'item'     => home_url( '/' ),
				),
				array(
					'@type'    => 'ListItem',
					'position' => 2,
					'name'     => $page['label'],
					'item'     => home_url( '/' . $page['slug'] . '/' ),
				),
			),
		);

		if ( ! empty( $page['content']['faq'] ) ) {
			$schema[] = sev_tort_faq_schema( $page['content']['faq'] );
		}
	}

	foreach ( array_filter( $schema ) as $item ) {
		printf( '<script type="application/ld+json">%s</script>' . "\n", wp_json_encode( $item, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES ) );
	}
}

function sev_tort_faq_schema( $items ) {
	$entities = array();

	foreach ( $items as $item ) {
		if ( empty( $item['q'] ) || empty( $item['a'] ) ) {
			continue;
		}

		$entities[] = array(
			'@type'          => 'Question',
			'name'           => $item['q'],
			'acceptedAnswer' => array(
				'@type' => 'Answer',
				'text'  => $item['a'],
			),
		);
	}

	if ( ! $entities ) {
		return null;
	}

	return array(
		'@context'   => 'https://schema.org',
		'@type'      => 'FAQPage',
		'mainEntity' => $entities,
	);
}

add_action( 'wp_head', 'sev_tort_favicon_tags', 2 );
function sev_tort_favicon_tags() {
	$favicon_uri = get_stylesheet_directory_uri() . '/assets/images/favicon/';

	printf( '<link rel="icon" href="%s" sizes="any">' . "\n", esc_url( home_url( '/favicon.ico' ) ) );
	printf( '<link rel="icon" type="image/png" sizes="32x32" href="%s">' . "\n", esc_url( $favicon_uri . 'favicon-32x32.png' ) );
	printf( '<link rel="icon" type="image/png" sizes="16x16" href="%s">' . "\n", esc_url( $favicon_uri . 'favicon-16x16.png' ) );
	printf( '<link rel="apple-touch-icon" sizes="180x180" href="%s">' . "\n", esc_url( $favicon_uri . 'apple-touch-icon.png' ) );
	printf( '<link rel="icon" type="image/png" sizes="192x192" href="%s">' . "\n", esc_url( $favicon_uri . 'android-chrome-192x192.png' ) );
	echo '<meta name="theme-color" content="#fff8f3">' . "\n";
}

add_filter( 'pre_get_document_title', 'sev_tort_document_title' );
function sev_tort_document_title( $title ) {
	$page = sev_tort_current_page_config();

	if ( $page ) {
		if ( 'politika-konfidencialnosti' === $page['slug'] ) {
			return 'Политика в отношении обработки персональных данных';
		}

		return ! empty( $page['seo_title'] ) ? $page['seo_title'] : $page['title'];
	}

	if ( is_front_page() ) {
		return sev_tort_home_seo_title();
	}

	return $title;
}

function sev_tort_home_seo_title() {
	return 'Торты на заказ в Севастополе | Домашняя кондитерская';
}

function sev_tort_home_seo_description() {
	return 'Закажите торт ручной работы в Севастополе: свежие начинки, декор под событие, доставка по городу. Напишите нам и обсудите вкус, вес, дату и детали.';
}

add_action( 'after_switch_theme', 'sev_tort_flush_rewrite_rules' );
function sev_tort_flush_rewrite_rules() {
	sev_tort_register_rewrite_rules();
	flush_rewrite_rules();
}
