<?php
defined( 'ABSPATH' ) || exit;

class Jalpi_Element_Table extends Jalpi_Element {
    public static function type(): string { return 'table'; }

    public function render( array $node, Jalpi_Renderer $renderer ): string {
        $id      = sanitize_html_class( $node['id'] ?? '' );
        $content = $node['content'] ?? [];
        $styles  = $node['styles']  ?? [];
        $headers = (array) ( $content['headers'] ?? [] );
        $rows    = (array) ( $content['rows']    ?? [] );
        $caption = esc_html( $content['caption'] ?? '' );
        $a       = $renderer->get_css_attrs( $node );

        $renderer->add_css( '.jalpi-el.jalpi-' . $id . '{display:block;overflow-x:auto;' . $renderer->styles_to_css( $styles ) . '}' );

        $thead = '';
        if ( $headers ) {
            $ths = '';
            foreach ( $headers as $h ) { $ths .= '<th class="jalpi-table__th" scope="col">' . esc_html( $h ) . '</th>'; }
            $thead = '<thead class="jalpi-table__head"><tr>' . $ths . '</tr></thead>';
        }

        $tbody = '';
        foreach ( $rows as $row ) {
            $tds = '';
            foreach ( (array) $row as $cell ) { $tds .= '<td class="jalpi-table__td">' . esc_html( $cell ) . '</td>'; }
            $tbody .= '<tr class="jalpi-table__row">' . $tds . '</tr>';
        }

        $cap = $caption ? '<caption class="jalpi-table__caption">' . $caption . '</caption>' : '';

        return '<div class="jalpi-el jalpi-table-wrap jalpi-' . esc_attr( $id ) . $a['extra_cls'] . '"' . $a['id_attr'] . '>'
             . '<table class="jalpi-table">' . $cap . $thead . '<tbody class="jalpi-table__body">' . $tbody . '</tbody></table>'
             . '</div>';
    }
}
