<?php
/**
 * Kumo Foundation Theme - functions.php
 * Production-ready version for Kumo Development
 * UPDATED: Includes header-menu.js for mobile navigation
 *
 * @package KumoFoundation
 * @version 1.1
 */

/**
 * Required includes
 */
require_once __DIR__ . '/includes/init-blocks.php';
require_once __DIR__ . '/includes/function-posttype.php';

$theme_customizer = __DIR__ . '/inc/customizer.php';
if ( is_readable( $theme_customizer ) ) {
	require_once $theme_customizer;
}

/**
 * Theme Setup
 */
if ( ! function_exists( 'kumo_theme_setup' ) ) {
	function kumo_theme_setup() {

		// Text domain
		load_theme_textdomain( 'kumo-foundation', __DIR__ . '/languages' );

		// Content width
		global $content_width;
		if ( ! isset( $content_width ) ) {
			$content_width = 1200;
		}

		// Theme supports
		add_theme_support( 'title-tag' );
		add_theme_support( 'automatic-feed-links' );
		add_theme_support( 'post-thumbnails' );
		add_theme_support( 'custom-logo' );

		add_theme_support(
			'html5',
			array(
				'search-form',
				'comment-form',
				'comment-list',
				'gallery',
				'caption',
				'script',
				'style',
				'navigation-widgets',
			)
		);

		// Block editor supports
		add_theme_support( 'wp-block-styles' );
		add_theme_support( 'align-wide' );
		add_theme_support( 'editor-styles' );
		add_editor_style( 'style-editor.css' );

		// Default attachment display settings
		update_option( 'image_default_align', 'none' );
		update_option( 'image_default_link_type', 'none' );
		update_option( 'image_default_size', 'large' );

		// Custom CSS styles of WordPress gallery
		add_filter( 'use_default_gallery_style', '__return_false' );

		// Nav menus
		register_nav_menus(
			array(
				'main-menu'     => 'Main Navigation Menu',
				'quick-links'   => 'Quick Links Menu',
				'quick-links-2' => 'Quick Links Menu 2',
			)
		);
	}
	add_action( 'after_setup_theme', 'kumo_theme_setup' );
}

/**
 * Enqueue editor stylesheet
 */
if ( ! function_exists( 'kumo_load_editor_styles' ) ) {
	function kumo_load_editor_styles() {
		if ( is_admin() ) {
			wp_enqueue_style( 'editor-style', get_theme_file_uri( 'style-editor.css' ), array(), wp_get_theme()->get( 'Version' ) );
		}
	}
	add_action( 'enqueue_block_assets', 'kumo_load_editor_styles' );
}

// Disable Block Directory
remove_action( 'enqueue_block_editor_assets', 'wp_enqueue_editor_block_directory_assets' );
remove_action( 'enqueue_block_editor_assets', 'gutenberg_enqueue_block_editor_assets_block_directory' );

/**
 * Back-compat: wp_body_open (pre WP 5.2)
 */
if ( ! function_exists( 'wp_body_open' ) ) {
	function wp_body_open() {
		do_action( 'wp_body_open' );
	}
}

/**
 * UNIVERSAL SITE IDENTITY (Customizer)
 * Per-site values so you can reuse the theme everywhere
 */
add_action(
	'customize_register',
	function( $wp_customize ) {

		$wp_customize->add_section(
			'universal_identity',
			array(
				'title'    => 'Universal Site Identity',
				'priority' => 25,
			)
		);

		// Standard identity fields
		$fields = array(
			'site_phone'   => 'Phone Number',
			'site_email'   => 'Email Address',
			'site_address' => 'Physical Address',
			'cta_label'    => 'Primary CTA Label',
			'cta_url'      => 'Primary CTA URL',
		);

		foreach ( $fields as $key => $label ) {
			$wp_customize->add_setting( $key, array( 'default' => '' ) );
			$wp_customize->add_control(
				$key,
				array(
					'label'   => $label,
					'section' => 'universal_identity',
					'type'    => 'text',
				)
			);
		}

		// Advanced toggle for dynamic phone logic
		$wp_customize->add_setting( 'enable_dynamic_phone', array( 'default' => false ) );
		$wp_customize->add_control(
			'enable_dynamic_phone',
			array(
				'label'   => 'Enable Dynamic Phone (advanced)',
				'section' => 'universal_identity',
				'type'    => 'checkbox',
			)
		);
	}
);

/**
 * Disable comments for Media attachments
 */
function kumo_filter_media_comment_status( $open, $post_id = null ) {
	$media_post = get_post( $post_id );
	if ( $media_post && 'attachment' === $media_post->post_type ) {
		return false;
	}
	return $open;
}
add_filter( 'comments_open', 'kumo_filter_media_comment_status', 10, 2 );

/**
 * Responsive oEmbed wrapper
 */
function kumo_oembed_filter( $html ) {
	return '<div class="ratio ratio-16x9">' . $html . '</div>';
}
add_filter( 'embed_oembed_html', 'kumo_oembed_filter', 10 );

/**
 * Enqueue CSS + JS
 * UPDATED: Now includes header-menu.js for mobile navigation
 */
function kumo_scripts_loader() {
	$theme_version = wp_get_theme()->get( 'Version' );

	// Styles
	wp_enqueue_style( 'style', get_theme_file_uri( 'style.css' ), array(), $theme_version, 'all' );
	wp_enqueue_style( 'main', get_theme_file_uri( 'build/css/style.min.css' ), array(), $theme_version, 'all' );
	wp_enqueue_style( 'aos', get_theme_file_uri( 'html/app/assets/css/aos.css' ), array(), $theme_version, 'all' );
	wp_enqueue_style( 'sources-styles', get_theme_file_uri( 'sources/styles.css' ), array(), $theme_version, 'all' );

	if ( is_rtl() ) {
		wp_enqueue_style( 'rtl', get_theme_file_uri( 'build/rtl.css' ), array(), $theme_version, 'all' );
	}

	// Scripts
	wp_enqueue_script( 'bootstrap', get_theme_file_uri( 'html/app/assets/components/bootstrap.min.js' ), array( 'jquery' ), $theme_version, true );
	wp_enqueue_script( 'custom', get_theme_file_uri( 'html/app/assets/components/custom.js' ), array( 'jquery' ), $theme_version, true );
	wp_enqueue_script( 'scriptjs', get_theme_file_uri( 'build/js/scripts.min.js' ), array( 'jquery' ), $theme_version, true );
	wp_enqueue_script( 'general-scriptjs', get_theme_file_uri( 'sources/script.js' ), array( 'jquery' ), $theme_version, true );
	
	// NEW: Header menu toggle for mobile navigation
	wp_enqueue_script( 'header-menu', get_theme_file_uri( 'sources/header-menu.js' ), array( 'jquery' ), $theme_version, true );

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

/**
 * ACF Options Page
 */
if ( function_exists( 'acf_add_options_page' ) ) {
	acf_add_options_page();
}

/**
 * Image helper with default alt
 */
function im_generate_image( $attachment_id, $size = 'full' ) {
	if ( $attachment_id ) {
		$alt = get_post_meta( $attachment_id, '_wp_attachment_image_alt', true );
		if ( empty( $alt ) ) {
			$alt = 'Image';
		}
		return wp_get_attachment_image( $attachment_id, $size, false, array( 'alt' => esc_attr( $alt ) ) );
	}
	return '';
}

/**
 * Block editor styles
 */
function kumo_block_editor_styles() {
	$theme_version = wp_get_theme()->get( 'Version' );

	wp_enqueue_style(
		'kumo-block-editor-styles',
		get_theme_file_uri( 'editor-style.css' ),
		array(),
		$theme_version
	);

	wp_enqueue_style(
		'kumo-block-editor-styles-build',
		get_theme_file_uri( 'build/css/style.min.css' ),
		array( 'kumo-block-editor-styles' ),
		$theme_version
	);
}
add_action( 'enqueue_block_editor_assets', 'kumo_block_editor_styles' );

/**
 * Thumbnail helper
 */
function get_thumb_image( $id ) {
	$image             = get_the_post_thumbnail_url( $id );
	$placeholder_image = get_template_directory_uri() . '/html/app/assets/img/placeholder.png';
	return ! empty( $image ) ? $image : $placeholder_image;
}

/**
 * Allow iframes in ACF rendered content
 */
function kumo_allow_iframes_in_acf( $value ) {
	global $allowedposttags;
	$allowedposttags['iframe'] = array(
		'src'             => true,
		'height'          => true,
		'width'           => true,
		'frameborder'     => true,
		'allow'           => true,
		'allowfullscreen' => true,
	);
	return $value;
}
add_filter( 'acf/format_value/type=textarea', 'kumo_allow_iframes_in_acf', 10, 1 );
add_filter( 'acf/format_value/type=wysiwyg', 'kumo_allow_iframes_in_acf', 10, 1 );

/**
 * Custom Nav Walkers (if files exist)
 */
$custom_walker = __DIR__ . '/inc/wp-bootstrap-navwalker.php';
if ( is_readable( $custom_walker ) ) {
	require_once $custom_walker;
}

$custom_walker_footer = __DIR__ . '/inc/wp-bootstrap-navwalker-footer.php';
if ( is_readable( $custom_walker_footer ) ) {
	require_once $custom_walker_footer;
}

/**
 * Dynamic Phone (advanced / LOAR-style)
 * Only enqueues if enabled in Customizer
 */
function kumo_enqueue_phone_ajax_script() {
	if ( ! get_theme_mod( 'enable_dynamic_phone' ) ) {
		return;
	}

	wp_enqueue_script(
		'dynamic-phone-ajax',
		get_template_directory_uri() . '/sources/dynamic-phone.js',
		array( 'jquery' ),
		'1.0',
		true
	);

	wp_localize_script(
		'dynamic-phone-ajax',
		'ajax_params',
		array(
			'ajax_url' => admin_url( 'admin-ajax.php' ),
			'nonce'    => wp_create_nonce( 'phone_number_nonce' ),
		)
	);
}
add_action( 'wp_enqueue_scripts', 'kumo_enqueue_phone_ajax_script' );

function kumo_ajax_dynamic_phone() {
	header( 'Cache-Control: no-cache, no-store, must-revalidate' );
	header( 'Pragma: no-cache' );
	header( 'Expires: 0' );

	check_ajax_referer( 'phone_number_nonce', 'nonce' );

	// If advanced dynamic phone is NOT enabled, return simple phone
	if ( ! get_theme_mod( 'enable_dynamic_phone' ) ) {
		$phone = get_theme_mod( 'site_phone' );
		if ( ! $phone ) {
			wp_send_json_success( '' );
			wp_die();
		}

		$output = '<a href="tel:' . preg_replace( '/[^0-9]/', '', $phone ) . '">' .
			'<span class="phonecall"><i class="icon-Phone_light"></i>' . esc_html( $phone ) . '</span></a>';

		wp_send_json_success( $output );
		wp_die();
	}

	// Advanced IP-based phone logic would go here
	// (keeping simplified for Kumo - most users won't need this)

	$default_phone = get_theme_mod( 'site_phone' ) ?: '';
	$output        = '<a href="tel:' . preg_replace( '/[^0-9]/', '', $default_phone ) . '">' .
		'<span class="phonecall"><i class="icon-Phone_light"></i>' . esc_html( $default_phone ) . '</span></a>';

	wp_send_json_success( $output );
	wp_die();
}

add_action( 'wp_ajax_dynamic_phone_number', 'kumo_ajax_dynamic_phone' );
add_action( 'wp_ajax_nopriv_dynamic_phone_number', 'kumo_ajax_dynamic_phone' );

/**
 * Common helper for ACF links
 */
function common_link( $acf_link, $link_classes = '', $show_title = true, $extra_title_html = '', $extra_title_html_place = 'before', $extra_attribute = '' ) {
	if ( $acf_link ) {
		$link_url    = $acf_link['url'];
		$link_title  = $acf_link['title'];
		$link_target = $acf_link['target'] ? $acf_link['target'] : '_self';
		$title       = '';

		if ( 'before' === $extra_title_html_place && $extra_title_html ) {
			$title .= $extra_title_html;
		}
		if ( $show_title ) {
			$title .= $link_title;
		}
		if ( 'after' === $extra_title_html_place && $extra_title_html ) {
			$title .= $extra_title_html;
		}

		echo '<a href="' . esc_url( $link_url ) . '" class="' . esc_attr( $link_classes ) . '" target="' . esc_attr( $link_target ) . '" ' . $extra_attribute . '>' . $title . '</a>';
	}
}

/**
 * Background class helper
 */
function returnBackground( $option ) {
	if ( 'light-bg' === $option ) {
		return 'multi-block-wrap light-bg';
	} elseif ( 'white-bg' === $option ) {
		return 'multi-block-wrap';
	}
	return '';
}

/**
 * Simple pagination helper
 */
function wp_paginate( $query ) {
	$current_page = max( 1, get_query_var( 'paged' ) );
	$total_pages  = $query->max_num_pages;

	if ( $total_pages > 1 ) {
		echo '<div class="pagination">';

		if ( $current_page < $total_pages ) {
			echo '<a href="' . esc_url( get_pagenum_link( $current_page + 1 ) ) . '" class="btn-primary">' . esc_html__( 'Next', 'kumo-foundation' ) . '</a>';
		} else {
			echo '<span class="btn-primary disabled">' . esc_html__( 'Next', 'kumo-foundation' ) . '</span>';
		}

		echo '</div>';
	}
}

/**
 * Test if a page is a blog page
 */
function is_blog() {
	global $post;
	$posttype = get_post_type( $post );
	return ( ( is_archive() || is_author() || is_category() || is_home() || is_single() || ( is_tag() && ( 'post' === $posttype ) ) ) ? true : false );
}