<?php
/**
 * Template: testimonials/page.php
 *
 * Storefront testimonials page.
 * Rendered via [titancart_testimonials] shortcode.
 *
 * Available variables:
 *   $testimonials  — Array of approved testimonial rows (id, author_name,
 *                    customer_first, customer_last, rating, title, body, created_at, ...)
 *   $total         — Total approved testimonials matching the filter
 *   $pages         — Number of pages
 *   $page          — Current page (1-based)
 *   $per_page      — Items per page
 *   $layout        — 'grid' (default) — 'marquee' reserved for future
 *
 * Override: copy to your-theme/titancart/testimonials/page.php
 *
 * @package TitanCart
 */
defined( 'ABSPATH' ) || exit;

$testimonials = $testimonials ?? [];
$total        = (int) ( $total ?? 0 );
$pages        = max( 1, (int) ( $pages ?? 1 ) );
$page         = max( 1, (int) ( $page ?? 1 ) );
$per_page     = max( 1, (int) ( $per_page ?? 12 ) );
$layout       = $layout ?? 'grid';

/**
 * Build a display label for the testimonial author.
 *
 * Prefers the linked customer record (first name + last initial) for privacy
 * over the raw author_name when both are present. Falls back to author_name,
 * then to "Anonymous" as a last resort.
 */
$tc_t_label = function ( array $row ): string {
    $first = trim( (string) ( $row['customer_first'] ?? '' ) );
    $last  = trim( (string) ( $row['customer_last']  ?? '' ) );
    if ( $first !== '' ) {
        $li = $last !== '' ? ' ' . mb_substr( $last, 0, 1 ) . '.' : '';
        return $first . $li;
    }
    $name = trim( (string) ( $row['author_name'] ?? '' ) );
    return $name !== '' ? $name : __( 'Anonymous', 'titancart-lite' );
};

/**
 * Build initials for the avatar circle (max 2 chars).
 */
$tc_t_initials = function ( string $label ): string {
    $parts = preg_split( '/\s+/', trim( $label ) );
    $out   = '';
    foreach ( (array) $parts as $part ) {
        $part = trim( $part, " .\t\n\r\0\x0B" );
        if ( $part === '' ) continue;
        $out .= mb_strtoupper( mb_substr( $part, 0, 1 ) );
        if ( mb_strlen( $out ) >= 2 ) break;
    }
    return $out !== '' ? $out : '?';
};

/**
 * HSL hash for stable per-author avatar tint.
 * Deterministic: same name → same color.
 */
$tc_t_avatar_color = function ( string $seed ): array {
    $hash = crc32( $seed );
    $hue  = $hash % 360;
    return [
        'bg'   => "hsl({$hue}, 60%, 92%)",
        'text' => "hsl({$hue}, 50%, 35%)",
    ];
};

$rest_base = esc_url( get_permalink() );
?>

<div class="tc-testimonials" data-layout="<?php echo esc_attr( $layout ); ?>">

    <header class="tc-testimonials__header">
        <h1 class="tc-testimonials__title"><?php echo esc_html__( 'Customer Testimonials', 'titancart-lite' ); ?></h1>
        <?php if ( $total > 0 ) : ?>
            <p class="tc-testimonials__sub">
                <?php
                printf(
                    esc_html(
                        /* translators: %d: number of testimonials */
                        _n( '%d happy customer.', '%d happy customers.', $total, 'titancart-lite' )
                    ),
                    (int) $total
                );
                ?>
            </p>
        <?php endif; ?>
    </header>

    <?php if ( empty( $testimonials ) ) : ?>

        <div class="tc-testimonials__empty">
            <p><?php echo esc_html__( 'No testimonials yet — check back soon.', 'titancart-lite' ); ?></p>
        </div>

    <?php else : ?>

        <div class="tc-testimonials__grid">

            <?php foreach ( $testimonials as $row ) :
                $label    = $tc_t_label( $row );
                $initials = $tc_t_initials( $label );
                $colors   = $tc_t_avatar_color( $label );
                $rating   = isset( $row['rating'] ) ? (int) $row['rating'] : 0;
                $title    = trim( (string) ( $row['title'] ?? '' ) );
                $body     = trim( (string) ( $row['body']  ?? '' ) );
                $created  = titancart_format_date( $row['created_at'] ?? '' );
            ?>
                <article class="tc-testimonials__card">

                    <header class="tc-testimonials__card-head">
                        <div class="tc-testimonials__avatar"
                             style="background:<?php echo esc_attr( $colors['bg'] ); ?>; color:<?php echo esc_attr( $colors['text'] ); ?>;"
                             aria-hidden="true">
                            <?php echo esc_html( $initials ); ?>
                        </div>
                        <div class="tc-testimonials__who">
                            <div class="tc-testimonials__name"><?php echo esc_html( $label ); ?></div>
                            <?php if ( $created ) : ?>
                                <div class="tc-testimonials__date tc-muted"><?php echo esc_html( $created ); ?></div>
                            <?php endif; ?>
                        </div>
                    </header>

                    <?php if ( $rating > 0 ) : ?>
                        <div class="tc-testimonials__rating">
                            <span class="tc-stars" aria-label="<?php
                                /* translators: %d: rating value 1-5 */
                                echo esc_attr( sprintf( __( '%d out of 5 stars', 'titancart-lite' ), $rating ) );
                            ?>">
                                <?php for ( $s = 1; $s <= 5; $s++ ) echo esc_html( $s <= $rating ? '★' : '☆' ); // WP.org R2 item 6: escaped at echo. ?>
                            </span>
                        </div>
                    <?php endif; ?>

                    <?php if ( $title !== '' ) : ?>
                        <h3 class="tc-testimonials__card-title"><?php echo esc_html( $title ); ?></h3>
                    <?php endif; ?>

                    <?php if ( $body !== '' ) : ?>
                        <p class="tc-testimonials__body"><?php echo wp_kses_post( $body ); ?></p>
                    <?php endif; ?>

                </article>

            <?php endforeach; ?>

        </div>

        <?php if ( $pages > 1 ) : ?>
            <nav class="tc-testimonials__pagination" aria-label="<?php echo esc_attr__( 'Testimonials pagination', 'titancart-lite' ); ?>">

                <?php if ( $page > 1 ) :
                    $prev_url = add_query_arg( 'testimonials_page', $page - 1, $rest_base );
                ?>
                    <a class="tc-btn tc-btn--sm tc-btn--outline" href="<?php echo esc_url( $prev_url ); ?>">
                        <?php echo esc_html__( '← Previous', 'titancart-lite' ); ?>
                    </a>
                <?php endif; ?>

                <span class="tc-testimonials__pageinfo tc-muted">
                    <?php
                    printf(
                        esc_html(
                            /* translators: 1: current page, 2: total pages */
                            __( 'Page %1$d of %2$d', 'titancart-lite' )
                        ),
                        (int) $page,
                        (int) $pages
                    );
                    ?>
                </span>

                <?php if ( $page < $pages ) :
                    $next_url = add_query_arg( 'testimonials_page', $page + 1, $rest_base );
                ?>
                    <a class="tc-btn tc-btn--sm tc-btn--outline" href="<?php echo esc_url( $next_url ); ?>">
                        <?php echo esc_html__( 'Next →', 'titancart-lite' ); ?>
                    </a>
                <?php endif; ?>

            </nav>
        <?php endif; ?>

    <?php endif; ?>

</div>
