<?php
/**
 * Front-end assets.
 *
 * @package Gustavo_Portfolio
 */

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

/**
 * Return a cache-busting asset version.
 *
 * @param string $relative_path Theme-relative path.
 * @return string
 */
function gustavoo_portfolio_asset_version( $relative_path ) {
	$release = '1.1.0';
	$path = get_theme_file_path( '/' . ltrim( $relative_path, '/' ) );

	if ( file_exists( $path ) ) {
		return $release . '-' . (string) filemtime( $path );
	}

	return $release;
}

/**
 * Enqueue only local, versioned assets.
 *
 * @return void
 */
function gustavoo_portfolio_enqueue_assets() {
	wp_enqueue_style(
		'gustavoo-portfolio-style',
		get_stylesheet_uri(),
		array(),
		gustavoo_portfolio_asset_version( 'style.css' )
	);

	if ( file_exists( get_theme_file_path( '/assets/css/main.css' ) ) ) {
		wp_enqueue_style(
			'gustavoo-portfolio-main',
			get_theme_file_uri( '/assets/css/main.css' ),
			array( 'gustavoo-portfolio-style' ),
			gustavoo_portfolio_asset_version( 'assets/css/main.css' )
		);
	}

	if ( file_exists( get_theme_file_path( '/assets/js/navigation.js' ) ) ) {
		wp_enqueue_script(
			'gustavoo-portfolio-navigation',
			get_theme_file_uri( '/assets/js/navigation.js' ),
			array(),
			gustavoo_portfolio_asset_version( 'assets/js/navigation.js' ),
			true
		);

		wp_script_add_data( 'gustavoo-portfolio-navigation', 'strategy', 'defer' );
		wp_localize_script(
			'gustavoo-portfolio-navigation',
			'gustavooPortfolioNavigation',
			array(
				'expand'   => __( 'Abrir menu', 'gustavoo-portfolio' ),
				'collapse' => __( 'Fechar menu', 'gustavoo-portfolio' ),
			)
		);
	}

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