<?php
/**
 * The template to display button.
 *
 * This template can be overridden by copying it to
 * your-child-theme/views/button.php.
 *
 * @package MadeByAura\Prime
 * @author  MadeByAura.com
 *
 * @param array $args
 */

namespace MadeByAura\Prime;

use MadeByAura\Prime\Helpers\Markup;
use MadeByAura\Prime\Helpers\Assorted;

defined( 'ABSPATH' ) || die();

// Merge incoming `$args` with defaults.
$args = array_replace_recursive(
	[
		'type'             => '1',
		'tag'              => 'a',
		'text'             => __( 'Button', 'aura-prime' ),
		'url'              => '#',
		'target'           => '',
		'nofollow'         => false,
		'icon_enabled'     => true,
		'icon_before_text' => false,
		'icon_mask_image'  => true,
		'class'            => '',
		'attrs'            => [],
	],
	$args,
);

// Do not proceed if tag, text, or url are empty.
if ( ! ( $args['tag'] && $args['text'] && $args['url'] ) ) {
	return;
}

// Set CSS classes.
$classes[] = $args['class'];
$classes[] = 'aura-button';
$classes[] = $args['type'] ? 'aura-button--' . Assorted::dashify( $args['type'] ) : '';
// Classes - Icon.
if ( $args['icon_enabled'] ) {
	$classes[] = 'aura-button--has-icon';
	$classes[] = $args['icon_before_text'] ? 'aura-button--icon-before-text' : 'aura-button--icon-after-text';
	$classes[] = $args['icon_mask_image'] ? 'aura-button--icon-mask-image' : 'aura-button--icon-background-image';
}

// Set HTML attributes.
$attrs['class'] = $classes;

// Anchor tag attributes.
if ( 'a' === $args['tag'] ) {
	$attrs['href']   = $args['url'];
	$attrs['target'] = $args['target'];
	$attrs['rel']    = $args['attrs']['rel'] ?? '';

	if ( '_blank' === $args['target'] ) {
		$attrs['rel'] = "{$attrs['rel']} noopener";
	}

	if ( true === $args['nofollow'] ) {
		$attrs['rel'] = "{$attrs['rel']} nofollow";
	}

	if ( $attrs['rel'] ) {
		$attrs['rel'] = trim( $attrs['rel'] );
	}
}

// Merge explicit attributes with implicit attributes.
$attrs = Markup::merge_attrs( $attrs, $args['attrs'] );
?>

<<?php echo tag_escape( $args['tag'] ); ?> <?php Markup::echo_attrs( $attrs ); ?>>
	<?php echo wp_kses( $args['text'], [ 'b' => [] ] ); ?>
</<?php echo tag_escape( $args['tag'] ); ?>>
