<?php
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

class IDVE_Block_Icon {

    public static function register( IDVE_Blocks $registry ) {
        $registry->register( 'icon', array(
            'label'    => __( 'Icon', 'insight-dezign-visual-editor' ),
            'icon'     => 'flag',
            'category' => 'content',
            'fields'   => array(
                'iconClass'  => array( 'type' => 'icon', 'label' => __( 'Icon', 'insight-dezign-visual-editor' ), 'default' => 'fa-solid fa-star' ),
                'iconSize'   => array( 'type' => 'text', 'label' => __( 'Size', 'insight-dezign-visual-editor' ), 'default' => '40px', 'tooltip' => 'Any CSS size value, e.g. 40px, 2em, 3rem' ),
                'iconColor'  => array( 'type' => 'color', 'label' => __( 'Color', 'insight-dezign-visual-editor' ), 'default' => '#333333' ),
                'alignment'  => array( 'type' => 'select', 'label' => __( 'Alignment', 'insight-dezign-visual-editor' ), 'options' => array( 'left', 'center', 'right' ), 'default' => 'center' ),
                'link'       => array( 'type' => 'text', 'label' => __( 'Link URL', 'insight-dezign-visual-editor' ), 'default' => '' ),
                'linkTarget' => array( 'type' => 'select', 'label' => __( 'Link Target', 'insight-dezign-visual-editor' ), 'options' => array( '_self', '_blank' ), 'default' => '_self', 'tooltip' => '_blank opens in a new tab' ),
            ),
            'render' => array( __CLASS__, 'render' ),
        ) );
    }

    public static function render( $data, $settings ) {
        $icon_class = ! empty( $data['iconClass'] ) ? $data['iconClass'] : 'fa-solid fa-star';
        $size       = ! empty( $data['iconSize'] ) ? $data['iconSize'] : '40px';
        $color      = ! empty( $data['iconColor'] ) ? $data['iconColor'] : '#333333';
        $alignment  = ! empty( $data['alignment'] ) ? $data['alignment'] : 'center';
        $link       = ! empty( $data['link'] ) ? $data['link'] : '';
        $target     = ! empty( $data['linkTarget'] ) ? $data['linkTarget'] : '_self';

        $classes = 'idve-icon';
        if ( ! empty( $settings['cssClass'] ) ) {
            $classes .= ' ' . esc_attr( $settings['cssClass'] );
        }

        $style = 'font-size:' . esc_attr( $size ) . ';color:' . esc_attr( $color );

        $icon_html = '<i class="' . esc_attr( $icon_class ) . ' ' . $classes . '" style="' . $style . '" aria-hidden="true"></i>';

        if ( ! empty( $link ) ) {
            $rel = '_blank' === $target ? ' rel="noopener noreferrer"' : '';
            $icon_html = '<a href="' . esc_url( $link ) . '" target="' . esc_attr( $target ) . '" style="text-decoration:none;color:inherit"' . $rel . '>' . $icon_html . '</a>';
        }

        return '<div class="idve-icon-wrapper" style="text-align:' . esc_attr( $alignment ) . '">' . $icon_html . '</div>';
    }
}
