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

class IDVE_Block_Heading {

    public static function register( IDVE_Blocks $registry ) {
        $registry->register( 'heading', array(
            'label'    => __( 'Heading', 'insight-dezign-visual-editor' ),
            'icon'     => 'heading',
            'category' => 'content',
            'fields'   => array(
                'content'   => array( 'type' => 'text', 'label' => __( 'Heading Text', 'insight-dezign-visual-editor' ), 'default' => '' ),
                'level'     => array( 'type' => 'select', 'label' => __( 'Level', 'insight-dezign-visual-editor' ), 'options' => array( 'h1', 'h2', 'h3', 'h4', 'h5', 'h6' ), 'default' => 'h2' ),
                'alignment' => array( 'type' => 'select', 'label' => __( 'Alignment', 'insight-dezign-visual-editor' ), 'options' => array( 'left', 'center', 'right' ), 'default' => 'left' ),
                'color'     => array( 'type' => 'color', 'label' => __( 'Color', 'insight-dezign-visual-editor' ), 'default' => '' ),
                'fontSize'  => array( 'type' => 'text', 'label' => __( 'Font Size', 'insight-dezign-visual-editor' ), 'default' => '' ),
            ),
            'render' => array( __CLASS__, 'render' ),
        ) );
    }

    public static function render( $data, $settings ) {
        $content = isset( $data['content'] ) ? $data['content'] : '';
        $level   = isset( $data['level'] ) ? $data['level'] : 'h2';

        $allowed = array( 'h1', 'h2', 'h3', 'h4', 'h5', 'h6' );
        if ( ! in_array( $level, $allowed, true ) ) {
            $level = 'h2';
        }

        $style_parts = array();
        if ( ! empty( $data['color'] ) ) {
            $c = self::sanitize_color( $data['color'] );
            if ( $c ) {
                $style_parts[] = 'color:' . $c;
            }
        }
        if ( ! empty( $data['fontSize'] ) ) {
            $style_parts[] = 'font-size:' . esc_attr( $data['fontSize'] );
        }

        $style_attr = '';
        if ( ! empty( $style_parts ) ) {
            $style_attr = ' style="' . esc_attr( implode( ';', $style_parts ) ) . '"';
        }

        $class_attr = '';
        if ( ! empty( $settings['cssClass'] ) ) {
            $class_attr = ' class="' . esc_attr( $settings['cssClass'] ) . '"';
        }

        return '<' . $level . $class_attr . $style_attr . '>' . esc_html( $content ) . '</' . $level . '>';
    }

    private static function sanitize_color( $color ) {
        if ( empty( $color ) || 'transparent' === $color ) {
            return '';
        }
        if ( preg_match( '/^#[0-9a-fA-F]{3,8}$/', $color ) ) {
            return $color;
        }
        if ( preg_match( '/^rgba?\(\s*\d{1,3}\s*,\s*\d{1,3}\s*,\s*\d{1,3}\s*(,\s*[\d.]+)?\s*\)$/', $color ) ) {
            return $color;
        }
        return '';
    }
}
