<?php
/**
 * Stats Dashboard Shortcode
 *
 * Registers shortcodes to display charts and statistics in posts/pages
 *
 * @package FleekDash\Shortcodes
 */

namespace FleekDash\Shortcodes;

/**
 * Class StatsDashboardShortcode
 *
 * @package FleekDash\Shortcodes
 */
class StatsDashboardShortcode
{
    private const DEFAULT_PERIOD = '30days';

    /**
     * Initialize the shortcode
     */
    public static function init()
    {
        add_shortcode('fleekdash_chart', [self::class, 'renderChart']);
        add_shortcode('fleekdash_dashboard', [self::class, 'renderDashboard']);

        // Enqueue necessary scripts
        \add_action('wp_enqueue_scripts', [self::class, 'enqueueScripts']);
    }

    /**
     * Enqueue the necessary scripts and styles
     */
    public static function enqueueScripts(): void
    {
        // Don't load any assets if plugin is temporarily disabled
        if (class_exists('\FleekDash\Core\ClassicModeHandler') && \FleekDash\Core\ClassicModeHandler::isTemporarilyDisabled()) {
            return;
        }

        // Only enqueue if the shortcode is present
        global $post;
        if (
            is_a($post, 'WP_Post') && (
                has_shortcode($post->post_content, 'fleekdash_chart') ||
                has_shortcode($post->post_content, 'fleekdash_dashboard')
            )
        ) {

            // Keep assets local to pages that include the shortcode.
            // Register and enqueue the React app
            \wp_register_script(
                'fleekdash-charts',
                plugins_url('dist/js/charts.js', FLEEKDASH_PLUGIN_FILE),
                ['wp-element', 'wp-api-fetch'],
                filemtime(FLEEKDASH_PLUGIN_DIR . 'dist/js/charts.js'),
                true,
            );

            \wp_enqueue_script('fleekdash-charts');

            // Add styles
            \wp_register_style(
                'fleekdash-charts-styles',
                plugins_url('dist/css/charts.css', FLEEKDASH_PLUGIN_FILE),
                [],
                filemtime(FLEEKDASH_PLUGIN_DIR . 'dist/css/charts.css'),
            );

            \wp_enqueue_style('fleekdash-charts-styles');
        }
    }

    /**
     * Render a single chart
     *
     * @param array $atts Shortcode attributes.
     * @return string The shortcode output.
     */
    public static function renderChart($atts): string
    {
        $atts = shortcode_atts([
            'type' => 'line',      // line, bar, pie, doughnut
            'metric' => 'posts',   // posts, comments, users
            'dimension' => 'date', // date, author, category, post, role
            'period' => self::DEFAULT_PERIOD,  // 7days, 30days, 90days, year, all
            'max_points' => 100,
            'height' => '400px',
            'post_type' => 'post', // post, page, ou qualquer custom post type
        ], $atts);

        // Sanitize attributes
        $chart_type = in_array($atts['type'], ['line', 'bar', 'pie', 'doughnut']) ? $atts['type'] : 'line';
        $metric = in_array($atts['metric'], ['posts', 'comments', 'users']) ? $atts['metric'] : 'posts';
        $dimension = in_array($atts['dimension'], ['date', 'author', 'category', 'post', 'role']) ? $atts['dimension'] : 'date';
        $period = in_array($atts['period'], ['7days', self::DEFAULT_PERIOD, '90days', 'year', 'all']) ? $atts['period'] : self::DEFAULT_PERIOD;
        $max_points = (int) $atts['max_points'];
        $height = \sanitize_text_field($atts['height']);
        $post_type = \sanitize_text_field($atts['post_type']);

        // Generate a unique ID for this chart
        $chart_id = 'fleekdash-chart-' . md5(serialize($atts) . rand());

        // Return the container which will be populated by React
        return sprintf(
            '<div id="%s" class="fleekdash-chart-wrapper" data-chart-type="%s" data-metric="%s" data-dimension="%s" data-period="%s" data-max-points="%d" data-post-type="%s" style="height: %s;"></div>',
            \esc_attr($chart_id),
            \esc_attr($chart_type),
            \esc_attr($metric),
            \esc_attr($dimension),
            \esc_attr($period),
            \esc_attr($max_points),
            \esc_attr($post_type),
            \esc_attr($height),
        );
    }

    /**
     * Render the complete dashboard
     *
     * @param array $atts Shortcode attributes.
     * @return string The shortcode output.
     */
    public static function renderDashboard($atts): string
    {
        $atts = shortcode_atts([
            'period' => self::DEFAULT_PERIOD, // 7days, 30days, 90days, year, all
            'post_type' => 'post', // post, page, ou qualquer custom post type
        ], $atts);

        // Sanitize attributes
        $period = in_array($atts['period'], ['7days', self::DEFAULT_PERIOD, '90days', 'year', 'all']) ? $atts['period'] : self::DEFAULT_PERIOD;
        $post_type = \sanitize_text_field($atts['post_type']);

        // Generate a unique ID for this dashboard
        $dashboard_id = 'fleekdash-dashboard-' . md5(serialize($atts) . rand());

        // Return the container which will be populated by React
        return sprintf(
            '<div id="%s" class="fleekdash-dashboard-wrapper" data-period="%s" data-post-type="%s"></div>',
            \esc_attr($dashboard_id),
            \esc_attr($period),
            \esc_attr($post_type),
        );
    }
}

// Initialize the shortcode
StatsDashboardShortcode::init();
