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

class IDVE_Block_Video {

    public static function register( IDVE_Blocks $registry ) {
        $registry->register( 'video', array(
            'label'    => __( 'Video', 'insight-dezign-visual-editor' ),
            'icon'     => 'video-alt3',
            'category' => 'media',
            'fields'   => array(
                'url'         => array( 'type' => 'text', 'label' => __( 'Video URL', 'insight-dezign-visual-editor' ), 'default' => '' ),
                'aspectRatio' => array( 'type' => 'select', 'label' => __( 'Aspect Ratio', 'insight-dezign-visual-editor' ), 'options' => array( '16:9', '4:3', '1:1' ), 'default' => '16:9' ),
            ),
            'render' => array( __CLASS__, 'render' ),
        ) );
    }

    public static function render( $data, $settings ) {
        $url   = isset( $data['url'] ) ? $data['url'] : '';
        $ratio = isset( $data['aspectRatio'] ) ? $data['aspectRatio'] : '16:9';

        if ( empty( $url ) ) {
            return '';
        }

        $ratio_class = 'idve-aspect-' . str_replace( ':', '-', $ratio );
        if ( ! empty( $settings['cssClass'] ) ) {
            $ratio_class .= ' ' . esc_attr( $settings['cssClass'] );
        }
        $embed_url = self::get_embed_url( $url );

        $padding_map = array( '16:9' => '56.25%', '4:3' => '75%', '1:1' => '100%' );
        $pad         = isset( $padding_map[ $ratio ] ) ? $padding_map[ $ratio ] : '56.25%';
        $wrap_style  = 'position:relative;width:100%;overflow:hidden;padding-bottom:' . $pad;
        $inner_style = 'position:absolute;top:0;left:0;width:100%;height:100%';

        if ( $embed_url ) {
            return '<div class="idve-video-wrapper ' . esc_attr( $ratio_class ) . '" style="' . esc_attr( $wrap_style ) . '">'
                . '<iframe src="' . esc_url( $embed_url ) . '" frameborder="0" allowfullscreen loading="lazy" style="' . esc_attr( $inner_style ) . '"></iframe>'
                . '</div>';
        }

        return '<div class="idve-video-wrapper ' . esc_attr( $ratio_class ) . '" style="' . esc_attr( $wrap_style ) . '">'
            . '<video src="' . esc_url( $url ) . '" controls style="' . esc_attr( $inner_style ) . '"></video>'
            . '</div>';
    }

    private static function get_embed_url( $url ) {
        // YouTube
        if ( preg_match( '/(?:youtube\.com\/(?:watch\?v=|embed\/)|youtu\.be\/)([a-zA-Z0-9_-]{11})/', $url, $m ) ) {
            return 'https://www.youtube.com/embed/' . $m[1];
        }
        // Vimeo
        if ( preg_match( '/vimeo\.com\/(?:video\/)?(\d+)/', $url, $m ) ) {
            return 'https://player.vimeo.com/video/' . $m[1];
        }
        return false;
    }
}
