<?php defined('BASEPATH') or exit('No direct script access allowed');

$label = isset($label) ? $label : '';
$href = isset($href) ? $href : '';
$type = isset($type) ? $type : 'button';
$variant = isset($variant) ? $variant : 'secondary';
$icon = isset($icon) ? $icon : '';
$size = isset($size) ? $size : 'md';
$icon_only = !empty($icon_only);
$disabled = !empty($disabled);
$class = isset($class) ? $class : '';
$attrs = isset($attrs) && is_array($attrs) ? $attrs : array();

$variant_map = array(
	'primary' => 'erp-btn erp-btn-primary',
	'secondary' => 'erp-btn erp-btn-secondary',
	'ghost' => 'erp-btn erp-btn-ghost',
	'danger' => 'erp-btn erp-btn-danger',
	'success' => 'erp-btn erp-btn-success',
	'toolbar' => 'erp-btn erp-btn-toolbar',
	'icon' => 'erp-btn erp-btn-icon',
);

$size_map = array(
	'sm' => 'erp-btn--sm',
	'md' => 'erp-btn--md',
	'lg' => 'erp-btn--lg',
);

$button_class = isset($variant_map[$variant]) ? $variant_map[$variant] : $variant_map['secondary'];
$button_class .= isset($size_map[$size]) ? ' ' . $size_map[$size] : ' ' . $size_map['md'];
if ($icon_only) {
	$button_class .= ' erp-btn-icon';
}
if ($class !== '') {
	$button_class .= ' ' . $class;
}

$attr_parts = array();
foreach ($attrs as $attr_key => $attr_value) {
	if ($attr_value === null || $attr_value === false) {
		continue;
	}
	if ($attr_value === true) {
		$attr_parts[] = html_escape($attr_key);
		continue;
	}
	$attr_parts[] = html_escape($attr_key) . '="' . html_escape($attr_value) . '"';
}
if ($disabled) {
	$attr_parts[] = 'disabled';
	$attr_parts[] = 'aria-disabled="true"';
}
$attr_string = !empty($attr_parts) ? ' ' . implode(' ', $attr_parts) : '';
?>

<?php if ($href !== '') { ?>
	<a href="<?= html_escape($href); ?>" class="<?= $button_class; ?>"<?= $attr_string; ?>>
		<?php if ($icon !== '') { ?>
			<i data-lucide="<?= html_escape($icon); ?>" class="h-4 w-4"></i>
		<?php } ?>
		<?php if (!$icon_only) { ?>
			<span><?= html_escape($label); ?></span>
		<?php } ?>
	</a>
<?php } else { ?>
	<button type="<?= html_escape($type); ?>" class="<?= $button_class; ?>"<?= $attr_string; ?>>
		<?php if ($icon !== '') { ?>
			<i data-lucide="<?= html_escape($icon); ?>" class="h-4 w-4"></i>
		<?php } ?>
		<?php if (!$icon_only) { ?>
			<span><?= html_escape($label); ?></span>
		<?php } ?>
	</button>
<?php } ?>
