<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\LoanProduct;
use App\Models\LoanTenure;

class LoanProductController extends Controller
{
    public function listLoans()
{
    $products = LoanProduct::with('category')->get();
    $tenures = LoanTenure::all();

    $score = 600;

    $products = LoanProduct::with('category')->whereHas('category', function ($query) use ($score) {
        $query->where('min_score', '<=', $score)->orWhereNull('min_score');
    })->get();

    $data = $products->map(function ($product) use ($tenures) {
        return [
            'id' => $product->id,
            'amount' => $product->amount,
            'interest_percent' => $product->interest_percent,
            'processing_fee_percent' => $product->processing_fee_percent,
            'processing_fee_per_day' => $product->processing_fee_per_day,
            'processing_offer_percent' => $product->processing_offer_percent,
            'protection_fee_percent' => $product->protection_fee_percent,
            'category' => [
                'id' => $product->category?->id,
                'name' => $product->category?->name,
                'min_score' => $product->category?->min_score,
                'max_score' => $product->category?->max_score,
            ],
            'tenures' => collect($product->tenure_ids)
                ->map(function ($tid) use ($tenures) {
                    $tenure = $tenures->firstWhere('id', $tid);
                    return $tenure ? [
                        'id' => $tenure->id,
                        'days' => $tenure->days
                    ] : null;
                })
                ->filter()
                ->values()
        ];
    });

    return response()->json([
        'status' => 'success',
        'data' => $data
    ]);
}




public function viewLoan(Request $request, $id)
{
    $tenureId = $request->get('tenure_id');
    $score = 800; // later: fetch from user profile

    $loan = LoanProduct::with('category')
        ->where('id', $id)
        ->whereHas('category', function ($query) use ($score) {
            $query->where('min_score', '<=', $score)
                  ->orWhereNull('min_score');
        })
        ->firstOrFail();

    // ✅ Check if tenure is valid for this product
    if (!in_array($tenureId, $loan->tenure_ids)) {
        return response()->json([
            'status' => 'error',
            'message' => 'Invalid tenure for this loan product.'
        ], 422);
    }

    $tenure = LoanTenure::findOrFail($tenureId);

    // Base values
    $principal = $loan->amount;
    $days = $tenure->days;

    // Charges
    $processingFee = ($principal * $loan->processing_fee_percent) / 100;

    // Extra ₹1/day if beyond 90 days
    if ($days > 90) {
        $processingFee += ($days - 90) * $loan->processing_fee_per_day;
    }

    // Discount
    $processingFeeDiscount = ($processingFee * $loan->processing_offer_percent) / 100;

    // Actual processing fee after discount
    $actualProcessingFee = $processingFee - $processingFeeDiscount;

    // Protection fee
    $protectionFee = ($principal * $loan->protection_fee_percent) / 100;

    // Disbursement
    $disbursementAmount = $principal - $actualProcessingFee - $protectionFee;

    // 📌 Interest calculation based on monthly rate
    $months = $days / 30; // convert days to months
    $monthlyRate = $loan->interest_percent; // already monthly %
    $interestAmount = ($principal * $monthlyRate / 100) * $months;

    // Total payable
    $totalPayable = $principal + $interestAmount;

    return response()->json([
        'status' => 'success',
        'data' => [
            'id' => $loan->id,
            'principal_amount' => round($principal, 2),
            'tenure_days' => $days,
            'processing_fee' => round($processingFee, 2),
            'processing_fee_discount' => round($processingFeeDiscount, 2),
            'actual_processing_fee' => round($actualProcessingFee, 2),
            'protection_fee' => round($protectionFee, 2),
            'disbursement_amount' => round($disbursementAmount, 2),
            'interest_amount' => round($interestAmount, 2),
            'total_payable' => round($totalPayable, 2),
            'category' => [
                'id' => $loan->category?->id,
                'name' => $loan->category?->name,
                'min_score' => $loan->category?->min_score,
                'max_score' => $loan->category?->max_score,
            ],
            'selected_tenure' => [
                'id' => $tenure->id,
                'days' => $tenure->days,
            ]
        ]
    ]);
}


public function loanInterestDetails(Request $request, $id)
{
    $tenureId = $request->get('tenure_id');

    $loan = LoanProduct::findOrFail($id);
    $tenure = LoanTenure::findOrFail($tenureId);

    $principal = $loan->amount;
    $days = $tenure->days;

    // Months from days
    $months = $days / 30;

    // Interest percent is monthly
    $monthlyRate = $loan->interest_percent;

    // Interest per month (flat interest, not reducing balance)
    $interestPerMonth = round($principal * ($monthlyRate / 100), 2);
    $totalInterest = $interestPerMonth * $months;
    $totalPayable = $principal + $totalInterest;

    // Principal per month
    $monthlyPrincipal = round($principal / $months, 2);
    $remainingBalance = $principal;

    $schedule = [];
    for ($m = 1; $m <= $months; $m++) {
        // Adjust last month to fix rounding issues
        $principalAmount = ($m === $months)
            ? $remainingBalance
            : $monthlyPrincipal;

        $totalPayment = round($principalAmount + $interestPerMonth, 2);
        $remainingBalance = round($remainingBalance - $principalAmount, 2);

        $schedule[] = [
            'month' => $m,
            'principal_amount' => $principalAmount,
            'interest_amount' => $interestPerMonth,
            'total_payment' => $totalPayment,
            'remaining_balance' => max($remainingBalance, 0)
        ];
    }

    return response()->json([
        'status' => 'success',
        'data' => [
            'loan_id' => $loan->id,
            'principal' => $principal,
            'monthly_rate_percent' => $monthlyRate,
            'months' => $months,
            'total_interest' => round($totalInterest, 2),
            'total_payable' => round($totalPayable, 2),
            'schedule' => $schedule
        ]
    ]);
}






}
