<?php

namespace FleekDash\Controllers\Analytics;

use FleekDash\Services\ResponseService;
use FleekDash\Controllers\Analytics\Traits\HasDateRangeHelpers;
use WP_REST_Request;

/**
 * Growth Stats Controller (V2.2)
 *
 * Analytics endpoints for site growth with chart data, summaries, and period comparisons.
 * Migrated from includes/API/real/Growth/SiteController.php
 *
 * @package FleekDash\Controllers\Analytics
 * @since 2.2.0
 */
class GrowthStatsController
{
    use HasDateRangeHelpers;
    /**
     * Get site growth stats with date range filtering
     *
     * @param WP_REST_Request $request
     * @return \WP_REST_Response
     */
    public function index($request)
    {
        $range_info = $this->get_date_range_info($request);
        $data = $this->get_real_site_growth_data($range_info);

        // Return results in consistent format
        return new \WP_REST_Response([
            'success' => true,
            'results' => $data,
            'metadata' => [
                'date_range' => $range_info,
                'endpoint' => 'site_growth_full'
            ]
        ]);
    }

    /**
     * Get chart data (time series)
     *
     * @param WP_REST_Request $request
     * @return \WP_REST_Response
     */
    public function chart($request)
    {
        $range_info = $this->get_date_range_info($request);
        $data = $this->get_real_site_growth_chart($range_info);

        // Return results in consistent format (matching ContentStatsController)
        return new \WP_REST_Response([
            'success' => true,
            'results' => $data,
            'metadata' => [
                'date_range' => $range_info,
                'endpoint' => 'site_growth_chart'
            ]
        ]);
    }

    /**
     * Get summary KPIs
     *
     * @param WP_REST_Request $request
     * @return \WP_REST_Response
     */
    public function summary($request)
    {
        $range_info = $this->get_date_range_info($request);
        $summary = $this->get_real_site_growth_summary($range_info);

        return new \WP_REST_Response([
            'success' => true,
            'results' => $summary,
            'metadata' => [
                'date_range' => $range_info,
                'endpoint' => 'site_growth_summary'
            ]
        ]);
    }

    /**
     * Get period comparison data
     *
     * @param WP_REST_Request $request
     * @return \WP_REST_Response
     */
    public function comparison($request)
    {
        $range_info = $this->get_date_range_info($request);
        $comparison_type = $request->get_param('comparison_type') ?: 'previous_period';

        $comparison_data = $this->get_real_site_growth_comparison($range_info, $comparison_type);

        return new \WP_REST_Response([
            'success' => true,
            'results' => $comparison_data,
            'metadata' => [
                'date_range' => $range_info,
                'comparison_type' => $comparison_type,
                'endpoint' => 'site_growth_comparison'
            ]
        ]);
    }

    private function get_real_site_growth_data($range_info)
    {
        global $wpdb;

        // Get all public post types except 'page' and 'profile'
        $excluded_types = ['page', 'profile'];
        $post_types = \get_post_types(['public' => true], 'names');
        $allowed_post_types = array_values(array_diff($post_types, $excluded_types));

        // Create placeholders for the IN clause
        $placeholders = implode(',', array_fill(0, count($allowed_post_types), '%s'));

        // Build date condition
        $date_condition = '';
        if ($range_info['start_date'] && $range_info['end_date']) {
            $date_condition = $wpdb->prepare(
                "AND DATE(activity_date) BETWEEN %s AND %s",
                $range_info['start_date'],
                $range_info['end_date'],
            );
        } else {
            $date_condition = $wpdb->prepare(
                "AND DATE(activity_date) >= DATE_SUB(NOW(), INTERVAL %d DAY)",
                $range_info['days'],
            );
        }

        // Use prepared statement for the main query
        $query = "
            SELECT
                DATE(activity_date) as date,
                SUM(comments_count) as comments,
                SUM(posts_count) as posts,
                SUM(users_count) as users,
                SUM(comments_count + posts_count + users_count) as total_activity
            FROM (
                -- Comments data
                SELECT
                    comment_date as activity_date,
                    COUNT(*) as comments_count,
                    0 as posts_count,
                    0 as users_count
                FROM {$wpdb->comments}
                WHERE comment_approved = '1'
                GROUP BY DATE(comment_date)

                UNION ALL

                -- Posts data
                SELECT
                    post_date as activity_date,
                    0 as comments_count,
                    COUNT(*) as posts_count,
                    0 as users_count
                FROM {$wpdb->posts}
                WHERE post_status = 'publish' AND post_type IN ({$placeholders})
                GROUP BY DATE(post_date)

                UNION ALL

                -- Users data
                SELECT
                    user_registered as activity_date,
                    0 as comments_count,
                    0 as posts_count,
                    COUNT(*) as users_count
                FROM {$wpdb->users}
                GROUP BY DATE(user_registered)
            ) combined_data
            WHERE 1=1 {$date_condition}
            GROUP BY DATE(activity_date)
            ORDER BY activity_date DESC
        ";

        $results = $wpdb->prepare($query, $allowed_post_types);
        $results = $wpdb->get_results($results, ARRAY_A);
        $formatted_data = [];

        foreach ($results as $row) {
            $formatted_data[] = [
                'date' => $row['date'],
                'comments' => (int) $row['comments'],
                'posts' => (int) $row['posts'],
                'users' => (int) $row['users'],
                'total_activity' => (int) $row['total_activity'],
                'growth_rate' => $this->calculate_real_growth_rate($row['date'], $range_info)
            ];
        }

        return $formatted_data;
    }

    private function get_real_site_growth_chart($range_info)
    {
        global $wpdb;

        // Get all public post types except 'page' and 'profile'
        // This shows all published content across the site
        $excluded_types = ['page', 'profile'];
        $post_types = \get_post_types(['public' => true], 'names');
        $allowed_post_types = array_values(array_diff($post_types, $excluded_types));

        // Create placeholders for the IN clause
        $placeholders = implode(',', array_fill(0, count($allowed_post_types), '%s'));

        // Build date condition
        $date_condition = '';
        if ($range_info['start_date'] && $range_info['end_date']) {
            $date_condition = $wpdb->prepare(
                "AND DATE(activity_date) BETWEEN %s AND %s",
                $range_info['start_date'],
                $range_info['end_date'],
            );
        } else {
            $date_condition = $wpdb->prepare(
                "AND DATE(activity_date) >= DATE_SUB(NOW(), INTERVAL %d DAY)",
                $range_info['days'],
            );
        }

        // Build proper date conditions for each table
        $comments_date_condition = '';
        $posts_date_condition = '';
        $users_date_condition = '';

        if ($range_info['start_date'] && $range_info['end_date']) {
            $comments_date_condition = $wpdb->prepare(
                "AND DATE(comment_date) BETWEEN %s AND %s",
                $range_info['start_date'],
                $range_info['end_date'],
            );
            $posts_date_condition = $wpdb->prepare(
                "AND DATE(post_date) BETWEEN %s AND %s",
                $range_info['start_date'],
                $range_info['end_date'],
            );
            $users_date_condition = $wpdb->prepare(
                "AND DATE(user_registered) BETWEEN %s AND %s",
                $range_info['start_date'],
                $range_info['end_date'],
            );
        } else {
            $comments_date_condition = $wpdb->prepare(
                "AND DATE(comment_date) >= DATE_SUB(NOW(), INTERVAL %d DAY)",
                $range_info['days'],
            );
            $posts_date_condition = $wpdb->prepare(
                "AND DATE(post_date) >= DATE_SUB(NOW(), INTERVAL %d DAY)",
                $range_info['days'],
            );
            $users_date_condition = $wpdb->prepare(
                "AND DATE(user_registered) >= DATE_SUB(NOW(), INTERVAL %d DAY)",
                $range_info['days'],
            );
        }

        // Get daily data for each metric with correct date columns
        $comments_query = "
            SELECT
                DATE(comment_date) as date,
                COUNT(*) as value
            FROM {$wpdb->comments}
            WHERE comment_approved = '1' {$comments_date_condition}
            GROUP BY DATE(comment_date)
            ORDER BY date ASC
        ";

        $posts_query = "
            SELECT
                DATE(post_date) as date,
                COUNT(*) as value
            FROM {$wpdb->posts}
            WHERE post_status = 'publish' AND post_type IN ({$placeholders}) {$posts_date_condition}
            GROUP BY DATE(post_date)
            ORDER BY date ASC
        ";

        $users_query = "
            SELECT
                DATE(user_registered) as date,
                COUNT(*) as value
            FROM {$wpdb->users}
            WHERE 1=1 {$users_date_condition}
            GROUP BY DATE(user_registered)
            ORDER BY date ASC
        ";

        $comments_data = $wpdb->get_results($comments_query, ARRAY_A);
        $posts_query_prepared = $wpdb->prepare($posts_query, $allowed_post_types);
        $posts_data = $wpdb->get_results($posts_query_prepared, ARRAY_A);
        $users_data = $wpdb->get_results($users_query, ARRAY_A);



        // Fill missing dates with zeros
        $all_dates = $this->get_date_range_array($range_info);
        $comments_series = $this->fill_missing_dates($comments_data, $all_dates);
        $posts_series = $this->fill_missing_dates($posts_data, $all_dates);
        $users_series = $this->fill_missing_dates($users_data, $all_dates);

        return [
            'series' => [
                [
                    'name' => 'Comments',
                    'data' => $comments_series,
                    'color' => '#3858e9',
                    'type' => 'line'
                ],
                [
                    'name' => 'Published Posts',
                    'data' => $posts_series,
                    'color' => '#00a32a',
                    'type' => 'line'
                ],
                [
                    'name' => 'Users',
                    'data' => $users_series,
                    'color' => '#F59E0B',
                    'type' => 'line'
                ]
            ],
            'total_growth' => $this->calculate_real_total_growth($range_info),
            'growth_trend' => $this->determine_growth_trend($comments_series, $posts_series, $users_series)
        ];
    }

    private function get_real_site_growth_summary($range_info)
    {
        global $wpdb;

        // Get all public post types except 'page' and 'profile'
        $excluded_types = ['page', 'profile'];
        $post_types = \get_post_types(['public' => true], 'names');
        $allowed_post_types = array_values(array_diff($post_types, $excluded_types));

        // Create placeholders for the IN clause
        $placeholders = implode(',', array_fill(0, count($allowed_post_types), '%s'));

        // Build date conditions for summary
        $comments_summary_condition = '';
        $posts_summary_condition = '';
        $users_summary_condition = '';

        if ($range_info['start_date'] && $range_info['end_date']) {
            $comments_summary_condition = $wpdb->prepare(
                "AND DATE(comment_date) BETWEEN %s AND %s",
                $range_info['start_date'],
                $range_info['end_date'],
            );
            $posts_summary_condition = $wpdb->prepare(
                "AND DATE(post_date) BETWEEN %s AND %s",
                $range_info['start_date'],
                $range_info['end_date'],
            );
            $users_summary_condition = $wpdb->prepare(
                "AND DATE(user_registered) BETWEEN %s AND %s",
                $range_info['start_date'],
                $range_info['end_date'],
            );
        } else {
            $comments_summary_condition = $wpdb->prepare(
                "AND DATE(comment_date) >= DATE_SUB(NOW(), INTERVAL %d DAY)",
                $range_info['days'],
            );
            $posts_summary_condition = $wpdb->prepare(
                "AND DATE(post_date) >= DATE_SUB(NOW(), INTERVAL %d DAY)",
                $range_info['days'],
            );
            $users_summary_condition = $wpdb->prepare(
                "AND DATE(user_registered) >= DATE_SUB(NOW(), INTERVAL %d DAY)",
                $range_info['days'],
            );
        }

        // Get totals for each metric with correct date columns
        $comments_total = $wpdb->get_var("
            SELECT COUNT(*) FROM {$wpdb->comments}
            WHERE comment_approved = '1' {$comments_summary_condition}
        ") ?: 0;

        $posts_query = "
            SELECT COUNT(*) FROM {$wpdb->posts}
            WHERE post_status = 'publish' AND post_type IN ({$placeholders}) {$posts_summary_condition}
        ";
        $posts_total = $wpdb->prepare($posts_query, $allowed_post_types);
        $posts_total = $wpdb->get_var($posts_total) ?: 0;

        $users_total = $wpdb->get_var("
            SELECT COUNT(*) FROM {$wpdb->users}
            WHERE 1=1 {$users_summary_condition}
        ") ?: 0;

        // Get growth compared to previous period
        $previous_comments = $this->get_previous_period_count('comments', $range_info);
        $previous_posts = $this->get_previous_period_count('posts', $range_info);
        $previous_users = $this->get_previous_period_count('users', $range_info);

        $comments_growth = $comments_total - $previous_comments;
        $posts_growth = $posts_total - $previous_posts;
        $users_growth = $users_total - $previous_users;

        $total_activity = $comments_total + $posts_total + $users_total;
        $overall_growth = round((($comments_growth + $posts_growth + $users_growth) / 3), 1);

        // Get insights
        $fastest_growing = $this->determine_fastest_growing($comments_growth, $posts_growth, $users_growth);
        $most_active_day = $this->get_most_active_day($range_info);
        $engagement_rate = $posts_total > 0 ? round(($comments_total / $posts_total) * 100, 1) : 0;

        return [
            'overview' => [
                'total_activity' => $total_activity,
                'overall_growth' => $overall_growth,
                'growth_trend' => $overall_growth > 0 ? 'up' : ($overall_growth < 0 ? 'down' : 'stable'),
                'period_days' => $range_info['days']
            ],
            'metrics' => [
                'comments' => [
                    'total' => (int) $comments_total,
                    'growth' => $comments_growth,
                    'growth_percentage' => $previous_comments > 0 ? round(($comments_growth / $previous_comments) * 100, 1) : 0,
                    'trend' => $comments_growth > 0 ? 'up' : ($comments_growth < 0 ? 'down' : 'stable')
                ],
                'posts' => [
                    'total' => (int) $posts_total,
                    'growth' => $posts_growth,
                    'growth_percentage' => $previous_posts > 0 ? round(($posts_growth / $previous_posts) * 100, 1) : 0,
                    'trend' => $posts_growth > 0 ? 'up' : ($posts_growth < 0 ? 'down' : 'stable')
                ],
                'users' => [
                    'total' => (int) $users_total,
                    'growth' => $users_growth,
                    'growth_percentage' => $previous_users > 0 ? round(($users_growth / $previous_users) * 100, 1) : 0,
                    'trend' => $users_growth > 0 ? 'up' : ($users_growth < 0 ? 'down' : 'stable')
                ]
            ],
            'insights' => [
                'fastest_growing' => $fastest_growing,
                'most_active_day' => $most_active_day,
                'growth_momentum' => $overall_growth > 0 ? 'increasing' : 'decreasing',
                'engagement_rate' => $engagement_rate
            ]
        ];
    }

    private function get_real_site_growth_comparison($range_info, $comparison_type)
    {
        $comparison_dates = $this->get_comparison_dates($range_info, $comparison_type);

        $current_data = $this->get_real_site_growth_chart($range_info);
        $comparison_data = $this->get_real_site_growth_chart($comparison_dates);

        $comparison_metrics = $this->calculate_real_comparison_metrics($current_data, $comparison_data);

        return [
            'current_period' => [
                'data' => $current_data,
                'summary' => $this->get_real_site_growth_summary($range_info)
            ],
            'comparison_period' => [
                'data' => $comparison_data,
                'summary' => $this->get_real_site_growth_summary($comparison_dates)
            ],
            'comparison_metrics' => $comparison_metrics,
            'comparison_type' => $comparison_type,
            'period_dates' => [
                'current' => [
                    'start_date' => $range_info['start_date'] ?: date('Y-m-d', strtotime("-{$range_info['days']} days")),
                    'end_date' => $range_info['end_date'] ?: date('Y-m-d')
                ],
                'comparison' => [
                    'start_date' => $comparison_dates['start_date'],
                    'end_date' => $comparison_dates['end_date']
                ]
            ]
        ];
    }

    private function calculate_real_growth_rate($date, $range_info)
    {
        // Calculate growth rate based on historical data
        global $wpdb;

        $current_date = strtotime($date);
        $previous_date = date('Y-m-d', strtotime('-1 day', $current_date));

        $current_total = $wpdb->get_var($wpdb->prepare("
            SELECT COUNT(*) FROM (
                SELECT comment_date FROM {$wpdb->comments} WHERE DATE(comment_date) = %s AND comment_approved = '1'
                UNION ALL
                SELECT post_date FROM {$wpdb->posts} WHERE DATE(post_date) = %s AND post_status = 'publish'
                UNION ALL
                SELECT user_registered FROM {$wpdb->users} WHERE DATE(user_registered) = %s
            ) activity
        ", $date, $date, $date)) ?: 0;

        $previous_total = $wpdb->get_var($wpdb->prepare("
            SELECT COUNT(*) FROM (
                SELECT comment_date FROM {$wpdb->comments} WHERE DATE(comment_date) = %s AND comment_approved = '1'
                UNION ALL
                SELECT post_date FROM {$wpdb->posts} WHERE DATE(post_date) = %s AND post_status = 'publish'
                UNION ALL
                SELECT user_registered FROM {$wpdb->users} WHERE DATE(user_registered) = %s
            ) activity
        ", $previous_date, $previous_date, $previous_date)) ?: 0;

        if ($previous_total > 0) {
            return round((($current_total - $previous_total) / $previous_total) * 100, 2);
        }

        return 0;
    }

    private function calculate_real_total_growth($range_info)
    {
        global $wpdb;

        // Get current period total
        $current_total = $wpdb->get_var("
            SELECT COUNT(*) FROM (
                SELECT comment_date FROM {$wpdb->comments}
                WHERE comment_approved = '1'
                AND DATE(comment_date) >= DATE_SUB(NOW(), INTERVAL {$range_info['days']} DAY)
                UNION ALL
                SELECT post_date FROM {$wpdb->posts}
                WHERE post_status = 'publish'
                AND DATE(post_date) >= DATE_SUB(NOW(), INTERVAL {$range_info['days']} DAY)
                UNION ALL
                SELECT user_registered FROM {$wpdb->users}
                WHERE DATE(user_registered) >= DATE_SUB(NOW(), INTERVAL {$range_info['days']} DAY)
            ) activity
        ") ?: 0;

        // Get previous period total
        $previous_total = $wpdb->get_var("
            SELECT COUNT(*) FROM (
                SELECT comment_date FROM {$wpdb->comments}
                WHERE comment_approved = '1'
                AND DATE(comment_date) BETWEEN DATE_SUB(NOW(), INTERVAL " . ($range_info['days'] * 2) . " DAY)
                AND DATE_SUB(NOW(), INTERVAL {$range_info['days']} DAY)
                UNION ALL
                SELECT post_date FROM {$wpdb->posts}
                WHERE post_status = 'publish'
                AND DATE(post_date) BETWEEN DATE_SUB(NOW(), INTERVAL " . ($range_info['days'] * 2) . " DAY)
                AND DATE_SUB(NOW(), INTERVAL {$range_info['days']} DAY)
                UNION ALL
                SELECT user_registered FROM {$wpdb->users}
                WHERE DATE(user_registered) BETWEEN DATE_SUB(NOW(), INTERVAL " . ($range_info['days'] * 2) . " DAY)
                AND DATE_SUB(NOW(), INTERVAL {$range_info['days']} DAY)
            ) activity
        ") ?: 0;

        if ($previous_total > 0) {
            return round((($current_total - $previous_total) / $previous_total) * 100, 1);
        }

        return 0;
    }

    private function determine_growth_trend($comments_series, $posts_series, $users_series)
    {
        // Calculate trend based on recent data points
        $recent_comments = array_slice($comments_series, -7); // Last 7 days
        $recent_posts = array_slice($posts_series, -7);
        $recent_users = array_slice($users_series, -7);

        $comments_trend = $this->calculate_series_trend($recent_comments);
        $posts_trend = $this->calculate_series_trend($recent_posts);
        $users_trend = $this->calculate_series_trend($recent_users);

        // Overall trend
        $positive_trends = 0;
        if ($comments_trend > 0)
            $positive_trends++;
        if ($posts_trend > 0)
            $positive_trends++;
        if ($users_trend > 0)
            $positive_trends++;

        if ($positive_trends >= 2) {
            return 'up';
        } elseif ($positive_trends <= 1) {
            return 'down';
        } else {
            return 'stable';
        }
    }

    private function calculate_series_trend($series)
    {
        if (count($series) < 2)
            return 0;

        $values = array_column($series, 'value');
        $first_half = array_slice($values, 0, floor(count($values) / 2));
        $second_half = array_slice($values, floor(count($values) / 2));

        $first_avg = array_sum($first_half) / count($first_half);
        $second_avg = array_sum($second_half) / count($second_half);

        return $second_avg - $first_avg;
    }

    private function get_previous_period_count($type, $range_info)
    {
        global $wpdb;

        $days = $range_info['days'];
        $table = $type === 'comments' ? $wpdb->comments : ($type === 'posts' ? $wpdb->posts : $wpdb->users);
        $date_column = $type === 'comments' ? 'comment_date' : ($type === 'posts' ? 'post_date' : 'user_registered');

        if ($type === 'posts') {
            // Get all public post types except 'page' and 'profile'
            $excluded_types = ['page', 'profile'];
            $post_types = \get_post_types(['public' => true], 'names');
            $allowed_post_types = array_values(array_diff($post_types, $excluded_types));

            // Create placeholders for the IN clause
            $placeholders = implode(',', array_fill(0, count($allowed_post_types), '%s'));

            $where_condition = "AND post_status = 'publish' AND post_type IN ({$placeholders})";

            $query = "
                SELECT COUNT(*) FROM {$table}
                WHERE DATE({$date_column}) BETWEEN DATE_SUB(NOW(), INTERVAL " . ($days * 2) . " DAY)
                AND DATE_SUB(NOW(), INTERVAL {$days} DAY)
                {$where_condition}
            ";

            $prepared_query = $wpdb->prepare($query, $allowed_post_types);
            return $wpdb->get_var($prepared_query) ?: 0;
        } else {
            $where_condition = $type === 'comments' ? "AND comment_approved = '1'" : "";

            return $wpdb->get_var("
                SELECT COUNT(*) FROM {$table}
                WHERE DATE({$date_column}) BETWEEN DATE_SUB(NOW(), INTERVAL " . ($days * 2) . " DAY)
                AND DATE_SUB(NOW(), INTERVAL {$days} DAY)
                {$where_condition}
            ") ?: 0;
        }
    }

    private function determine_fastest_growing($comments_growth, $posts_growth, $users_growth)
    {
        $growth_rates = [
            'comments' => $comments_growth,
            'posts' => $posts_growth,
            'users' => $users_growth
        ];

        return array_search(max($growth_rates), $growth_rates);
    }

    private function get_most_active_day($range_info)
    {
        global $wpdb;

        // Get all public post types except 'page' and 'profile'
        $excluded_types = ['page', 'profile'];
        $post_types = \get_post_types(['public' => true], 'names');
        $allowed_post_types = array_values(array_diff($post_types, $excluded_types));

        // Create placeholders for the IN clause
        $placeholders = implode(',', array_fill(0, count($allowed_post_types), '%s'));

        $query = "
            SELECT DATE(activity_date) as most_active_date, COUNT(*) as activity_count
            FROM (
                SELECT comment_date as activity_date FROM {$wpdb->comments} WHERE comment_approved = '1'
                UNION ALL
                SELECT post_date as activity_date FROM {$wpdb->posts} WHERE post_status = 'publish' AND post_type IN ({$placeholders})
                UNION ALL
                SELECT user_registered as activity_date FROM {$wpdb->users}
            ) activity
            WHERE DATE(activity_date) >= DATE_SUB(NOW(), INTERVAL {$range_info['days']} DAY)
            GROUP BY DATE(activity_date)
            ORDER BY activity_count DESC
            LIMIT 1
        ";

        $result = $wpdb->prepare($query, $allowed_post_types);
        $result = $wpdb->get_row($result);

        return $result ? $result->most_active_date : date('Y-m-d', strtotime('-1 day'));
    }

    private function get_date_range_array($range_info)
    {
        $dates = [];

        // Calculate date range correctly to match frontend expectations
        // When days=30, we want exactly 30 days, not 31 (including today)
        if ($range_info['start_date'] && $range_info['end_date']) {
            // Use provided dates as-is
            $start_date = $range_info['start_date'];
            $end_date = $range_info['end_date'];
        } else {
            // Calculate: end_date is today, start_date is (days-1) days ago
            // This ensures exactly 'days' number of dates
            $end_date = date('Y-m-d');
            $days = $range_info['days'] ?? 30;
            // Subtract (days-1) to get exactly 'days' dates including today
            $start_date = date('Y-m-d', strtotime("-" . ($days - 1) . " days"));
        }

        $current = strtotime($start_date);
        $end = strtotime($end_date);

        while ($current <= $end) {
            $dates[] = date('Y-m-d', $current);
            $current = strtotime('+1 day', $current);
        }

        return $dates;
    }

    private function fill_missing_dates($data, $all_dates)
    {
        $filled_data = [];
        $data_by_date = array_column($data, 'value', 'date');

        foreach ($all_dates as $date) {
            $filled_data[] = [
                'date' => $date,
                'value' => isset($data_by_date[$date]) ? (int) $data_by_date[$date] : 0
            ];
        }

        return $filled_data;
    }

    private function calculate_real_comparison_metrics($current_data, $comparison_data)
    {
        $current_comments = array_sum(array_column($current_data['series'][0]['data'], 'value'));
        $current_posts = array_sum(array_column($current_data['series'][1]['data'], 'value'));
        $current_users = array_sum(array_column($current_data['series'][2]['data'], 'value'));

        $comparison_comments = array_sum(array_column($comparison_data['series'][0]['data'], 'value'));
        $comparison_posts = array_sum(array_column($comparison_data['series'][1]['data'], 'value'));
        $comparison_users = array_sum(array_column($comparison_data['series'][2]['data'], 'value'));

        $comments_change = $current_comments - $comparison_comments;
        $posts_change = $current_posts - $comparison_posts;
        $users_change = $current_users - $comparison_users;

        $comments_change_percentage = $comparison_comments > 0 ? ($comments_change / $comparison_comments) * 100 : 0;
        $posts_change_percentage = $comparison_posts > 0 ? ($posts_change / $comparison_posts) * 100 : 0;
        $users_change_percentage = $comparison_users > 0 ? ($users_change / $comparison_users) * 100 : 0;

        return [
            'comments' => [
                'current' => $current_comments,
                'previous' => $comparison_comments,
                'change' => $comments_change,
                'change_percentage' => round($comments_change_percentage, 2),
                'trend' => $comments_change > 0 ? 'up' : ($comments_change < 0 ? 'down' : 'stable')
            ],
            'posts' => [
                'current' => $current_posts,
                'previous' => $comparison_posts,
                'change' => $posts_change,
                'change_percentage' => round($posts_change_percentage, 2),
                'trend' => $posts_change > 0 ? 'up' : ($posts_change < 0 ? 'down' : 'stable')
            ],
            'users' => [
                'current' => $current_users,
                'previous' => $comparison_users,
                'change' => $users_change,
                'change_percentage' => round($users_change_percentage, 2),
                'trend' => $users_change > 0 ? 'up' : ($users_change < 0 ? 'down' : 'stable')
            ],
            'overall' => [
                'current_total' => $current_comments + $current_posts + $current_users,
                'previous_total' => $comparison_comments + $comparison_posts + $comparison_users,
                'total_change' => $comments_change + $posts_change + $users_change,
                'total_change_percentage' => round((($comments_change + $posts_change + $users_change) / max($comparison_comments + $comparison_posts + $comparison_users, 1)) * 100, 2),
                'trend' => ($comments_change + $posts_change + $users_change) > 0 ? 'up' : 'down'
            ]
        ];
    }
}
