<?php

namespace App\Http\Controllers;

use App\Models\Member;
use App\Models\Transaction;
use App\Models\Loan;
use Illuminate\Support\Facades\Auth;

class DashboardController extends Controller
{
    public function index()
    {
        $user = auth()->user();
        $role = $user->role ?? 'user';
        $selectedRegion = session('selected_region');
        $isAdminOrTopLeader = in_array($role, ['admin', 'top-leader']);

        // Helper for filtering based on role and region
        $applyFilter = function($query, $type = 'member') use ($user, $selectedRegion, $isAdminOrTopLeader) {
            $role = $user->role ?? 'user';
            
            // For leaders, only show their own members
            if ($role === 'leader') {
                if ($type === 'member') {
                    $query->where('leader_id', $user->id);
                } elseif ($type === 'transaction') {
                    $query->whereHas('member', function($q) use ($user) {
                        $q->where('leader_id', $user->id);
                    });
                } elseif ($type === 'loan') {
                    $query->whereHas('user.member', function($q) use ($user) {
                        $q->where('leader_id', $user->id);
                    });
                }
            }
            // For admin/top-leader, apply region filter if selected
            elseif ($isAdminOrTopLeader && $selectedRegion) {
                if ($type === 'member') {
                    $query->whereHas('leader', function($q) use ($selectedRegion) {
                        $q->where('region', $selectedRegion);
                    });
                } elseif ($type === 'transaction') {
                    $query->whereHas('member.leader', function($q) use ($selectedRegion) {
                        $q->where('region', $selectedRegion);
                    });
                } elseif ($type === 'loan') {
                    $query->whereHas('user', function($q) use ($selectedRegion) {
                        $q->where('region', $selectedRegion);
                    });
                }
            }
        };

        // Retrieve recent members (e.g., last 5 members)
        $recentMembersQuery = Member::query();
        $applyFilter($recentMembersQuery);
        $recentMembers = $recentMembersQuery->latest()->take(5)->get();

        // Retrieve recent transactions (e.g., last 5 transactions)
        $recentTransactionsQuery = Transaction::query();
        $applyFilter($recentTransactionsQuery, 'transaction');
        $recentTransactions = $recentTransactionsQuery->latest()->take(5)->get();

        // Retrieve total members count
        $totalMembersQuery = Member::query();
        $applyFilter($totalMembersQuery);
        $totalMembers = $totalMembersQuery->count();

        // Retrieve total contributions sum
        $totalContributionsQuery = Transaction::query();
        $applyFilter($totalContributionsQuery, 'transaction');
        $totalContributions = $totalContributionsQuery->sum('amount');

        // Retrieve monthly contributions for current year
        $monthlyQuery = Transaction::query();
        $applyFilter($monthlyQuery, 'transaction');
        $monthlyContributions = $monthlyQuery->selectRaw('MONTH(created_at) as month, SUM(amount) as total')
            ->whereYear('created_at', date('Y'))
            ->groupBy('month')
            ->orderBy('month')
            ->pluck('total', 'month')
            ->toArray();

        // Ensure all months are present with 0 if no data
        $allMonths = range(1, 12);
        $monthlyContributionsFull = [];
        foreach ($allMonths as $month) {
            $monthlyContributionsFull[$month] = $monthlyContributions[$month] ?? 0;
        }

        // Pass the variables to the view
        $viewVars = compact(
            'recentMembers',
            'recentTransactions',
            'totalMembers',
            'totalContributions',
            'monthlyContributionsFull',
            'selectedRegion'
        );

        if ($role === 'user') {
            $viewVars['recentLoans'] = Loan::where('user_id', auth()->id())->latest()->take(5)->get();
        }

        // Additional data for top-leader
        if ($isAdminOrTopLeader) {
            // Active members count
            $activeQuery = Member::where('status', 'active');
            $applyFilter($activeQuery);
            $viewVars['activeMembers'] = $activeQuery->count();
            
            // Member growth (new members this month)
            $growthQuery = Member::whereMonth('created_at', date('m'))
                ->whereYear('created_at', date('Y'));
            $applyFilter($growthQuery);
            $viewVars['newMembersThisMonth'] = $growthQuery->count();
            
            // Previous month for comparison
            $prevGrowthQuery = Member::whereMonth('created_at', date('m') - 1)
                ->whereYear('created_at', date('Y'));
            $applyFilter($prevGrowthQuery);
            $viewVars['newMembersPreviousMonth'] = $prevGrowthQuery->count();
            
            // Total transactions count
            $transCountQuery = Transaction::query();
            $applyFilter($transCountQuery, 'transaction');
            $viewVars['totalTransactions'] = $transCountQuery->count();
            
            // Average contribution
            $avgQuery = Transaction::query();
            $applyFilter($avgQuery, 'transaction');
            $viewVars['averageContribution'] = $avgQuery->avg('amount') ?? 0;
            
            // Payment method breakdown
            $payQuery = Transaction::query();
            $applyFilter($payQuery, 'transaction');
            $viewVars['paymentMethods'] = $payQuery->selectRaw('payment_method, COUNT(*) as count, SUM(amount) as total')
                ->groupBy('payment_method')
                ->get();
            
            // Top 5 contributors
            $topQuery = Transaction::with('member');
            $applyFilter($topQuery, 'transaction');
            $viewVars['topContributors'] = $topQuery->selectRaw('member_id, SUM(amount) as total_contributed, COUNT(*) as contribution_count')
                ->groupBy('member_id')
                ->orderByDesc('total_contributed')
                ->take(5)
                ->get();
            
            // Recent 10 transactions for top leader
            $recent10Query = Transaction::with('member');
            $applyFilter($recent10Query, 'transaction');
            $viewVars['recentTransactions'] = $recent10Query->latest()->take(10)->get();
            
            // Monthly member growth
            $growthMonthlyQuery = Member::query();
            $applyFilter($growthMonthlyQuery);
            $viewVars['monthlyMemberGrowth'] = $growthMonthlyQuery->selectRaw('MONTH(created_at) as month, COUNT(*) as count')
                ->whereYear('created_at', date('Y'))
                ->groupBy('month')
                ->orderBy('month')
                ->pluck('count', 'month')
                ->toArray();
            
            // Ensure all months are present
            $monthlyGrowthFull = [];
            foreach ($allMonths as $month) {
                $monthlyGrowthFull[$month] = $viewVars['monthlyMemberGrowth'][$month] ?? 0;
            }
            $viewVars['monthlyMemberGrowth'] = $monthlyGrowthFull;
            
            // Contribution statistics by month (last 6 months)
            $last6Query = Transaction::query();
            $applyFilter($last6Query, 'transaction');
            $viewVars['last6MonthsStats'] = $last6Query->selectRaw('MONTH(created_at) as month, COUNT(*) as transaction_count, SUM(amount) as total_amount')
                ->where('created_at', '>=', now()->subMonths(6))
                ->groupBy('month')
                ->orderBy('month')
                ->get();
            
            // Pending loans count and data
            $pendingLoanQuery = Loan::where('status', 'pending');
            $applyFilter($pendingLoanQuery, 'loan');
            $viewVars['pendingLoansCount'] = $pendingLoanQuery->count();
            
            $pendingLoansListQuery = Loan::where('status', 'pending')->with('user');
            $applyFilter($pendingLoansListQuery, 'loan');
            $viewVars['pendingLoans'] = $pendingLoansListQuery->oldest()->take(5)->get();
        }


        // Return different dashboard views based on role
        $roleViews = [
            'user' => 'dashboard.user',
            'leader' => 'dashboard.leader',
            'top-leader' => 'dashboard.top-leader',
            'admin' => 'dashboard.top-leader', // Use top-leader view for admin too
        ];

        $view = $roleViews[$role] ?? 'dashboard';

        return view($view, $viewVars);
    }
}
