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

class IDVE_Block_Audio {

    public static function register( IDVE_Blocks $registry ) {
        $registry->register( 'audio', array(
            'label'    => __( 'Audio', 'insight-dezign-visual-editor' ),
            'icon'     => 'format-audio',
            'category' => 'media',
            'fields'   => array(
                'audioUrl' => array( 'type' => 'audio', 'label' => __( 'Audio File', 'insight-dezign-visual-editor' ), 'default' => '' ),
                'controls' => array( 'type' => 'toggle', 'label' => __( 'Show Controls', 'insight-dezign-visual-editor' ), 'default' => true ),
                'loop'     => array( 'type' => 'toggle', 'label' => __( 'Loop', 'insight-dezign-visual-editor' ), 'default' => false ),
                'autoplay' => array( 'type' => 'toggle', 'label' => __( 'Autoplay', 'insight-dezign-visual-editor' ), 'default' => false ),
                'preload'  => array( 'type' => 'select', 'label' => __( 'Preload', 'insight-dezign-visual-editor' ), 'options' => array( 'none', 'metadata', 'auto' ), 'default' => 'metadata' ),
                'caption'  => array( 'type' => 'text', 'label' => __( 'Caption', 'insight-dezign-visual-editor' ), 'default' => '' ),
            ),
            'render' => array( __CLASS__, 'render' ),
        ) );
    }

    public static function render( $data, $settings ) {
        $url = isset( $data['audioUrl'] ) ? $data['audioUrl'] : '';
        if ( empty( $url ) ) {
            return '';
        }

        $attrs = 'src="' . esc_url( $url ) . '"';

        $controls = isset( $data['controls'] ) ? $data['controls'] : true;
        if ( $controls ) {
            $attrs .= ' controls';
        }

        if ( ! empty( $data['loop'] ) ) {
            $attrs .= ' loop';
        }

        if ( ! empty( $data['autoplay'] ) ) {
            $attrs .= ' autoplay';
        }

        $preload = isset( $data['preload'] ) ? sanitize_key( $data['preload'] ) : 'metadata';
        $attrs  .= ' preload="' . esc_attr( $preload ) . '"';

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

        $html = '<figure class="' . $fig_class . '"><audio ' . $attrs . '></audio>';

        $caption = isset( $data['caption'] ) ? $data['caption'] : '';
        if ( ! empty( $caption ) ) {
            $html .= '<figcaption>' . esc_html( $caption ) . '</figcaption>';
        }

        $html .= '</figure>';
        return $html;
    }
}
