<?php
/**
 * Comments & Discussions module bootstrapper.
 *
 * @package TitanCart\Modules\Comments
 */

namespace TitanCart\Modules\Comments;

use TitanCart\REST\Comments\CommentsController;
use TitanCart\Storefront\TemplateLoader;

defined( 'ABSPATH' ) || exit;

class CommentsModule {

    public static function init(): void {
        add_action( 'rest_api_init', function () {
            ( new CommentsController() )->register_routes();
        } );

        // Storefront shortcode for the testimonials page.
        add_shortcode( 'titancart_testimonials', [ self::class, 'render_testimonials_page' ] );
    }

    /**
     * Render the storefront testimonials page.
     *
     * Shortcode attrs:
     *   count       int   Number per page (default 12).
     *   min_rating  int   Filter to rating >= N (default 0 = no filter).
     *   layout      str   'grid' (default) — 'marquee' reserved for future.
     *
     * @param  array|string $atts  Shortcode attributes.
     * @return string
     */
    public static function render_testimonials_page( $atts = [] ): string {
        $atts = shortcode_atts( [
            'count'      => 12,
            'min_rating' => 0,
            'layout'     => 'grid',
        ], is_array( $atts ) ? $atts : [], 'titancart_testimonials' );

        $page    = max( 1, absint( wp_unslash( $_GET['testimonials_page'] ?? 1 ) ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- idempotent GET view-state (pagination), see reviewer notes §6.
        $payload = ( new CommentsManager() )->get_public_testimonials( [
            'count'      => (int) $atts['count'],
            'min_rating' => (int) $atts['min_rating'],
            'page'       => $page,
        ] );

        ob_start();
        TemplateLoader::get_template( 'testimonials/page.php', [
            'testimonials' => $payload['testimonials'],
            'total'        => $payload['total'],
            'pages'        => $payload['pages'],
            'page'         => $payload['page'],
            'per_page'     => $payload['per_page'],
            'layout'       => $atts['layout'],
        ] );
        return ob_get_clean();
    }
}
