<?php
/**
 * Eshraq Portfolio Theme Functions
 *
 * @package Eshraq_Portfolio
 * @since 1.0.0
 */

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

define( 'ESHRAQ_VERSION', '1.0.0' );
define( 'ESHRAQ_DIR', get_template_directory() );
define( 'ESHRAQ_URI', get_template_directory_uri() );

/**
 * Theme Setup
 *
 * Registers theme support, menus, and other core features.
 */
function eshraq_setup() {
	// Add default posts and comments RSS feed links to head.
	add_theme_support( 'automatic-feed-links' );

	// 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' );
	set_post_thumbnail_size( 1200, 800, true );
	add_image_size( 'eshraq-portfolio', 1920, 1080, true );
	add_image_size( 'eshraq-thumb', 600, 400, true );

	// Register navigation menus.
	register_nav_menus( array(
		'primary'   => esc_html__( 'Primary Menu', 'eshraq-portfolio' ),
		'footer'    => esc_html__( 'Footer Menu', 'eshraq-portfolio' ),
		'social'    => esc_html__( 'Social Links', 'eshraq-portfolio' ),
	) );

	// Switch default core markup to output valid HTML5.
	add_theme_support( 'html5', array(
		'search-form',
		'comment-form',
		'comment-list',
		'gallery',
		'caption',
		'style',
		'script',
		'navigation-widgets',
	) );

	// Add support for custom logo.
	add_theme_support( 'custom-logo', array(
		'height'      => 100,
		'width'       => 300,
		'flex-width'  => true,
		'flex-height' => true,
	) );

	// Add support for custom background.
	add_theme_support( 'custom-background', array(
		'default-color' => 'f8f6f1',
	) );

	// Add support for selective refresh for widgets.
	add_theme_support( 'customize-selective-refresh-widgets' );

	// Add support for Block Editor.
	add_theme_support( 'wp-block-styles' );
	add_theme_support( 'editor-styles' );
	add_editor_style( 'assets/css/editor-style.css' );

	// Add support for responsive embeds.
	add_theme_support( 'responsive-embeds' );

	// Add support for editor color palette.
	add_theme_support( 'editor-color-palette', array(
		array(
			'name'  => esc_html__( 'Black', 'eshraq-portfolio' ),
			'slug'  => 'eshraq-black',
			'color' => '#0a0a0a',
		),
		array(
			'name'  => esc_html__( 'White', 'eshraq-portfolio' ),
			'slug'  => 'eshraq-white',
			'color' => '#f8f6f1',
		),
		array(
			'name'  => esc_html__( 'Warm Gray', 'eshraq-portfolio' ),
			'slug'  => 'eshraq-warm-gray',
			'color' => '#c8c8c8',
		),
		array(
			'name'  => esc_html__( 'Muted', 'eshraq-portfolio' ),
			'slug'  => 'eshraq-muted',
			'color' => '#999999',
		),
	) );

	// Translation support.
	load_theme_textdomain( 'eshraq-portfolio', ESHRAQ_DIR . '/languages' );
}
add_action( 'after_setup_theme', 'eshraq_setup' );

/**
 * Enqueue scripts and styles.
 */
function eshraq_scripts() {
	// Google Fonts - DM Sans (clean sans-serif) and Playfair Display (elegant serif).
	wp_enqueue_style(
		'eshraq-google-fonts',
		'https://fonts.googleapis.com/css2?family=DM+Sans:ital,opsz,wght@0,9..40,300;0,9..40,400;0,9..40,500;0,9..40,600;1,9..40,400&family=Playfair+Display:ital,wght@0,400;0,500;0,600;0,700;1,400;1,500&display=swap',
		array(),
		null
	);

	// Main stylesheet.
	wp_enqueue_style(
		'eshraq-main',
		ESHRAQ_URI . '/assets/css/main.css',
		array( 'eshraq-google-fonts' ),
		ESHRAQ_VERSION
	);

	// Theme stylesheet (style.css contains theme metadata only).
	wp_enqueue_style(
		'eshraq-style',
		get_stylesheet_uri(),
		array( 'eshraq-main' ),
		ESHRAQ_VERSION
	);

	// Main JavaScript.
	wp_enqueue_script(
		'eshraq-main',
		ESHRAQ_URI . '/assets/js/main.js',
		array(),
		ESHRAQ_VERSION,
		true
	);

	// Localize script for AJAX and accessibility.
	wp_localize_script( 'eshraq-main', 'eshraqData', array(
		'ajaxUrl' => esc_url( admin_url( 'admin-ajax.php' ) ),
		'nonce'   => wp_create_nonce( 'eshraq_nonce' ),
		'homeUrl' => esc_url( home_url( '/' ) ),
	) );

	// Comment reply script.
	if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) {
		wp_enqueue_script( 'comment-reply' );
	}
}
add_action( 'wp_enqueue_scripts', 'eshraq_scripts' );

/**
 * Register widget areas.
 */
function eshraq_widgets_init() {
	register_sidebar( array(
		'name'          => esc_html__( 'Footer Widget Area', 'eshraq-portfolio' ),
		'id'            => 'footer-widgets',
		'description'   => esc_html__( 'Add widgets to the footer area.', 'eshraq-portfolio' ),
		'before_widget' => '<div id="%1$s" class="widget %2$s">',
		'after_widget'  => '</div>',
		'before_title'  => '<h3 class="widget-title">',
		'after_title'   => '</h3>',
	) );

	register_sidebar( array(
		'name'          => esc_html__( 'Blog Sidebar', 'eshraq-portfolio' ),
		'id'            => 'blog-sidebar',
		'description'   => esc_html__( 'Add widgets to the blog sidebar.', 'eshraq-portfolio' ),
		'before_widget' => '<div id="%1$s" class="widget %2$s">',
		'after_widget'  => '</div>',
		'before_title'  => '<h3 class="widget-title">',
		'after_title'   => '</h3>',
	) );
}
add_action( 'widgets_init', 'eshraq_widgets_init' );

/**
 * Custom walker for the primary navigation menu.
 *
 * Adds aria attributes and smooth transition support.
 */
class Eshraq_Nav_Walker extends Walker_Nav_Menu {

	/**
	 * Starts the list before the elements are added.
	 */
	public function start_lvl( &$output, $depth = 0, $args = null ) {
		$indent  = str_repeat( "\t", $depth );
		$output .= "\n{$indent}<ul class=\"sub-menu\">\n";
	}

	/**
	 * Starts the element output.
	 */
	public function start_el( &$output, $item, $depth = 0, $args = null, $id = 0 ) {
		$indent  = ( $depth ) ? str_repeat( "\t", $depth ) : '';
		$classes = empty( $item->classes ) ? array() : (array) $item->classes;
		$classes[] = 'nav-link-item';

		if ( in_array( 'menu-item-current', $classes, true ) || in_array( 'current-menu-item', $classes, true ) ) {
			$classes[] = 'is-active';
		}

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

		$output .= $indent . '<li' . $class_names . '>';

		$atts = array(
			'title'  => ! empty( $item->attr_title ) ? $item->attr_title : '',
			'target' => ! empty( $item->target ) ? $item->target : '',
			'rel'    => ! empty( $item->xfn ) ? $item->xfn : '',
			'href'   => ! empty( $item->url ) ? $item->url : '',
			'class'  => 'nav-link',
		);

		if ( $depth === 0 ) {
			$atts['class'] .= ' nav-link--primary';
		}

		$atts = apply_filters( 'nav_menu_link_attributes', $atts, $item, $args, $depth );

		$attributes = '';
		foreach ( $atts as $attr => $value ) {
			if ( ! empty( $value ) ) {
				$value       = ( 'href' === $attr ) ? esc_url( $value ) : esc_attr( $value );
				$attributes .= ' ' . $attr . '="' . $value . '"';
			}
		}

		$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 );
	}
}

/**
 * Custom excerpt length.
 */
function eshraq_excerpt_length( $length ) {
	return 30;
}
add_filter( 'excerpt_length', 'eshraq_excerpt_length', 999 );

/**
 * Custom excerpt more.
 */
function eshraq_excerpt_more( $more ) {
	return '&hellip;';
}
add_filter( 'excerpt_more', 'eshraq_excerpt_more' );

/**
 * Add body classes.
 */
function eshraq_body_classes( $classes ) {
	if ( is_singular() ) {
		$classes[] = 'singular';
	}

	if ( is_front_page() && ! is_home() ) {
		$classes[] = 'front-page';
	}

	if ( is_home() ) {
		$classes[] = 'blog-page';
	}

	if ( ! has_nav_menu( 'primary' ) ) {
		$classes[] = 'no-primary-menu';
	}

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

/**
 * Customizer settings.
 */
require ESHRAQ_DIR . '/inc/customizer.php';

/**
 * Custom template functions.
 */
require ESHRAQ_DIR . '/inc/template-tags.php';

/**
 * AJAX handler for portfolio loading.
 */
function eshraq_load_portfolio_items() {
	check_ajax_referer( 'eshraq_nonce', 'nonce' );

	$paged = isset( $_POST['page'] ) ? absint( $_POST['page'] ) : 1;
	$cat   = isset( $_POST['category'] ) ? sanitize_text_field( wp_unslash( $_POST['category'] ) ) : '';

	$args = array(
		'post_type'      => 'portfolio',
		'posts_per_page' => 12,
		'paged'          => $paged,
		'post_status'    => 'publish',
	);

	if ( ! empty( $cat ) ) {
		$args['tax_query'] = array(
			array(
				'taxonomy' => 'portfolio_category',
				'field'    => 'slug',
				'terms'    => $cat,
			),
		);
	}

	$query = new WP_Query( $args );

	if ( $query->have_posts() ) {
		while ( $query->have_posts() ) {
			$query->the_post();
			get_template_part( 'template-parts/portfolio', 'item' );
		}
		wp_reset_postdata();
	}

	wp_send_json_success();
}
add_action( 'wp_ajax_eshraq_load_portfolio', 'eshraq_load_portfolio_items' );
add_action( 'wp_ajax_nopriv_eshraq_load_portfolio', 'eshraq_load_portfolio_items' );

/**
 * Register Custom Post Type: Portfolio
 */
function eshraq_register_portfolio_cpt() {
	$labels = array(
		'name'               => esc_html__( 'Portfolio', 'eshraq-portfolio' ),
		'singular_name'      => esc_html__( 'Project', 'eshraq-portfolio' ),
		'menu_name'          => esc_html__( 'Portfolio', 'eshraq-portfolio' ),
		'add_new'            => esc_html__( 'Add New Project', 'eshraq-portfolio' ),
		'add_new_item'       => esc_html__( 'Add New Project', 'eshraq-portfolio' ),
		'edit_item'          => esc_html__( 'Edit Project', 'eshraq-portfolio' ),
		'new_item'           => esc_html__( 'New Project', 'eshraq-portfolio' ),
		'view_item'          => esc_html__( 'View Project', 'eshraq-portfolio' ),
		'search_items'       => esc_html__( 'Search Projects', 'eshraq-portfolio' ),
		'not_found'          => esc_html__( 'No projects found', 'eshraq-portfolio' ),
		'not_found_in_trash' => esc_html__( 'No projects found in Trash', 'eshraq-portfolio' ),
		'all_items'          => esc_html__( 'All Projects', 'eshraq-portfolio' ),
	);

	$args = array(
		'labels'             => $labels,
		'public'             => true,
		'publicly_queryable' => true,
		'show_ui'            => true,
		'show_in_menu'       => true,
		'query_var'          => true,
		'rewrite'            => array( 'slug' => 'project' ),
		'capability_type'    => 'post',
		'has_archive'        => true,
		'hierarchical'       => false,
		'menu_position'      => 5,
		'menu_icon'          => 'dashicons-portfolio',
		'supports'           => array( 'title', 'editor', 'thumbnail', 'excerpt', 'custom-fields' ),
		'show_in_rest'       => true,
	);

	register_post_type( 'portfolio', $args );

	// Register Portfolio Categories taxonomy.
	$cat_labels = array(
		'name'          => esc_html__( 'Categories', 'eshraq-portfolio' ),
		'singular_name' => esc_html__( 'Category', 'eshraq-portfolio' ),
		'search_items'  => esc_html__( 'Search Categories', 'eshraq-portfolio' ),
		'all_items'     => esc_html__( 'All Categories', 'eshraq-portfolio' ),
		'edit_item'     => esc_html__( 'Edit Category', 'eshraq-portfolio' ),
		'update_item'   => esc_html__( 'Update Category', 'eshraq-portfolio' ),
		'add_new_item'  => esc_html__( 'Add New Category', 'eshraq-portfolio' ),
		'new_item_name' => esc_html__( 'New Category Name', 'eshraq-portfolio' ),
		'menu_name'     => esc_html__( 'Categories', 'eshraq-portfolio' ),
	);

	register_taxonomy( 'portfolio_category', 'portfolio', array(
		'labels'            => $cat_labels,
		'hierarchical'      => true,
		'public'            => true,
		'show_ui'           => true,
		'show_admin_column' => true,
		'show_in_rest'      => true,
		'rewrite'           => array( 'slug' => 'portfolio-category' ),
	) );
}
add_action( 'init', 'eshraq_register_portfolio_cpt' );

/**
 * Register Custom Post Type: Testimonials
 */
function eshraq_register_testimonial_cpt() {
	$labels = array(
		'name'               => esc_html__( 'Testimonials', 'eshraq-portfolio' ),
		'singular_name'      => esc_html__( 'Testimonial', 'eshraq-portfolio' ),
		'menu_name'          => esc_html__( 'Testimonials', 'eshraq-portfolio' ),
		'add_new'            => esc_html__( 'Add New', 'eshraq-portfolio' ),
		'add_new_item'       => esc_html__( 'Add New Testimonial', 'eshraq-portfolio' ),
		'edit_item'          => esc_html__( 'Edit Testimonial', 'eshraq-portfolio' ),
		'new_item'           => esc_html__( 'New Testimonial', 'eshraq-portfolio' ),
		'view_item'          => esc_html__( 'View Testimonial', 'eshraq-portfolio' ),
		'search_items'       => esc_html__( 'Search Testimonials', 'eshraq-portfolio' ),
		'not_found'          => esc_html__( 'No testimonials found', 'eshraq-portfolio' ),
		'not_found_in_trash' => esc_html__( 'No testimonials found in Trash', 'eshraq-portfolio' ),
		'all_items'          => esc_html__( 'All Testimonials', 'eshraq-portfolio' ),
	);

	$args = array(
		'labels'             => $labels,
		'public'             => false,
		'show_ui'            => true,
		'show_in_menu'       => true,
		'capability_type'    => 'post',
		'has_archive'        => false,
		'hierarchical'       => false,
		'menu_position'      => 6,
		'menu_icon'          => 'dashicons-format-quote',
		'supports'           => array( 'title', 'editor', 'thumbnail' ),
		'show_in_rest'       => true,
	);

	register_post_type( 'testimonial', $args );
}
add_action( 'init', 'eshraq_register_testimonial_cpt' );

/**
 * Portfolio query modifier for the front page.
 */
function eshraq_portfolio_query( $query ) {
	if ( is_admin() || ! is_front_page() ) {
		return;
	}

	$query->set( 'post_type', array( 'portfolio', 'post' ) );
	$query->set( 'posts_per_page', 12 );
}
add_action( 'pre_get_posts', 'eshraq_portfolio_query' );

/**
 * Add preload for critical fonts.
 */
function eshraq_resource_hints( $urls, $relation_type ) {
	if ( 'preconnect' === $relation_type ) {
		$urls[] = array(
			'href' => 'https://fonts.googleapis.com',
			'crossorigin',
		);
		$urls[] = array(
			'href' => 'https://fonts.gstatic.com',
			'crossorigin',
		);
	}
	return $urls;
}
add_filter( 'wp_resource_hints', 'eshraq_resource_hints', 10, 2 );

/**
 * Add custom meta to head.
 */
function eshraq_meta_tags() {
	?>
	<meta name="theme-color" content="#0a0a0a">
	<?php
}
add_action( 'wp_head', 'eshraq_meta_tags', 1 );
