<?php

namespace App\Http\Controllers;

use App\Models\Loan;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use App\Mail\LoanApprovalMail;
use App\Mail\LoanRejectionMail;
use App\Mail\LoanDisbursedMail;

class LoanController extends Controller
{
    public function index()
    {
        $user = auth()->user();
        
        // If user is just a member, show only their loans
        if ($user->role === 'user') {
            $loans = Loan::where('user_id', $user->id)
                ->with(['leaderApprover', 'approver', 'disburser'])
                ->latest()
                ->get();
        } else {
            // For leaders, treasurers, admins
            $query = Loan::with(['user', 'leaderApprover', 'approver', 'disburser']);

            // Regional Treasurer Filtering
            if ($user->role === 'regional-treasurer' && $user->region) {
                $query->whereHas('user', function($q) use ($user) {
                    $q->where('region', $user->region);
                });
            }
            // Leader Filtering (only their members' loans)
            elseif ($user->role === 'leader') {
                $query->whereHas('user.member', function($q) use ($user) {
                    $q->where('leader_id', $user->id);
                });
            }

            $loans = $query->latest()->get();
        }

        return view('loans.index', compact('loans'));
    }

    public function create()
    {
        return view('loans.create');
    }

    public function store(Request $request)
    {
        $request->validate([
            'amount' => 'required|numeric|min:1',
            'purpose' => 'required|string|max:1000',
        ]);

        Loan::create([
            'user_id' => auth()->id(),
            'amount' => $request->amount,
            'purpose' => $request->purpose,
            'status' => 'pending_leader_review',
        ]);

        return redirect()->route('loans.index')->with('success', 'Loan request submitted successfully.');
    }

    public function show(Loan $loan)
    {
        // Check authorization
        $user = auth()->user();
        if ($loan->user_id !== $user->id && !in_array($user->role, ['leader', 'top-leader', 'admin'])) {
            abort(403, 'Unauthorized action.');
        }

        $loan->load(['user', 'leaderApprover', 'approver', 'disburser']);
        return view('loans.show', compact('loan'));
    }

    // Leader approves/rejects loan
    public function confirm(Request $request, Loan $loan)
    {
        $user = auth()->user();
        
        // Leaders can only approve pending_leader_review
        if ($user->role === 'leader' && !$loan->isPendingLeaderReview()) {
            return redirect()->back()->with('error', 'This loan is not pending your review.');
        }
        
        // Top-leaders can approve pending_top_leader_review
        if (in_array($user->role, ['top-leader', 'admin']) && !$loan->isPendingTopLeaderReview()) {
            return redirect()->back()->with('error', 'This loan is not pending your review.');
        }

        $request->validate([
            'action' => 'required|in:approve,reject',
            'notes' => 'nullable|string|max:1000',
        ]);

        if ($user->role === 'leader') {
            // Leader approval/rejection
            if ($request->action === 'approve') {
                $loan->update([
                    'status' => 'pending_top_leader_review',
                    'leader_approved_by' => $user->id,
                    'leader_approved_at' => now(),
                ]);
                $message = 'Loan approved and sent to top-leader for final review.';
            } else {
                $loan->update([
                    'status' => 'leader_rejected',
                    'leader_approved_by' => $user->id,
                    'leader_approved_at' => now(),
                    'leader_notes' => $request->notes,
                ]);
                
                // Send email notification to user
                Mail::to($loan->user->email)->send(
                    new LoanApprovalMail($loan, $user->name, true)
                );
                $message = 'Loan request rejected.';
            }
        } else {
            // Top-leader/admin final approval
            if ($request->action === 'approve') {
                $loan->update([
                    'status' => 'approved',
                    'approved_by' => $user->id,
                    'approved_at' => now(),
                ]);
                $message = 'Loan approved successfully. Ready for disbursement.';
            } else {
                $loan->update([
                    'status' => 'top_leader_rejected',
                    'approved_by' => $user->id,
                    'approved_at' => now(),
                    'notes' => $request->notes,
                ]);
                
                // Send rejection email
                Mail::to($loan->user->email)->send(
                    new LoanRejectionMail($loan, $user->name, $request->notes)
                );
                $message = 'Loan request rejected.';
            }
        }

        return redirect()->back()->with('success', $message);
    }

    public function pending()
    {
        $user = auth()->user();
        
        // Leaders see pending_leader_review
        // Top-leaders see pending_top_leader_review
        if ($user->role === 'leader') {
            $loans = Loan::where('status', 'pending_leader_review')
                ->whereHas('user.member', function($q) use ($user) {
                    $q->where('leader_id', $user->id);
                })
                ->with('user')
                ->oldest()
                ->get();
        } else {
            $loans = Loan::where('status', 'pending_top_leader_review');
            
            // Filter by selected region for top leaders if applicable
            $selectedRegion = session('selected_region');
            if ($selectedRegion) {
                $loans->whereHas('user.member', function($q) use ($selectedRegion) {
                    $q->whereHas('leader', function($query) use ($selectedRegion) {
                        $query->where('region', $selectedRegion);
                    });
                });
            }

            $loans = $loans->with(['user', 'leaderApprover'])
                ->oldest()
                ->get();
        }
        
        return view('loans.pending', compact('loans'));
    }

    public function markAsPaid(Request $request, Loan $loan)
    {
        $user = auth()->user();

        // Check permissions
        $allowedRoles = ['top-leader', 'admin', 'treasurer', 'regional-treasurer'];
        if (!in_array($user->role, $allowedRoles)) {
            abort(403, 'Unauthorized action.');
        }

        // Regional Treasurer check
        if ($user->role === 'regional-treasurer') {
            if ($loan->user->region !== $user->region) {
                abort(403, 'You can only disburse loans for your region.');
            }
        }

        // Check if loan is approved
        if (!$loan->isApproved()) {
            return redirect()->back()->with('error', 'Only approved loans can be marked as disbursed.');
        }

        // Check if already paid
        if ($loan->isPaid()) {
            return redirect()->back()->with('error', 'This loan has already been disbursed.');
        }

        $request->validate([
            'payment_date' => 'required|date',
            'payment_amount' => 'required|numeric|min:0',
            'payment_method' => 'required|in:cash,bank_transfer,mobile_money',
            'notes' => 'nullable|string|max:1000',
        ]);

        $loan->update([
            'payment_date' => $request->payment_date,
            'payment_amount' => $request->payment_amount,
            'payment_method' => $request->payment_method,
            'notes' => $request->notes,
            'disbursed_by' => auth()->id(),
            'disbursed_at' => now(),
        ]);
        
        // Send disbursement email
        Mail::to($loan->user->email)->send(new LoanDisbursedMail($loan));

        return redirect()->route('loans.show', $loan)->with('success', 'Loan marked as disbursed successfully.');
    }
}
