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

add_shortcode( 'idsc_accordion', 'idsc_accordion_shortcode' );
add_shortcode( 'idsc_accordion_item', 'idsc_accordion_item_shortcode' );

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

    $atts = shortcode_atts( array(
        'open_first' => 'no',
        'icon'       => 'chevron',
        'border'     => 'bordered',
    ), $atts, 'idsc_accordion' );

    $GLOBALS['idsc_accordion_ctx'] = array(
        'icon'       => $atts['icon'],
        'open_first' => $atts['open_first'],
        'index'      => 0,
    );

    $border_class = sanitize_html_class( 'idsc-accordion--' . $atts['border'] );
    $icon_class   = sanitize_html_class( 'idsc-accordion--icon-' . $atts['icon'] );
    $inner        = do_shortcode( $content );

    unset( $GLOBALS['idsc_accordion_ctx'] );

    return '<div class="idsc-accordion ' . $border_class . ' ' . $icon_class . '">' . $inner . '</div>';
}

function idsc_accordion_item_shortcode( $atts, $content = '' ) {
    $atts = shortcode_atts( array(
        'title' => '',
    ), $atts, 'idsc_accordion_item' );

    $ctx   = isset( $GLOBALS['idsc_accordion_ctx'] ) ? $GLOBALS['idsc_accordion_ctx'] : array();
    $index = isset( $ctx['index'] ) ? $ctx['index'] : 0;
    $open  = ( $index === 0 && isset( $ctx['open_first'] ) && $ctx['open_first'] === 'yes' ) ? ' open' : '';

    if ( isset( $GLOBALS['idsc_accordion_ctx'] ) ) {
        $GLOBALS['idsc_accordion_ctx']['index']++;
    }

    $icon_html = '';
    $icon_type = isset( $ctx['icon'] ) ? $ctx['icon'] : 'chevron';
    if ( $icon_type === 'chevron' ) {
        $icon_html = '<span class="idsc-accordion__icon"><svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="6,8 10,12 14,8"/></svg></span>';
    } elseif ( $icon_type === 'plus-minus' ) {
        $icon_html = '<span class="idsc-accordion__icon idsc-accordion__icon--pm"><svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><line x1="4" y1="10" x2="16" y2="10"/><line class="idsc-accordion__plus-v" x1="10" y1="4" x2="10" y2="16"/></svg></span>';
    }

    $html  = '<details class="idsc-accordion__item"' . $open . '>';
    $html .= '<summary class="idsc-accordion__header">';
    $html .= '<span class="idsc-accordion__title">' . esc_html( $atts['title'] ) . '</span>';
    $html .= $icon_html;
    $html .= '</summary>';
    $html .= '<div class="idsc-accordion__body">' . wp_kses_post( $content ) . '</div>';
    $html .= '</details>';

    return $html;
}
