<?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 PDF;

class PdfReportController extends Controller
{
    /**
     * Generate monthly financial statement PDF
     */
    public function monthlyStatement()
    {
        $month = now();
        $contributions = Contribution::with('member')
            ->whereMonth('contribution_date', $month->month)
            ->whereYear('contribution_date', $month->year)
            ->get();
        
        $totalContributions = $contributions->sum('amount');
        $totalLoans = Loan::whereMonth('created_at', $month->month)
            ->whereYear('created_at', $month->year)
            ->sum('amount');
        
        $data = [
            'month' => $month->format('F Y'),
            'contributions' => $contributions,
            'totalContributions' => $totalContributions,
            'totalLoans' => $totalLoans,
            'generatedDate' => now()->format('d M Y')
        ];
        
        $pdf = PDF::loadView('pdfs.monthly-statement', $data);
        return $pdf->download('monthly-statement-' . $month->format('Y-m') . '.pdf');
    }

    /**
     * Generate member contribution statement PDF
     */
    public function memberStatement(Member $member)
    {
        $contributions = Contribution::where('member_id', $member->id)
            ->orderBy('contribution_date', 'desc')
            ->get();
        
        $totalContributions = $contributions->sum('amount');
        
        $data = [
            'member' => $member,
            'contributions' => $contributions,
            'totalContributions' => $totalContributions,
            'generatedDate' => now()->format('d M Y')
        ];
        
        $pdf = PDF::loadView('pdfs.member-statement', $data);
        return $pdf->download('member-statement-' . $member->id . '.pdf');
    }

    /**
     * Generate loan portfolio report PDF
     */
    public function loanReport()
    {
        $loans = Loan::with(['user', 'approver', 'disburser'])->latest()->get();
        
        $totalLoans = $loans->sum('amount');
        $disbursedLoans = $loans->where('disbursed_at', '!=', null)->sum('payment_amount');
        $pendingLoans = $loans->whereIn('status', ['pending_leader_review', 'pending_top_leader_review'])->count();
        
        $data = [
            'loans' => $loans,
            'totalLoans' => $totalLoans,
            'disbursedLoans' => $disbursedLoans,
            'pendingLoans' => $pendingLoans,
            'generatedDate' => now()->format('d M Y')
        ];
        
        $pdf = PDF::loadView('pdfs.loan-report', $data);
        return $pdf->download('loan-report-' . now()->format('Y-m-d') . '.pdf');
    }
}
