<?php

namespace App\Http\Controllers;

use App\Models\Contribution;
use App\Models\Transaction;
use App\Models\Loan;
use App\Models\Member;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class TreasurerDashboardController extends Controller
{
    public function index()
    {
        $user = auth()->user();
        $selectedRegion = session('selected_region');
        $isAdminOrTopLeader = in_array($user->role, ['admin', 'top-leader']);
        
        $isRegional = $isAdminOrTopLeader ? (bool)$selectedRegion : ($user->role === 'regional-treasurer');
        $region = $isAdminOrTopLeader ? $selectedRegion : $user->region;

        // Helper closures for filtering
        $filterContributions = function($query) use ($isRegional, $region) {
            if ($isRegional && $region) {
                $query->whereHas('member.leader', function($q) use ($region) {
                    $q->where('region', $region);
                });
            }
        };

        $filterLoans = function($query) use ($isRegional, $region) {
            if ($isRegional && $region) {
                $query->whereHas('user', function($q) use ($region) {
                    $q->where('region', $region);
                });
            }
        };

        $filterMembers = function($query) use ($isRegional, $region) {
            if ($isRegional && $region) {
                $query->whereHas('leader', function($q) use ($region) {
                    $q->where('region', $region);
                });
            }
        };

        $totalContributions = Contribution::where(function($q) use ($filterContributions) {
            $filterContributions($q);
        })->sum('amount');

        $socialContributions = Contribution::where('contribution_type', 'social')
            ->where(function($q) use ($filterContributions) {
                $filterContributions($q);
            })->sum('amount');

        $shareContributions = Contribution::where('contribution_type', 'share')
            ->where(function($q) use ($filterContributions) {
                $filterContributions($q);
            })->sum('amount');

        $monthlyContributions = Contribution::whereMonth('contribution_date', now()->month)
            ->whereYear('contribution_date', now()->year)
            ->where(function($q) use ($filterContributions) {
                $filterContributions($q);
            })
            ->sum('amount');

        $outstandingLoans = Loan::whereIn('status', ['approved', 'pending_top_leader_review', 'pending_leader_review'])
            ->where(function($q) use ($filterLoans) {
                $filterLoans($q);
            })
            ->sum('amount');
        
        $disbursedLoans = Loan::whereNotNull('disbursed_at')
            ->where(function($q) use ($filterLoans) {
                $filterLoans($q);
            })
            ->sum('payment_amount');
        
        $totalMembers = Member::where(function($q) use ($filterMembers) {
            $filterMembers($q);
        })->count();

        $activeMembers = Member::where('status', 'active')
            ->where(function($q) use ($filterMembers) {
                $filterMembers($q);
            })->count();
        
        // Recent Activity
        $recentContributions = Contribution::with('member')
            ->where(function($q) use ($filterContributions) {
                $filterContributions($q);
            })
            ->latest()
            ->take(5)
            ->get();
        
        $recentLoans = Loan::with('user')
            ->where(function($q) use ($filterLoans) {
                $filterLoans($q);
            })
            ->latest()
            ->take(5)
            ->get();
        
        $pendingLoans = Loan::whereIn('status', ['pending_leader_review', 'pending_top_leader_review'])
            ->where(function($q) use ($filterLoans) {
                $filterLoans($q);
            })
            ->count();
        
        // Payment method breakdown
        $paymentMethods = Contribution::select('payment_method', DB::raw('SUM(amount) as total'))
            ->where(function($q) use ($filterContributions) {
                $filterContributions($q);
            })
            ->groupBy('payment_method')
            ->get();
        
        // Monthly contributions for chart (last 12 months)
        $monthlyData = [];
        for ($i = 11; $i >= 0; $i--) {
            $month = now()->subMonths($i);
            $monthlyData[] = [
                'month' => $month->format('M Y'),
                'total' => Contribution::whereYear('contribution_date', $month->year)
                    ->whereMonth('contribution_date', $month->month)
                    ->where(function($q) use ($filterContributions) {
                        $filterContributions($q);
                    })
                    ->sum('amount')
            ];
        }
        
        // Loan status breakdown for chart
        $loanStats = [
            'pending_leader' => Loan::where('status', 'pending_leader_review')->where(function($q) use ($filterLoans) { $filterLoans($q); })->count(),
            'pending_top_leader' => Loan::where('status', 'pending_top_leader_review')->where(function($q) use ($filterLoans) { $filterLoans($q); })->count(),
            'approved' => Loan::where('status', 'approved')->where(function($q) use ($filterLoans) { $filterLoans($q); })->count(),
            'disbursed' => Loan::whereNotNull('disbursed_at')->where(function($q) use ($filterLoans) { $filterLoans($q); })->count(),
            'rejected' => Loan::whereIn('status', ['leader_rejected', 'top_leader_rejected'])->where(function($q) use ($filterLoans) { $filterLoans($q); })->count(),
        ];
        
        return view('treasurer.dashboard', compact(
            'totalContributions',
            'socialContributions',
            'shareContributions',
            'monthlyContributions',
            'outstandingLoans',
            'disbursedLoans',
            'totalMembers',
            'activeMembers',
            'recentContributions',
            'recentLoans',
            'pendingLoans',
            'paymentMethods',
            'monthlyData',
            'loanStats',
            'isRegional',
            'region'
        ));
    }
}
