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

add_shortcode( 'idsc_testimonial', 'idsc_testimonial_shortcode' );

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

    $atts = shortcode_atts( array(
        'author' => '',
        'role'   => '',
        'photo'  => '',
        'rating' => '0',
        'layout' => 'standard',
    ), $atts, 'idsc_testimonial' );

    $layout = sanitize_html_class( $atts['layout'] );
    $class  = 'idsc-testimonial idsc-testimonial--' . $layout;

    $html = '<blockquote class="' . esc_attr( $class ) . '">';

    // Stars
    $rating = intval( $atts['rating'] );
    if ( $rating > 0 ) {
        $html .= '<div class="idsc-testimonial__stars">';
        for ( $i = 0; $i < 5; $i++ ) {
            $filled = $i < $rating ? ' idsc-star--filled' : '';
            $html .= '<svg class="idsc-testimonial__star' . $filled . '" viewBox="0 0 20 20"><polygon points="10,1.5 12.47,7.27 18.76,7.85 13.97,12.05 15.35,18.2 10,15.08 4.65,18.2 6.03,12.05 1.24,7.85 7.53,7.27"/></svg>';
        }
        $html .= '</div>';
    }

    $html .= '<div class="idsc-testimonial__content">' . wp_kses_post( $content ) . '</div>';

    // Footer with author info
    if ( ! empty( $atts['author'] ) || ! empty( $atts['photo'] ) ) {
        $html .= '<footer class="idsc-testimonial__footer">';

        if ( ! empty( $atts['photo'] ) ) {
            $photo_id = intval( $atts['photo'] );
            $img      = wp_get_attachment_image( $photo_id, array( 60, 60 ), false, array( 'class' => 'idsc-testimonial__photo' ) );
            if ( $img ) {
                $html .= $img;
            }
        }

        if ( ! empty( $atts['author'] ) ) {
            $html .= '<div class="idsc-testimonial__meta">';
            $html .= '<cite class="idsc-testimonial__author">' . esc_html( $atts['author'] ) . '</cite>';
            if ( ! empty( $atts['role'] ) ) {
                $html .= '<span class="idsc-testimonial__role">' . esc_html( $atts['role'] ) . '</span>';
            }
            $html .= '</div>';
        }

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

    $html .= '</blockquote>';

    return $html;
}
