<?php

namespace App\Http\Controllers;

use App\Models\Contribution;
use App\Models\Loan;
use App\Models\Member;
use Illuminate\Http\Request;
use Barryvdh\DomPDF\Facade\Pdf;

class MemberDashboardController extends Controller
{
    /**
     * Show member dashboard
     */
    public function index()
    {
        $user = auth()->user();
        
        // Get user's loans (loans are linked to users via user_id)
        $loans = Loan::where('user_id', $user->id)
            ->with(['leaderApprover', 'approver', 'disburser'])
            ->latest()
            ->take(5)
            ->get();
        
        $activeLoans = Loan::where('user_id', $user->id)
            ->whereIn('status', ['approved', 'pending_leader_review', 'pending_top_leader_review'])
            ->count();
        
        $totalLoanAmount = Loan::where('user_id', $user->id)
            ->whereNotNull('disbursed_at')
            ->sum('payment_amount');
        
        // Link User to Member via phone
        $member = Member::where('phone', $user->phone)->first();
        
        $contributions = collect([]);
        $totalContributions = 0;
        $thisMonthContributions = 0;
        $monthlyData = [];

        if ($member) {
            $contributions = $member->contributions()->latest()->take(5)->get();
            $totalContributions = $member->contributions()->sum('amount');
            $thisMonthContributions = $member->contributions()
                ->whereMonth('contribution_date', now()->month)
                ->whereYear('contribution_date', now()->year)
                ->sum('amount');
        }
        
        for ($i = 5; $i >= 0; $i--) {
            $month = now()->subMonths($i);
            $total = 0;
            if ($member) {
                $total = $member->contributions()
                    ->whereMonth('contribution_date', $month->month)
                    ->whereYear('contribution_date', $month->year)
                    ->sum('amount');
            }
            $monthlyData[] = [
                'month' => $month->format('M'),
                'total' => $total
            ];
        }
        
        return view('member.dashboard', compact(
            'contributions',
            'totalContributions',
            'thisMonthContributions',
            'loans',
            'activeLoans',
            'totalLoanAmount',
            'monthlyData'
        ));
    }
    
    /**
     * Show contribution history
     */
    public function contributions()
    {
        $user = auth()->user();
        $member = Member::where('phone', $user->phone)->first();
        
        $contributions = $member ? $member->contributions()->latest()->paginate(15) : collect([]);
        
        return view('member.contributions', compact('contributions'));
    }
    
    /**
     * Download personal statement PDF
     */
    public function downloadStatement()
    {
        $user = auth()->user();
        $member = Member::where('phone', $user->phone)->first();
        
        if (!$member) {
            return back()->with('error', 'Member record not found for this account.');
        }

        $contributions = $member->contributions()->latest()->get();
        $totalContributions = $contributions->sum('amount');
        
        $data = [
            'member' => $member,
            'user' => $member, // For compatibility
            'contributions' => $contributions,
            'totalContributions' => $totalContributions,
            'generatedDate' => now()->format('d M Y')
        ];
        
        $pdf = Pdf::loadView('pdfs.member-statement', $data);
        return $pdf->download('my-statement-' . now()->format('Y-m-d') . '.pdf');
    }
}
