<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Models\SystemSetting;
use App\Services\ThemeService;
use Illuminate\Http\Request;
use Illuminate\View\View;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class DashboardController extends Controller
{
    protected ThemeService $themeService;

    public function __construct(ThemeService $themeService)
    {
        $this->themeService = $themeService;
    }

    /**
     * Redirect to the appropriate dashboard based on user role.
     *
     * Uses getDashboardUrl() which guards against stale route caches by
     * falling back to direct URL paths when named routes are unavailable.
     */
    public function index(): RedirectResponse
    {
        return redirect()->to(Auth::user()->getDashboardUrl());
    }

    /**
     * Display the Super Manager dashboard.
     */
    public function superManager(): View
    {
        abort_unless(Auth::user()->hasRole('Super Manager'), 403);

        $stats = $this->getSuperManagerStats();

        return view('dashboard.super-manager', compact('stats'));
    }

    /**
     * Display the Manager dashboard.
     */
    public function manager(): View
    {
        abort_unless(Auth::user()->hasRole('Manager'), 403);

        $user  = Auth::user()->load('profile');
        $stats = $this->getManagerStats();

        return view('dashboard.manager', compact('user', 'stats'));
    }

    /**
     * Display the Members dashboard.
     */
    public function members(): View
    {
        abort_unless(Auth::user()->hasRole('Members'), 403);

        $user = Auth::user()->load('profile');
        $stats = $this->getMemberStats($user);

        return view('dashboard.members', compact('user', 'stats'));
    }

    /**
     * Display the Trainers dashboard.
     */
    public function trainers(): View
    {
        abort_unless(Auth::user()->hasRole('Trainers'), 403);

        $user = Auth::user()->load('profile');
        $stats = $this->getTrainerStats($user);

        return view('dashboard.trainers', compact('user', 'stats'));
    }

    /**
     * Display the Trainees dashboard.
     */
    public function trainees(): View
    {
        abort_unless(Auth::user()->hasRole('Trainees'), 403);

        $user = Auth::user()->load('profile');
        $stats = $this->getTraineeStats($user);

        return view('dashboard.trainees', compact('user', 'stats'));
    }

    /**
     * Display the Mentor dashboard.
     */
    public function mentor(): View
    {
        abort_unless(Auth::user()->hasRole('Mentor'), 403);

        $user = Auth::user()->load('profile');
        $stats = $this->getMentorStats($user);

        return view('dashboard.mentor', compact('user', 'stats'));
    }

    /**
     * Display the Mentee dashboard.
     */
    public function mentee(): View
    {
        abort_unless(Auth::user()->hasRole('Mentee'), 403);

        $user = Auth::user()->load('profile');
        $stats = $this->getMenteeStats($user);

        return view('dashboard.mentee', compact('user', 'stats'));
    }

    /**
     * Display the Partners dashboard.
     */
    public function partners(): View
    {
        abort_unless(Auth::user()->hasRole('Partners'), 403);

        $user = Auth::user()->load('profile');
        $stats = $this->getPartnerStats($user);

        return view('dashboard.partners', compact('user', 'stats'));
    }

    /**
     * Display the Contributor dashboard.
     */
    public function contributor(): View
    {
        abort_unless(Auth::user()->hasRole('Contributor'), 403);

        $user = Auth::user()->load('profile');
        $stats = $this->getContributorStats($user);

        return view('dashboard.contributor', compact('user', 'stats'));
    }

    /**
     * Display the Health Marketor dashboard.
     */
    public function healthMarketor(): View
    {
        abort_unless(Auth::user()->hasRole('Health Marketor'), 403);

        $user = Auth::user()->load('profile');
        $stats = $this->getHealthMarketorStats($user);

        return view('dashboard.health-marketor', compact('user', 'stats'));
    }

    /**
     * Get statistics for Super Manager dashboard.
     */
    protected function getSuperManagerStats(): array
    {
        // --- Existing ---
        $totalUsers    = User::count();
        $activeUsers   = User::active()->count();
        $inactiveUsers = User::inactive()->count();
        $usersByRole   = User::with('roles')->get()
            ->groupBy(fn($u) => $u->roles->first()?->name ?? 'No Role')
            ->map->count();
        $recentLogins  = \App\Models\UserSession::where('last_activity', '>=', now()->subDays(7))
            ->distinct('user_id')
            ->count('user_id');
        $otpEnabled    = SystemSetting::get('otp_enabled', false);

        // --- Fix: New Users (7 days) ---
        $newThisWeek = User::where('created_at', '>=', now()->subDays(7))->count();

        // --- Fix: 2FA Enabled ---
        $twoFactorEnabledCount = User::where('two_factor_enabled', true)
            ->whereNotNull('two_factor_confirmed_at')
            ->count();

        // --- Security stats ---
        $failedLoginsToday = \App\Models\LoginAttempt::failed()
            ->whereDate('attempted_at', today())
            ->count();

        $loginSparklineData = \App\Models\LoginAttempt::successful()
            ->where('attempted_at', '>=', now()->subHours(24))
            ->selectRaw('HOUR(attempted_at) as hour, COUNT(*) as count')
            ->groupBy('hour')
            ->orderBy('hour')
            ->pluck('count', 'hour')
            ->toArray();

        // --- Financial stats ---
        $monthlyRevenue = \App\Models\MembershipTransaction::where('status', 'completed')
            ->whereBetween('created_at', [now()->startOfMonth(), now()->endOfMonth()])
            ->sum('amount');

        // --- Training stats ---
        $totalTrainingSessions  = \App\Models\TrainingSession::count();
        $activeTrainingSessions = \App\Models\TrainingSession::where('status', 'scheduled')->count();
        $totalRegistrations     = \App\Models\TrainingRegistration::count();

        // --- Mentorship stats ---
        $activeAssignments       = \App\Models\Mentorship\Assignment::where('status', 'active')->count();
        $totalMentorshipSessions = \App\Models\Mentorship\Session::count();

        // --- Membership stats ---
        $totalMembers     = \App\Models\Member::count();
        $pendingApprovals = \App\Models\MembershipApplication::where('status', 'pending')->count();

        // --- Permission heatmap data ---
        $rolesWithPermissions = \Spatie\Permission\Models\Role::with('permissions')->get();

        // --- System alerts ---
        $systemAlerts = [];
        if ($failedLoginsToday > 10) {
            $systemAlerts[] = [
                'type'     => 'security',
                'message'  => "High failed login count: {$failedLoginsToday} today",
                'count'    => $failedLoginsToday,
                'severity' => 'critical',
            ];
        }
        if ($pendingApprovals > 5) {
            $systemAlerts[] = [
                'type'     => 'approval',
                'message'  => "{$pendingApprovals} membership applications pending review",
                'count'    => $pendingApprovals,
                'severity' => 'warning',
            ];
        }
        $newUsersLastHour = User::where('created_at', '>=', now()->subHour())->count();
        if ($newUsersLastHour > 0) {
            $systemAlerts[] = [
                'type'     => 'info',
                'message'  => "{$newUsersLastHour} new user(s) registered in the last hour",
                'count'    => $newUsersLastHour,
                'severity' => 'info',
            ];
        }
        if ($totalRegistrations > 0) {
            $pendingTraining = \App\Models\TrainingRegistration::where('status', 'pending')->count();
            if ($pendingTraining > 0) {
                $systemAlerts[] = [
                    'type'     => 'training',
                    'message'  => "{$pendingTraining} training registration(s) awaiting approval",
                    'count'    => $pendingTraining,
                    'severity' => 'warning',
                ];
            }
        }

        return [
            // Existing
            'total_users'               => $totalUsers,
            'active_users'              => $activeUsers,
            'inactive_users'            => $inactiveUsers,
            'users_by_role'             => $usersByRole,
            'recent_logins'             => $recentLogins,
            'otp_enabled'               => $otpEnabled,
            // Fixes
            'new_this_week'             => $newThisWeek,
            'two_factor_enabled_count'  => $twoFactorEnabledCount,
            // Security
            'failed_logins_today'       => $failedLoginsToday,
            'login_sparkline_data'      => $loginSparklineData,
            // Financial
            'monthly_revenue'           => (float) $monthlyRevenue,
            // Training
            'total_training_sessions'   => $totalTrainingSessions,
            'active_training_sessions'  => $activeTrainingSessions,
            'total_registrations'       => $totalRegistrations,
            // Mentorship
            'active_assignments'        => $activeAssignments,
            'total_mentorship_sessions' => $totalMentorshipSessions,
            // Membership
            'total_members'             => $totalMembers,
            'pending_approvals'         => $pendingApprovals,
            // Heatmap
            'roles_with_permissions'    => $rolesWithPermissions,
            // Alerts
            'system_alerts'             => $systemAlerts,
        ];
    }

    /**
     * Get statistics for Manager dashboard.
     */
    protected function getManagerStats(): array
    {
        // User stats
        $totalUsers   = User::count();
        $activeUsers  = User::active()->count();
        $newThisWeek  = User::where('created_at', '>=', now()->subWeek())->count();
        $newThisMonth = User::where('created_at', '>=', now()->subMonth())->count();

        // Pending approval counts
        $pendingMemberApprovals        = \App\Models\MembershipApplication::where('status', 'pending')->count();
        $pendingTrainingRegistrations  = \App\Models\TrainingRegistration::where('status', 'pending')->count();
        $pendingMentorshipApplications = \App\Models\Mentorship\Application::where('status', 'pending')->count();
        $pendingLoanApplications       = \App\Models\LoanApplication::where('status', 'pending')->count();

        // Pending queues (limit 10 each for display)
        $pendingMemberQueue = \App\Models\MembershipApplication::where('status', 'pending')
            ->with('user')
            ->latest()
            ->limit(10)
            ->get();

        $pendingTrainingQueue = \App\Models\TrainingRegistration::where('status', 'pending')
            ->with(['user', 'trainingPackage'])
            ->latest()
            ->limit(10)
            ->get();

        $pendingMentorshipQueue = \App\Models\Mentorship\Application::where('status', 'pending')
            ->with(['user', 'programme'])
            ->latest()
            ->limit(10)
            ->get();

        // Module overview
        $totalTrainingSessions  = \App\Models\TrainingSession::count();
        $activeTrainingSessions = \App\Models\TrainingSession::where('status', 'scheduled')->count();
        $totalRegistrations     = \App\Models\TrainingRegistration::count();
        $totalProgrammes        = \App\Models\Mentorship\Programme::count();
        $activeAssignments      = \App\Models\Mentorship\Assignment::where('status', 'active')->count();
        $totalMembers           = \App\Models\Member::count();

        // Trend data — last 12 weeks
        $trendLabels = collect(range(11, 0))
            ->map(fn($w) => now()->subWeeks($w)->format('M d'))
            ->values()
            ->toArray();

        $trainingTrend = \App\Models\TrainingRegistration::selectRaw(
            'YEARWEEK(created_at, 1) as yw, COUNT(*) as count'
        )->where('created_at', '>=', now()->subWeeks(12))
         ->groupBy('yw')
         ->orderBy('yw')
         ->pluck('count')
         ->values()
         ->toArray();

        $mentorshipTrend = \App\Models\Mentorship\Assignment::selectRaw(
            'YEARWEEK(created_at, 1) as yw, COUNT(*) as count'
        )->where('created_at', '>=', now()->subWeeks(12))
         ->groupBy('yw')
         ->orderBy('yw')
         ->pluck('count')
         ->values()
         ->toArray();

        return [
            'total_users'                      => $totalUsers,
            'active_users'                     => $activeUsers,
            'new_this_week'                    => $newThisWeek,
            'new_this_month'                   => $newThisMonth,
            'pending_member_approvals'         => $pendingMemberApprovals,
            'pending_training_registrations'   => $pendingTrainingRegistrations,
            'pending_mentorship_applications'  => $pendingMentorshipApplications,
            'pending_loan_applications'        => $pendingLoanApplications,
            'pending_member_queue'             => $pendingMemberQueue,
            'pending_training_queue'           => $pendingTrainingQueue,
            'pending_mentorship_queue'         => $pendingMentorshipQueue,
            'total_training_sessions'          => $totalTrainingSessions,
            'active_training_sessions'         => $activeTrainingSessions,
            'total_registrations'              => $totalRegistrations,
            'total_programmes'                 => $totalProgrammes,
            'active_assignments'               => $activeAssignments,
            'total_members'                    => $totalMembers,
            'trend_labels'                     => $trendLabels,
            'training_trend'                   => $trainingTrend,
            'mentorship_trend'                 => $mentorshipTrend,
        ];
    }

    /**
     * Get statistics for Member dashboard.
     */
    protected function getMemberStats(User $user): array
    {
        $member = \App\Models\Member::where('user_id', $user->id)
            ->with(['membershipCategories'])
            ->first();

        // Contribution stats — all null-safe for missing Member record
        $totalPaid        = $member?->contributions()->paid()->sum('amount') ?? 0;
        $overdueCount     = $member?->contributions()->overdue()->count() ?? 0;
        $nextContribution = $member?->contributions()->pending()
                                ->orderBy('due_date')->first();

        // Loan stats — null-safe
        $activeLoans    = $member?->loanApplications()->active()->count() ?? 0;
        $outstandingBal = $member?->loanApplications()->active()->sum('outstanding_balance') ?? 0;
        $nextLoan       = $member?->loanApplications()->active()
                                ->orderBy('next_payment_date')->first();

        // Training stats — scoped to user, not member
        $completedTraining = \App\Models\TrainingRegistration::forUser($user->id)->completed()->count();
        $pendingTraining   = \App\Models\TrainingRegistration::forUser($user->id)->pending()->count();
        $recentTraining    = \App\Models\TrainingRegistration::forUser($user->id)
                                ->with('trainingPackage')->latest()->limit(5)->get();

        // Recent membership transactions — empty collection if no member record
        $recentTransactions = $member
            ? \App\Models\MembershipTransaction::where('member_id', $member->id)
                ->latest()->limit(5)->get()
            : collect();

        return [
            'days_active'          => $user->created_at->diffInDays(now()),
            'last_login'           => $user->sessions()->latest('last_activity')->value('last_activity')?->diffForHumans() ?? 'Never',
            'member'               => $member,
            'membership_status'    => $member?->status ?? 'not_registered',
            'membership_code'      => $member?->membership_code,
            'membership_category'  => $member?->primary_category?->name ?? 'N/A',
            'next_renewal_date'    => $member?->next_renewal_date?->format('d M Y'),
            'total_paid'           => (float) $totalPaid,
            'overdue_count'        => (int) $overdueCount,
            'next_contribution'    => $nextContribution,
            'active_loans'         => (int) $activeLoans,
            'outstanding_balance'  => (float) $outstandingBal,
            'next_loan_payment'    => $nextLoan,
            'completed_training'   => (int) $completedTraining,
            'pending_training'     => (int) $pendingTraining,
            'recent_training'      => $recentTraining,
            'recent_transactions'  => $recentTransactions,
        ];
    }

    /**
     * Get statistics for Trainer dashboard.
     */
    protected function getTrainerStats(User $user): array
    {
        // Step 1: Get all session IDs where this user is an assigned trainer
        $sessionIds = \App\Models\TrainingSession::whereHas('trainers', function ($q) use ($user) {
            $q->where('trainer_id', $user->id);
        })->pluck('id');

        // Step 2: Get all unique package IDs from those sessions
        $packageIds = $sessionIds->isNotEmpty()
            ? \App\Models\TrainingSession::whereIn('id', $sessionIds)
                ->pluck('training_package_id')
                ->unique()
            : collect();

        // Upcoming sessions (next 3) scoped to trainer's sessions
        $upcomingSessions = $sessionIds->isNotEmpty()
            ? \App\Models\TrainingSession::whereIn('id', $sessionIds)
                ->upcoming()
                ->with('trainingPackage')
                ->limit(3)
                ->get()
            : collect();

        // Leaderboard: all approved/completed registrations for trainer's packages
        $leaderboard = $packageIds->isNotEmpty()
            ? \App\Models\TrainingRegistration::whereIn('training_package_id', $packageIds)
                ->whereIn('status', ['approved', 'completed'])
                ->with(['user', 'trainingPackage'])
                ->orderByDesc('attendance_percentage')
                ->get()
            : collect();

        // Stats
        $totalSessions    = $sessionIds->count();
        $totalTrainees    = $packageIds->isNotEmpty()
            ? \App\Models\TrainingRegistration::whereIn('training_package_id', $packageIds)
                ->whereIn('status', ['approved', 'completed'])
                ->count()
            : 0;
        $certificatesIssued = \App\Models\TrainingCertificate::where('generated_by', $user->id)->count();

        // Pending attendance: completed sessions with no attendance records
        $pendingAttendance = $sessionIds->isNotEmpty()
            ? \App\Models\TrainingSession::whereIn('id', $sessionIds)
                ->where('status', 'completed')
                ->whereDoesntHave('attendances')
                ->count()
            : 0;

        return [
            'days_active'          => $user->created_at->diffInDays(now()),
            'experience_years'     => $user->profile?->experience_years ?? 0,
            'specialization'       => $user->profile?->specialization ?? 'Not specified',
            'certification'        => $user->profile?->certification ?? 'Not Set',
            'session_ids'          => $sessionIds,
            'package_ids'          => $packageIds,
            'upcoming_sessions'    => $upcomingSessions,
            'leaderboard'          => $leaderboard,
            'total_sessions'       => $totalSessions,
            'total_trainees'       => $totalTrainees,
            'certificates_issued'  => $certificatesIssued,
            'pending_attendance'   => $pendingAttendance,
        ];
    }

    /**
     * Get statistics for Trainee dashboard.
     */
    protected function getTraineeStats(User $user): array
    {
        // All active/completed registrations for this trainee (scoped to user_id)
        $registrations = \App\Models\TrainingRegistration::where('user_id', $user->id)
            ->whereIn('status', ['approved', 'completed'])
            ->with(['trainingPackage.category'])
            ->get();

        // Package IDs for upcoming sessions lookup
        $packageIds = $registrations->pluck('training_package_id')->unique();

        // Upcoming sessions (next 2) — scoped to enrolled packages only
        $upcomingSessions = $packageIds->isNotEmpty()
            ? \App\Models\TrainingSession::whereIn('training_package_id', $packageIds)
                ->upcoming()
                ->with('trainingPackage')
                ->limit(2)
                ->get()
            : collect();

        // Valid certificates earned
        $certificates = \App\Models\TrainingCertificate::where('user_id', $user->id)
            ->valid()
            ->with('trainingPackage')
            ->get();

        // Spider chart: group completed registrations by category name
        // Use fixed axis mapping (Option B from guide) for consistent pentagon shape
        $axisMap = [
            'Technical'                => 'Technical Skills',
            'Technical Skills'         => 'Technical Skills',
            'Soft Skills'              => 'Soft Skills',
            'Communication'            => 'Soft Skills',
            'Leadership'               => 'Leadership',
            'Management'               => 'Leadership',
            'Health & Wellness'        => 'Health & Wellness',
            'Health'                   => 'Health & Wellness',
            'Professional Dev'         => 'Professional Development',
            'Professional Development' => 'Professional Development',
        ];

        $completedByCategory = [];
        foreach ($registrations->where('status', 'completed') as $reg) {
            $rawCategory = $reg->trainingPackage?->category?->name ?? 'Other';
            $axis = $axisMap[$rawCategory] ?? null;
            if ($axis) {
                $completedByCategory[$axis] = ($completedByCategory[$axis] ?? 0) + 1;
            }
        }

        return [
            'days_active'           => $user->created_at->diffInDays(now()),
            'fitness_level'         => $user->profile?->fitness_level ?? 'Not specified',
            'goals'                 => $user->profile?->goals ?? 'Not specified',
            'registrations'         => $registrations,
            'upcoming_sessions'     => $upcomingSessions,
            'certificates'          => $certificates,
            'completed_by_category' => $completedByCategory,
            'active_registrations'  => $registrations->count(),
            'cert_count'            => $certificates->count(),
        ];
    }

    /**
     * Get statistics for Mentor dashboard.
     */
    protected function getMentorStats(User $user): array
    {
        // Active + pending_acceptance assignments with mentee and programme eager-loaded
        $assignments = \App\Models\Mentorship\Assignment::where('mentor_id', $user->id)
            ->whereIn('status', ['active', 'pending_acceptance'])
            ->with(['mentee', 'programme'])
            ->get();

        // Next upcoming session across all this mentor's assignments
        $nextSession = \App\Models\Mentorship\Session::whereHas('assignment', function ($q) use ($user) {
            $q->where('mentor_id', $user->id);
        })->upcoming()
          ->with(['assignment.mentee', 'assignment.programme'])
          ->first();

        // Stat counts
        $activeMentees     = $assignments->where('status', 'active')->count();
        $sessionsCompleted = \App\Models\Mentorship\Session::whereHas('assignment', function ($q) use ($user) {
            $q->where('mentor_id', $user->id);
        })->where('status', 'completed')->count();
        $certsIssued       = \App\Models\Mentorship\Certificate::whereHas('assignment', function ($q) use ($user) {
            $q->where('mentor_id', $user->id);
        })->where('status', 'active')->count();
        $pendingAcceptance = $assignments->where('status', 'pending_acceptance')->count();

        return [
            'days_active'        => $user->created_at->diffInDays(now()),
            'expertise_areas'    => $user->profile?->expertise_areas ?? 'Not specified',
            'availability'       => $user->profile?->availability ?? 'Not specified',
            'assignments'        => $assignments,
            'next_session'       => $nextSession,
            'active_mentees'     => $activeMentees,
            'sessions_completed' => $sessionsCompleted,
            'certs_issued'       => $certsIssued,
            'pending_acceptance' => $pendingAcceptance,
        ];
    }

    /**
     * Get statistics for Mentee dashboard.
     */
    protected function getMenteeStats(User $user): array
    {
        $activeAssignment = \App\Models\Mentorship\Assignment::where('mentee_id', $user->id)
            ->where('status', 'active')
            ->with(['mentor', 'programme'])
            ->first();

        $nextSession = \App\Models\Mentorship\Session::whereHas(
            'assignment',
            fn($q) => $q->where('mentee_id', $user->id)
        )
            ->upcoming()
            ->with('assignment.mentor')
            ->orderBy('start_time')
            ->first();

        return [
            // Profile fields (keep existing)
            'days_active'               => $user->created_at->diffInDays(now()),
            'learning_goals'            => $user->profile?->learning_goals ?? 'Not specified',
            'experience_level'          => $user->profile?->experience_level ?? 'Not specified',

            // Mentorship data
            'active_assignment'         => $activeAssignment,
            'next_session'              => $nextSession,
            'active_assignment_count'   => \App\Models\Mentorship\Assignment::where('mentee_id', $user->id)
                                                ->where('status', 'active')->count(),
            'sessions_completed'        => $activeAssignment?->sessions_completed ?? 0,
            'certificate_count'         => \App\Models\Mentorship\Certificate::where('user_id', $user->id)
                                                ->where('status', 'active')->count(),
            'pending_acceptance_count'  => \App\Models\Mentorship\Assignment::where('mentee_id', $user->id)
                                                ->where('status', 'pending_acceptance')->count(),
        ];
    }

    /**
     * Get statistics for Partner dashboard.
     */
    protected function getPartnerStats(User $user): array
    {
        // Resolve the RPartner record linked to this user (may be null)
        $partnerRecord = \App\Models\RPartner::where('user_id', $user->id)->first();

        // Active partnership (latest active MOU/contract)
        $activePartnership = $partnerRecord
            ? \App\Models\RPartnership::where('partner_id', $partnerRecord->id)
                ->active()
                ->latest()
                ->first()
            : null;

        // ROI metrics — all null-safe
        $totalContractValue = $partnerRecord
            ? (float) (\App\Models\RPartnership::where('partner_id', $partnerRecord->id)
                ->active()
                ->sum('value') ?? 0)
            : 0.0;

        $contractCurrency = $partnerRecord
            ? (\App\Models\RPartnership::where('partner_id', $partnerRecord->id)
                ->active()
                ->latest()
                ->value('currency') ?? 'USD')
            : 'USD';

        $forumThreadCount = $partnerRecord
            ? \App\Models\RForumThread::where('partner_id', $partnerRecord->id)->count()
            : 0;

        $daysRemaining = $activePartnership?->days_remaining;

        // Published research publications for resource repository
        $publications = \App\Models\RPublication::published()
            ->with(['files' => fn($q) => $q->where('is_public', true)])
            ->latest('approved_at')
            ->take(12)
            ->get();

        return [
            // Profile fields
            'days_active'      => $user->created_at->diffInDays(now()),
            'company_name'     => $user->profile?->company_name
                                    ?? $partnerRecord?->organization_name
                                    ?? 'Not specified',
            'partnership_type' => $user->profile?->partnership_type
                                    ?? $partnerRecord?->organization_type
                                    ?? 'Not specified',

            // Partner identity
            'partner_record'       => $partnerRecord,
            'active_partnership'   => $activePartnership,

            // ROI metrics
            'total_contract_value' => $totalContractValue,
            'contract_currency'    => $contractCurrency,
            'forum_thread_count'   => $forumThreadCount,
            'partnership_level'    => $partnerRecord?->partnership_level ?? 'bronze',
            'partnership_status'   => $partnerRecord?->partnership_status ?? 'pending',
            'days_remaining'       => $daysRemaining,

            // Resource repository
            'publications' => $publications,
        ];
    }

    /**
     * Get statistics for Contributor dashboard.
     */
    protected function getContributorStats(User $user): array
    {
        // Activity heatmap: merge Discussion + DiscussionReply daily counts for past year
        $discussionDates = \App\Models\Discussion::where('user_id', $user->id)
            ->where('created_at', '>=', now()->subYear())
            ->selectRaw('DATE(created_at) as date, COUNT(*) as count')
            ->groupBy('date')
            ->pluck('count', 'date');

        $replyDates = \App\Models\DiscussionReply::where('user_id', $user->id)
            ->active()
            ->where('created_at', '>=', now()->subYear())
            ->selectRaw('DATE(created_at) as date, COUNT(*) as count')
            ->groupBy('date')
            ->pluck('count', 'date');

        $activityData = $discussionDates->mergeRecursive($replyDates)
            ->map(fn($v) => is_array($v) ? array_sum($v) : $v)
            ->toArray();

        return [
            // Profile fields
            'days_active'            => $user->created_at->diffInDays(now()),
            'contribution_type'      => $user->profile?->contribution_type ?? 'Not specified',
            'skills'                 => $user->profile?->skills ?? 'Not specified',

            // Discussion stats
            'total_discussions'      => \App\Models\Discussion::where('user_id', $user->id)->count(),
            'published_discussions'  => \App\Models\Discussion::where('user_id', $user->id)->published()->count(),
            'draft_discussions'      => \App\Models\Discussion::where('user_id', $user->id)->where('status', 'draft')->count(),
            'total_views'            => (int) \App\Models\Discussion::where('user_id', $user->id)->sum('view_count'),
            'total_replies'          => \App\Models\DiscussionReply::where('user_id', $user->id)->active()->count(),

            // Activity heatmap data (date → count map)
            'activity_data'          => $activityData,

            // Recent discussions with topic
            'recent_discussions'     => \App\Models\Discussion::with(['topic'])
                                            ->where('user_id', $user->id)
                                            ->latest()
                                            ->limit(5)
                                            ->get(),

            // Active topics with discussion counts
            'topics'                 => \App\Models\DiscussionTopic::active()
                                            ->ordered()
                                            ->withCount(['discussions' => fn($q) => $q->published()])
                                            ->limit(10)
                                            ->get(),

            // Published publications for resource repository
            'recent_publications'    => \App\Models\RPublication::published()
                                            ->with('files')
                                            ->latest()
                                            ->limit(6)
                                            ->get(),

            // Own publications (all statuses)
            'own_publications'       => \App\Models\RPublication::where('user_id', $user->id)
                                            ->latest()
                                            ->limit(5)
                                            ->get(),
        ];
    }

    /**
     * Get statistics for Health Marketor dashboard.
     */
    protected function getHealthMarketorStats(User $user): array
    {
        // Institution portfolio stats scoped to this user
        $institutionBase = \App\Models\HealthInstitution::where('user_id', $user->id);
        $institutionStats = [
            'total'   => (clone $institutionBase)->count(),
            'active'  => (clone $institutionBase)->where('listing_status', 'published')->count(),
            'pending' => (clone $institutionBase)->where('listing_status', 'pending_payment')->count(),
            'expired' => (clone $institutionBase)->where('listing_status', 'expired')->count(),
        ];

        // Machine inventory stats scoped to this user
        $machineBase = \App\Models\DigitalMachine::where('user_id', $user->id);
        $machineStats = [
            'total'   => (clone $machineBase)->count(),
            'active'  => (clone $machineBase)->where('listing_status', 'published')->count(),
            'pending' => (clone $machineBase)->whereIn('listing_status', ['pending_payment', 'pending_approval'])->count(),
            'expired' => (clone $machineBase)->where('listing_status', 'expired')->count(),
        ];

        // Recent institutions for table widget
        $recentInstitutions = \App\Models\HealthInstitution::where('user_id', $user->id)
            ->latest()->take(5)->get();

        // Recent machines for table widget
        $recentMachines = \App\Models\DigitalMachine::where('user_id', $user->id)
            ->latest()->take(5)->get();

        // Campaign funnel feed
        $recentCampaigns = \App\Models\RCampaign::where('user_id', $user->id)
            ->latest()->take(5)->get();

        // Sentiment data from poll responses
        $pollIds = \App\Models\RPoll::where('user_id', $user->id)->pluck('id');
        $sentimentData = ['positive' => 0, 'neutral' => 0, 'negative' => 0];
        if ($pollIds->isNotEmpty()) {
            $responses = \App\Models\RPollResponse::whereIn('poll_id', $pollIds)
                ->with('option')
                ->get();
            foreach ($responses as $response) {
                $sentiment = $response->option?->sentiment ?? 'neutral';
                if (array_key_exists($sentiment, $sentimentData)) {
                    $sentimentData[$sentiment]++;
                } else {
                    $sentimentData['neutral']++;
                }
            }
        }

        // Institution city distribution for geo density map
        $institutionCities = \App\Models\HealthInstitution::where('user_id', $user->id)
            ->select('city', \Illuminate\Support\Facades\DB::raw('count(*) as count'))
            ->groupBy('city')
            ->get();

        return [
            // Profile
            'days_active'     => $user->created_at->diffInDays(now()),
            'marketing_focus' => $user->profile?->marketing_focus ?? 'Not specified',
            'target_audience' => $user->profile?->target_audience ?? 'Not specified',

            // Institution portfolio
            'institution_stats'   => $institutionStats,
            'recent_institutions' => $recentInstitutions,

            // Machine inventory
            'machine_stats'   => $machineStats,
            'recent_machines' => $recentMachines,

            // Campaign funnel
            'recent_campaigns' => $recentCampaigns,

            // Sentiment chart
            'sentiment_data' => $sentimentData,

            // Geo density map
            'institution_cities' => $institutionCities,
        ];
    }
}
