<?php

use EVPB\Tools\AdvancedTab;
use EVPB\Tools\Helper;
use EVPB\Tools\ToCSS;

$prefix = 'evbCell';
$id = wp_unique_id( "$prefix-" );
$innerBlocks = $content;

if( !function_exists( 'evbCellWidthVal' ) ) {
	function evbCellWidthVal( $content, $device ) {
		$isFullWidth = $content['isFullWidth'] ?? true;
		$width = $content['width'] ?? [];

		return ( $isFullWidth || 0 === intval( $width[$device] ?? 0 ) ) ? '100%' : $width[$device];
	}
}
if( !function_exists( 'evbCellDeviceCSS' ) ) {
	function evbCellDeviceCSS( $id, $attributes, $device ) {
		extract( $attributes ?? [] );
		extract( $cells ?? [] );
		extract( $content ?? [] );
		extract( $items ?? [] );

		return "#$id {
			grid-column: auto / span ". ( $column[$device] ?? 1 ) .";
			grid-row: auto / span ". ( $row[$device] ?? 1 ) .";
		}
		#$id >.evbCell >.evbCellContent {
			max-width: " . evbCellWidthVal( $content, $device ) . ';' .
			ToCSS::hasCSS( 'height', !empty( $height[$device] ?? '' ) ? ToCSS::autoOrVal( $height[$device] ) : '' ) .
			ToCSS::hasCSS( 'align-self', $alignment['vertical'][$device] ?? '' ) .
			ToCSS::hasCSS( 'justify-self', $alignment['horizontal'][$device] ?? '' ) .
			ToCSS::hasCSS( 'text-align', $alignment['text'][$device] ?? '' ) .
			ToCSS::hasCSS( 'flex-direction', $direction[$device] ?? 'column' ) .
			ToCSS::hasCSS( 'justify-content', $justify[$device] ?? '' ) .
			ToCSS::hasCSS( 'align-items', $align[$device] ?? '' ) .
			ToCSS::hasCSS( 'flex-wrap', $wrap[$device] ?? '' ) .
			ToCSS::hasCSS( 'column-gap', $columnGap[$device] ?? '' ) .
			ToCSS::hasCSS( 'row-gap', $rowGap[$device] ?? '' ) .
		"}";
	}
}

if( !function_exists( 'evbCellStyle' ) ) {
	function evbCellStyle( $attributes, $id ) {
		extract( $attributes ?? [] );

		$styles = evbCellDeviceCSS( $id, $attributes, 'desktop' ) .
			Helper::TAB_BREAKPOINT ." {" .
				evbCellDeviceCSS( $id, $attributes, 'tablet' ) . "
			}
			". Helper::MOB_BREAKPOINT ." {" .
				evbCellDeviceCSS( $id, $attributes, 'mobile' ) . "
			}
		";

		return $styles;
	}
}

extract( $attributes ?? [] );

$evbRowCellCSS = AdvancedTab::generateCSS( "#$id", "#$id >.$prefix", $advanced ) . evbCellStyle( $attributes, $id );
if ( ! empty( trim( $evbRowCellCSS ) ) ) {
	wp_add_inline_style( 'evb-row-columns-style', $evbRowCellCSS );
}

if( isset( $advanced['animation']['type'] ) && !empty( $advanced['animation']['type'] ) ) {
	wp_enqueue_style( 'aos' );
	wp_enqueue_script( 'aos' );
}

$tag = $advanced['layout']['tag'] ?? 'div';

?>
<<?php echo esc_attr( $tag ); ?>
	<?php echo wp_kses_data( get_block_wrapper_attributes() ); ?>
	id='<?php echo esc_attr( $id ); ?>'
	<?php echo wp_kses_data( AdvancedTab::animationProps( $advanced['animation'] ?? null ) ); ?>
>
	<div <?php echo AdvancedTab::getAdvancedAttributes( $advanced['attributes'] ?? [], [ 'class' => $prefix ] ); ?>>
		<div class='<?php echo esc_attr( $prefix ); ?>Content'>
			<?php echo wp_kses( $innerBlocks, Helper::allowedHTML() ); ?>
		</div>
	</div>
</<?php echo esc_attr( $tag ); ?>>