<?php

namespace App\Http\Controllers\Membership\Public;

use App\Http\Controllers\Controller;
use App\Models\LoanProduct;
use App\Models\MembershipCategory;
use Illuminate\Http\Request;

class LoanProductController extends Controller
{
    /**
     * Display available loan products.
     */
    public function index()
    {
        $products = LoanProduct::active()
            ->ordered()
            ->get();

        $featuredProducts = $products->where('is_featured', true);
        $regularProducts = $products->where('is_featured', false);

        return view('loans.public.index', compact('products', 'featuredProducts', 'regularProducts'));
    }

    /**
     * Display a specific loan product.
     */
    public function show(LoanProduct $loanProduct)
    {
        if (!$loanProduct->is_active) {
            abort(404);
        }

        return view('loans.public.show', compact('loanProduct'));
    }

    /**
     * Calculate loan details via AJAX.
     */
    public function calculate(Request $request, LoanProduct $loanProduct)
    {
        $request->validate([
            'amount' => 'required|numeric|min:' . $loanProduct->min_amount . '|max:' . $loanProduct->max_amount,
            'term_months' => 'required|integer|min:' . $loanProduct->min_term_months . '|max:' . $loanProduct->max_term_months,
        ]);

        $amount = $request->amount;
        $termMonths = $request->term_months;

        $monthlyPayment = $loanProduct->calculateMonthlyPayment($amount, $termMonths);
        $totalInterest = $loanProduct->calculateTotalInterest($amount, $termMonths);
        $totalRepayable = $amount + $totalInterest;
        $processingFee = $loanProduct->calculateProcessingFee($amount);

        return response()->json([
            'success' => true,
            'data' => [
                'amount' => number_format($amount, 2),
                'term_months' => $termMonths,
                'interest_rate' => $loanProduct->interest_rate,
                'monthly_payment' => number_format($monthlyPayment, 2),
                'total_interest' => number_format($totalInterest, 2),
                'total_repayable' => number_format($totalRepayable, 2),
                'processing_fee' => number_format($processingFee, 2),
                'currency' => $loanProduct->currency,
            ],
        ]);
    }
}
