<?php
/**
 * Render callback for the AxcelersBlocks Table block.
 *
 * The table is composed of inner section / row / cell blocks. This renders the
 * <table> wrapper (with its own attribute-driven CSS) and prints the inner block
 * content.
 *
 * @package AxcelersBlocks
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

require_once dirname( __DIR__, 3 ) . '/includes/table-block-render-helpers.php';

$axcelersblocks_block_name = isset( $block->name ) ? str_replace( '/', '-', $block->name ) . '-block' : 'axcelersblocks-table-block';

$axcelersblocks_table_classes = array( 'axcelersblocks-table' );

// Build a <colgroup> from the `cols` attribute (manual column definitions). Only
// set values are emitted, so an unconfigured column stays a bare <col>.
$axcelersblocks_colgroup = '';
if ( ! empty( $attributes['cols'] ) && is_array( $attributes['cols'] ) ) {
	$axcelersblocks_cols_html = '';
	foreach ( $attributes['cols'] as $axcelersblocks_col ) {
		$axcelersblocks_col_attrs = array();

		$axcelersblocks_span = isset( $axcelersblocks_col['span'] ) ? absint( $axcelersblocks_col['span'] ) : 1;
		if ( $axcelersblocks_span > 1 ) {
			$axcelersblocks_col_attrs['span'] = (string) $axcelersblocks_span;
		}

		$axcelersblocks_styles = array();
		if ( ! empty( $axcelersblocks_col['width'] ) ) {
			$axcelersblocks_col_width = axcelersblocks_sanitize_css_value( $axcelersblocks_col['width'] );
			if ( '' !== $axcelersblocks_col_width ) {
				$axcelersblocks_styles[] = 'width:' . $axcelersblocks_col_width;
			}
		}
		if ( ! empty( $axcelersblocks_col['backgroundColor'] ) ) {
			$axcelersblocks_col_bg = axcelersblocks_sanitize_css_value( $axcelersblocks_col['backgroundColor'] );
			if ( '' !== $axcelersblocks_col_bg ) {
				$axcelersblocks_styles[] = 'background-color:' . $axcelersblocks_col_bg;
			}
		}
		if ( $axcelersblocks_styles ) {
			$axcelersblocks_col_attrs['style'] = implode( ';', $axcelersblocks_styles );
		}

		$axcelersblocks_cols_html .= '<col ' . axcelersblocks_table_build_attrs( $axcelersblocks_col_attrs ) . ' />';
	}
	if ( '' !== $axcelersblocks_cols_html ) {
		$axcelersblocks_colgroup = '<colgroup>' . $axcelersblocks_cols_html . '</colgroup>';
	}
}

echo wp_kses_post(
	axcelersblocks_table_render_element(
		$attributes,
		$axcelersblocks_colgroup . $content,
		$axcelersblocks_block_name,
		array(
			'allowed_tags'  => array( 'table' ),
			'default_tag'   => 'table',
			'base_classes'  => $axcelersblocks_table_classes,
			'fallback_slug' => 'axb-table',
		)
	)
);
