<?php

namespace FleekDash\Controllers\Analytics;

use FleekDash\Utils\AvatarHelper;

/**
 * User Analytics
 *
 * Handles user-specific analytics data
 *
 * @package FleekDash\Controllers\Analytics
 */
class UserAnalytics
{
    /**
     * Get recent users data
     *
     * @param int $limit Number of users to fetch
     * @return array Recent users data
     */
    public function getRecentUsersData($limit = 5)
    {
        $recent_users = get_users([
            'number' => $limit,
            'orderby' => 'registered',
            'order' => 'DESC',
            'fields' => ['ID', 'user_login', 'user_email', 'display_name', 'user_registered']
        ]);

        $users_data = [];
        foreach ($recent_users as $user) {
            // Use AvatarHelper so avatar URL is offload-friendly (wp_get_attachment_url when applicable)
            $avatar_url = AvatarHelper::getUserAvatarUrl($user->ID, ['size' => 96]);

            $display_name = $user->display_name ?: $user->user_login;
            $initials = $this->generateInitials($display_name);

            $users_data[] = [
                'id' => $user->ID,
                'username' => $user->user_login,
                'display_name' => $display_name,
                'email' => $user->user_email,
                'registered_date' => $user->user_registered,
                'avatar_url' => $avatar_url, // null if no Gravatar, triggers our fallback
                'fallback_initials' => $initials,
                'role' => $this->getUserRole($user->ID)
            ];
        }

        $total_users = count(get_users());

        return [
            'users' => $users_data,
            'total_users' => $total_users,
            'recent_count' => count($users_data)
        ];
    }

    /**
     * Generate initials from display name
     *
     * @param string $display_name Display name
     * @return string Initials
     */
    public function generateInitials($display_name)
    {
        $words = explode(' ', trim($display_name));
        $initials = '';

        if (count($words) >= 2) {
            $initials = strtoupper(substr($words[0], 0, 1) . substr($words[count($words) - 1], 0, 1));
        } else {
            $initials = strtoupper(substr($display_name, 0, 2));
        }

        return $initials;
    }

    /**
     * Get user role
     *
     * @param int $user_id User ID
     * @return string User role
     */
    public function getUserRole($user_id)
    {
        $user = \get_userdata($user_id);
        if ($user) {
            $roles = $user->roles;
            return !empty($roles) ? $roles[0] : 'subscriber';
        }
        return 'subscriber';
    }

    /**
     * Get user roles breakdown
     *
     * @param \DateTime $start_date Start date
     * @param \DateTime $end_date End date
     * @return array Role breakdown
     */
    public function getUserRolesBreakdown($start_date, $end_date)
    {
        $users = get_users([
            'date_query' => [
                [
                    'after' => $start_date->format('Y-m-d'),
                    'before' => $end_date->format('Y-m-d'),
                    'inclusive' => true
                ]
            ]
        ]);

        $roles = [];
        foreach ($users as $user) {
            $user_roles = $user->roles;
            foreach ($user_roles as $role) {
                $roles[$role] = ($roles[$role] ?? 0) + 1;
            }
        }

        return $roles;
    }

    /**
     * Get unique users for comments on a specific date
     *
     * @param \DateTime $date Date
     * @return int Number of unique users
     */
    public function getUniqueUsersForComments($date)
    {
        global $wpdb;

        return $wpdb->get_var($wpdb->prepare("
            SELECT COUNT(DISTINCT user_id)
            FROM {$wpdb->comments}
            WHERE DATE(comment_date) = %s
            AND user_id > 0
        ", $date->format('Y-m-d')));
    }

    /**
     * Get user registrations for specific date
     *
     * @param \DateTime $date Date
     * @return int Number of registrations
     */
    public function getUserRegistrationsForDate($date)
    {
        return count(get_users([
            'date_query' => [
                [
                    'after' => $date->format('Y-m-d'),
                    'before' => $date->format('Y-m-d'),
                    'inclusive' => true
                ]
            ]
        ]));
    }
}
