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

add_shortcode( 'idsc_tabs', 'idsc_tabs_shortcode' );
add_shortcode( 'idsc_tab', 'idsc_tab_shortcode' );

function idsc_tabs_shortcode( $atts, $content = '' ) {
    IDSC_Assets::flag_css();
    IDSC_Assets::flag_js();

    static $instance = 0;
    $instance++;

    $atts = shortcode_atts( array(
        'layout'    => 'horizontal',
        'alignment' => 'left',
        'active'    => '1',
    ), $atts, 'idsc_tabs' );

    $GLOBALS['idsc_tabs_ctx'] = array(
        'instance' => $instance,
        'index'    => 0,
        'active'   => max( 1, intval( $atts['active'] ) ),
        'tabs'     => array(),
        'panels'   => array(),
    );

    do_shortcode( $content );

    $ctx = $GLOBALS['idsc_tabs_ctx'];
    unset( $GLOBALS['idsc_tabs_ctx'] );

    $layout_class = sanitize_html_class( 'idsc-tabs--' . $atts['layout'] );
    $align_class  = sanitize_html_class( 'idsc-tabs--align-' . $atts['alignment'] );
    $id           = 'idsc-tabs-' . $instance;

    $html = '<div class="idsc-tabs ' . $layout_class . ' ' . $align_class . '" id="' . esc_attr( $id ) . '" data-idsc-tabs>';

    // Tab buttons
    $html .= '<div class="idsc-tabs__nav" role="tablist">';
    foreach ( $ctx['tabs'] as $i => $tab ) {
        $active  = ( $i + 1 ) === $ctx['active'] ? ' idsc-tabs__btn--active' : '';
        $sel     = ( $i + 1 ) === $ctx['active'] ? 'true' : 'false';
        $tab_id  = $id . '-tab-' . ( $i + 1 );
        $panel_id = $id . '-panel-' . ( $i + 1 );
        $html .= '<button type="button" class="idsc-tabs__btn' . $active . '" role="tab" aria-selected="' . $sel . '" aria-controls="' . esc_attr( $panel_id ) . '" id="' . esc_attr( $tab_id ) . '">' . esc_html( $tab ) . '</button>';
    }
    $html .= '</div>';

    // Tab panels
    foreach ( $ctx['panels'] as $i => $panel_content ) {
        $hidden   = ( $i + 1 ) === $ctx['active'] ? '' : ' hidden';
        $tab_id   = $id . '-tab-' . ( $i + 1 );
        $panel_id = $id . '-panel-' . ( $i + 1 );
        $html .= '<div class="idsc-tabs__panel" role="tabpanel" id="' . esc_attr( $panel_id ) . '" aria-labelledby="' . esc_attr( $tab_id ) . '"' . $hidden . '>' . wp_kses_post( $panel_content ) . '</div>';
    }

    $html .= '</div>';

    return $html;
}

function idsc_tab_shortcode( $atts, $content = '' ) {
    if ( ! isset( $GLOBALS['idsc_tabs_ctx'] ) ) {
        return '';
    }

    $atts = shortcode_atts( array(
        'title' => 'Tab',
    ), $atts, 'idsc_tab' );

    $GLOBALS['idsc_tabs_ctx']['tabs'][]   = $atts['title'];
    $GLOBALS['idsc_tabs_ctx']['panels'][] = $content;
    $GLOBALS['idsc_tabs_ctx']['index']++;

    return '';
}
