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

add_shortcode( 'idsc_gallery', 'idsc_gallery_shortcode' );

function idsc_gallery_shortcode( $atts ) {
    IDSC_Assets::flag_css();

    $atts = shortcode_atts( array(
        'ids'           => '',
        'columns'       => '3',
        'gap'           => '10',
        'aspect_ratio'  => 'original',
        'border_radius' => '0',
        'link_to'       => 'none',
        'captions'      => 'no',
    ), $atts, 'idsc_gallery' );

    if ( empty( $atts['ids'] ) ) {
        return '';
    }

    $ids     = array_map( 'intval', explode( ',', $atts['ids'] ) );
    $columns = max( 1, min( 6, intval( $atts['columns'] ) ) );
    $gap     = intval( $atts['gap'] );
    $radius  = intval( $atts['border_radius'] );

    $aspect_class = '';
    if ( $atts['aspect_ratio'] !== 'original' ) {
        $aspect_class = ' idsc-gallery--' . sanitize_html_class( str_replace( ':', 'x', $atts['aspect_ratio'] ) );
    }

    $style = 'grid-template-columns:repeat(' . $columns . ',1fr);gap:' . $gap . 'px';

    $html = '<div class="idsc-gallery' . $aspect_class . '" style="' . esc_attr( $style ) . '">';

    foreach ( $ids as $id ) {
        $img = wp_get_attachment_image( $id, 'large', false, array( 'class' => 'idsc-gallery__img' ) );
        if ( ! $img ) {
            continue;
        }

        $item_style = $radius > 0 ? ' style="border-radius:' . $radius . 'px;overflow:hidden"' : '';

        $html .= '<figure class="idsc-gallery__item"' . $item_style . '>';

        if ( $atts['link_to'] === 'media' ) {
            $url   = wp_get_attachment_url( $id );
            $html .= '<a href="' . esc_url( $url ) . '">' . $img . '</a>';
        } elseif ( $atts['link_to'] === 'attachment' ) {
            $url   = get_attachment_link( $id );
            $html .= '<a href="' . esc_url( $url ) . '">' . $img . '</a>';
        } else {
            $html .= $img;
        }

        if ( $atts['captions'] === 'yes' ) {
            $caption = wp_get_attachment_caption( $id );
            if ( $caption ) {
                $html .= '<figcaption class="idsc-gallery__caption">' . esc_html( $caption ) . '</figcaption>';
            }
        }

        $html .= '</figure>';
    }

    $html .= '</div>';

    return $html;
}
