<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\IntercompanyLoan;
use App\Models\LoanRepayment;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class LoanController extends Controller
{
    public function index(Request $request)
    {
        $user = $request->user();
        $query = IntercompanyLoan::with(['borrower', 'lender', 'superAdminBankAccount', 'bankAccount']);

        if (!$user->isSuperAdmin()) {
            $query->where('borrower_company_id', $user->company_id);
        }

        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }

        return response()->json(['data' => $query->latest()->get()]);
    }

    public function store(Request $request)
    {
        $user = $request->user();
        if (!$user->company_id) {
            return response()->json(['message' => 'Not associated with a company'], 403);
        }

        // Super Admin cannot request loans (they are the lender)
        if ($user->isSuperAdmin()) {
            return response()->json(['message' => 'Super Admin cannot request loans'], 403);
        }

        $validated = $request->validate([
            'amount'             => 'required|numeric|min:1',
            'interest_rate'      => 'required|numeric|min:0|max:100',
            'term_months'        => 'required|integer|min:1|max:360',
            'purpose'            => 'required|string|max:1000',
            'repayment_schedule' => 'required|in:monthly,quarterly,annually',
            'payment_method'     => 'required|in:bank,cash',
            'bank_account_id'    => 'nullable|integer|exists:bank_accounts,id',
        ]);

        // Validate bank account belongs to borrower company if payment method is bank
        if ($validated['payment_method'] === 'bank') {
            if (!$validated['bank_account_id']) {
                return response()->json(['message' => 'Bank account is required when payment method is bank'], 422);
            }
            $bankAccount = \App\Models\BankAccount::where('id', $validated['bank_account_id'])
                ->where('company_id', $user->company_id)
                ->first();
            if (!$bankAccount) {
                return response()->json(['message' => 'Invalid bank account for your company'], 422);
            }
        }

        // Super Admin is the lender
        $lenderId = null; // No company, Super Admin is lender

        // Calculate total interest using simple interest (aligns with approval calculation)
        $monthlyInterestRate = $validated['interest_rate'] / 100 / 12;
        $totalInterest = round($validated['amount'] * $monthlyInterestRate * $validated['term_months'], 2);
        $totalRepayable = round($validated['amount'] + $totalInterest, 2);

        $expectedDisbursement = now()->toDateString();
        $expectedMaturity     = now()->addMonths((int)$validated['term_months'])->toDateString();

        // Debug: Log what we're actually sending
        \Log::info('Loan creation data:', [
            'validated' => $validated,
            'interest_type' => 'simple',
            'all_data' => [
                'loan_number'         => 'LN-' . date('Y') . '-' . strtoupper(substr(uniqid(), -6)),
                'lender_company_id'   => $lenderId,
                'borrower_company_id' => $user->company_id,
                'principal_amount'    => $validated['amount'],
                'outstanding_balance' => $totalRepayable,
                'interest_rate'       => $validated['interest_rate'],
                'interest_type'       => 'simple',
                'disbursement_date'   => $expectedDisbursement,
                'maturity_date'       => $expectedMaturity,
                'due_date'            => $expectedMaturity,
                'term_months'         => $validated['term_months'],
                'purpose'             => $validated['purpose'],
                'payment_frequency'   => $validated['repayment_schedule'],
                'status'              => 'pending',
                'terms_conditions'    => 'Standard inter-company loan terms',
                'requested_by'        => $user->id,
                'payment_method'      => $validated['payment_method'],
                'bank_account_id'     => $validated['bank_account_id'] ?? null,
                'is_super_admin_lender' => true,
            ]
        ]);

        $loan = IntercompanyLoan::create([
            'loan_number'         => 'LN-' . date('Y') . '-' . strtoupper(substr(uniqid(), -6)),
            'lender_company_id'   => $lenderId,
            'borrower_company_id' => $user->company_id,
            'principal_amount'    => $validated['amount'],
            'outstanding_balance' => $totalRepayable,
            'interest_rate'       => $validated['interest_rate'],
            'interest_type'       => 'simple',
            'disbursement_date'   => $expectedDisbursement,
            'maturity_date'       => $expectedMaturity,
            'due_date'            => $expectedMaturity,
            'term_months'         => $validated['term_months'],
            'purpose'             => $validated['purpose'],
            'payment_frequency'   => $validated['repayment_schedule'],
            'status'              => 'pending',
            'terms_conditions'    => 'Standard inter-company loan terms',
            'requested_by'        => $user->id,
            'payment_method'      => $validated['payment_method'],
            'bank_account_id'     => $validated['bank_account_id'] ?? null,
            'is_super_admin_lender' => true,
        ]);

        return response()->json(['data' => $loan->load(['borrower', 'lender']), 'message' => 'Loan request submitted'], 201);
    }

    public function approve(Request $request, $id)
    {
        $user = $request->user();
        
        // Only Super Admin can approve loans
        if (!$user->isSuperAdmin()) {
            return response()->json(['message' => 'Unauthorized. Only Super Admin can approve loans'], 403);
        }

        $request->validate([
            'payment_method' => 'required|in:bank,cash',
            'bank_account_id' => 'nullable|integer|exists:bank_accounts,id',
            'super_admin_bank_account_id' => 'nullable|integer|exists:super_admin_bank_accounts,id',
        ]);

        $loan = IntercompanyLoan::findOrFail($id);
        if ($loan->status !== 'pending') return response()->json(['message' => 'Not pending'], 400);

        // Validate bank account if payment method is bank
        // Bank account should belong to the borrower company (where money is being deposited)
        if ($request->payment_method === 'bank') {
            if (!$request->bank_account_id) {
                return response()->json(['message' => 'Bank account is required when payment method is bank'], 422);
            }
            $bankAccount = \App\Models\BankAccount::where('id', $request->bank_account_id)
                ->where('company_id', $loan->borrower_company_id)
                ->first();
            if (!$bankAccount) {
                return response()->json(['message' => 'Invalid bank account for borrower company'], 422);
            }
        }

        // ── Super Admin profit/balance check ─────────────────────────────────
        if ($request->payment_method === 'cash') {
            $superAdminFinancial = \App\Models\SuperAdminFinancial::recalculateMonth(now()->format('Y-m'));
            $superAdminProfit = (float) $superAdminFinancial->net_profit;
            $superAdminCash = (float) $superAdminFinancial->cash_balance;
            $available = max($superAdminProfit, $superAdminCash);
            
            if ($available < $loan->principal_amount && $superAdminProfit <= 0) {
                return response()->json([
                    'message' => 'Insufficient profit: Super Admin does not have enough profit to approve this loan. Current profit: ₦' . number_format($superAdminProfit, 2),
                ], 400);
            }
        }
        // ────────────────────────────────────────────────────────────────

        // Calculate total repayable (principal + simple interest over full term)
        $totalInterest   = round($loan->principal_amount * ($loan->interest_rate / 100 / 12) * $loan->term_months, 2);
        $totalRepayable  = round($loan->principal_amount + $totalInterest, 2);

        DB::beginTransaction();
        try {
            $loan->update([
                'status'              => 'approved',
                'approved_at'         => now(),
                'disbursement_date'   => now(),
                'outstanding_balance' => $totalRepayable,
                'payment_method'      => $request->payment_method,
                'bank_account_id'     => $request->bank_account_id,
                'super_admin_bank_account_id' => $request->super_admin_bank_account_id,
            ]);
            $this->generateRepayments($loan);

            // ── Update balances based on payment method ─────────────────
            $amount   = (float) $loan->principal_amount;
            $borrower = \App\Models\Company::find($loan->borrower_company_id)?->fresh();

            if ($request->payment_method === 'cash') {
                // Cash payment: deduct from Super Admin profit, add to borrower cash
                $superAdminFinancial = \App\Models\SuperAdminFinancial::recalculateMonth(now()->format('Y-m'));
                $superAdminFinancial->cash_balance = max(0, $superAdminFinancial->cash_balance - $amount);
                $superAdminFinancial->save();
                
                if ($borrower) {
                    $borrowerOldCash = (float)($borrower->getAttributes()['cash_balance'] ?? 0);
                    $borrower->update(['cash_balance' => $borrowerOldCash + $amount]);
                }
            } elseif ($request->payment_method === 'bank') {
                // Bank payment: debit Super Admin bank account, credit borrower bank account
                if ($request->super_admin_bank_account_id) {
                    $superAdminBank = \App\Models\SuperAdminBankAccount::find($request->super_admin_bank_account_id);
                    if ($superAdminBank) {
                        $superAdminBank->debit($amount);
                    }
                }
                
                // Credit borrower's bank account
                $bankAccount = \App\Models\BankAccount::find($request->bank_account_id);
                if ($bankAccount) {
                    $bankAccount->credit($amount);
                }
            }
            // ────────────────────────────────────────────────────────────────

            // ── Update borrower's monthly financials to include loan disbursement in revenue ──
            try {
                $disbursementMonth = \Carbon\Carbon::parse($loan->disbursement_date ?? now())->format('Y-m');
                \App\Models\MonthlyCompanyFinancial::recalculateMonth($loan->borrower_company_id, $disbursementMonth);
            } catch (\Exception $e) {
                // Log silently; don't fail the loan approval
            }
            // ───────────────────────────────────────────────────────────────────────────────

            // ── Update linked invoice status to paid if exists ──
            try {
                $linkedInvoice = \App\Models\Invoice::where('loan_id', $loan->id)->first();
                if ($linkedInvoice && $linkedInvoice->status !== 'paid') {
                    $linkedInvoice->update([
                        'status' => 'paid',
                        'paid_amount' => $linkedInvoice->total_amount,
                        'balance' => 0,
                    ]);
                }
            } catch (\Exception $e) {
                // Log silently; don't fail the loan approval
            }
            // ─────────────────────────────────────────────────

            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['message' => $e->getMessage()], 500);
        }

        // ── Financial logs (outside transaction so a schema issue never blocks approval) ──
        try {
            $note = "Intercompany loan #{$loan->loan_number} approved";
            $now  = now();
            $hasCol = \Illuminate\Support\Facades\Schema::hasColumn('company_financial_logs', 'report_period');
            // Ensure variables exist to avoid undefined variable notices
            $lender = $lender ?? null;
            $lenderOldCash = $lenderOldCash ?? null;
            $lenderNewCash = $lenderNewCash ?? null;
            $borrowerOldCash = $borrowerOldCash ?? null;
            $borrowerNewCash = $borrowerNewCash ?? null;

            if ($lender) {
                $row = [
                    'company_id'      => $lender->id,
                    'field_name'      => 'cash_balance',
                    'old_value'       => $lenderOldCash,
                    'new_value'       => $lenderNewCash,
                    'changed_by'      => $user->id,
                    'changed_by_name' => $user->name,
                    'ip_address'      => request()->ip(),
                    'notes'           => $note . ' — disbursed to borrower',
                    'created_at'      => $now,
                    'updated_at'      => $now,
                ];
                if ($hasCol) $row['report_period'] = 'monthly';
                DB::table('company_financial_logs')->insert($row);
            }
            if ($borrower ?? false) {
                $row = [
                    'company_id'      => $borrower->id,
                    'field_name'      => 'cash_balance',
                    'old_value'       => $borrowerOldCash,
                    'new_value'       => $borrowerNewCash,
                    'changed_by'      => $user->id,
                    'changed_by_name' => $user->name,
                    'ip_address'      => request()->ip(),
                    'notes'           => $note . ' — funds received from lender',
                    'created_at'      => $now,
                    'updated_at'      => $now,
                ];
                if ($hasCol) $row['report_period'] = 'monthly';
                DB::table('company_financial_logs')->insert($row);
            }
        } catch (\Exception $e) {
            // Log silently; don't fail the response
        }
        // ────────────────────────────────────────────────────────────────

        return response()->json(['data' => $loan->fresh()->load(['borrower','lender']), 'message' => 'Loan approved and financials updated']);
    }

    public function reject(Request $request, $id)
    {
        $user = $request->user();
        if (!$user->hasRole('Super Admin')) {
            return response()->json(['message' => 'Unauthorized'], 403);
        }

        $validated = $request->validate(['reason' => 'required|string|max:1000']);
        $loan = IntercompanyLoan::findOrFail($id);
        if ($loan->status !== 'pending') return response()->json(['message' => 'Not pending'], 400);

        $loan->update(['status' => 'rejected', 'rejection_reason' => $validated['reason'], 'rejected_by' => $user->id, 'rejected_at' => now()]);
        return response()->json(['data' => $loan, 'message' => 'Loan rejected']);
    }

    public function repayments($id)
    {
        $loan = IntercompanyLoan::findOrFail($id);
        $repayments = LoanRepayment::where('loan_id', $id)
            ->orderBy('due_date')
            ->get()
            ->map(function ($r) {
                // Auto-flag overdue
                if ($r->status === 'scheduled' && $r->due_date && now()->gt($r->due_date)) {
                    $r->status = 'overdue';
                }
                return $r;
            });
        return response()->json(['data' => $repayments]);
    }

    public function confirmRepayment(Request $request, $repaymentId)
    {
        $user = $request->user();
        $repayment = LoanRepayment::findOrFail($repaymentId);
        $loan = \App\Models\IntercompanyLoan::findOrFail($repayment->loan_id);

        if (!$user->isSuperAdmin() && $user->company_id !== $loan->lender_company_id) {
            return response()->json(['message' => 'Unauthorized – only the lending company can confirm'], 403);
        }
        if ($repayment->status !== 'pending_confirmation') {
            return response()->json(['message' => 'This repayment is not awaiting confirmation'], 400);
        }

        
        $validated = $request->validate([
            'receipt' => 'nullable|file|mimes:pdf,jpg,jpeg,png|max:2048',
            'bank_account_id' => 'nullable|integer|exists:bank_accounts,id',
            'super_admin_bank_account_id' => 'nullable|integer|exists:super_admin_bank_accounts,id',
        ]);

        $receiptPath = null;
        if ($request->hasFile('receipt')) {
            $receiptPath = $request->file('receipt')->store('loan_receipts', 'public');
        }

        // ── Process bank account transfers when repayment is confirmed ──
        \Log::info('Loan repayment confirmation - processing bank account transfers', [
            'repayment_id' => $repayment->id,
            'amount' => $repayment->total_amount,
            'is_super_admin_lender' => $loan->is_super_admin_lender,
            'borrower_bank_account_id' => $repayment->bank_account_id,
            'super_admin_bank_account_id' => $repayment->super_admin_bank_account_id
        ]);

        DB::beginTransaction();
        try {
            // Persist any supplied accounts / receipt from confirmation
            $repaymentUpdates = [];
            if (!empty($validated['bank_account_id'])) {
                $repaymentUpdates['bank_account_id'] = $validated['bank_account_id'];
            }
            if (!empty($validated['super_admin_bank_account_id'])) {
                $repaymentUpdates['super_admin_bank_account_id'] = $validated['super_admin_bank_account_id'];
            }
            if ($receiptPath) {
                $repaymentUpdates['receipt_path'] = $receiptPath;
            }
            if (!empty($repaymentUpdates)) {
                $repayment->update($repaymentUpdates);
            }

            // Refresh repayment data after possible updates
            $repayment->refresh();
            if ($loan->is_super_admin_lender) {
                // Company paying back to group holding company
                
                // 1. Validate and debit from company's bank account (money leaving company)
                if ($repayment->bank_account_id) {
                    $borrowerBankAccount = \App\Models\BankAccount::find($repayment->bank_account_id);
                    \Log::info('Borrower bank before debit', ['id' => $borrowerBankAccount?->id, 'balance' => $borrowerBankAccount?->current_balance]);
                    if (!$borrowerBankAccount) {
                        DB::rollBack();
                        return response()->json(['message' => 'Company bank account not found'], 422);
                    }
                    
                    if ($borrowerBankAccount->current_balance < $repayment->total_amount) {
                        DB::rollBack();
                        return response()->json([
                            'message' => 'Insufficient funds in company bank account',
                            'details' => [
                                'account_name' => $borrowerBankAccount->account_name,
                                'current_balance' => $borrowerBankAccount->current_balance,
                                'required_amount' => $repayment->total_amount
                            ]
                        ], 422);
                    }
                    
                    $borrowerBankAccount->debit($repayment->total_amount);
                    \Log::info('Borrower bank after debit', ['id' => $borrowerBankAccount->id, 'balance' => $borrowerBankAccount->current_balance]);
                }
                
                // 2. Credit to group holding bank account (money received by holding company)
                // Use account from repayment record, or from confirmation request if super admin is providing it now
                $targetHoldingAccountId = $repayment->super_admin_bank_account_id 
                    ?? ($validated['super_admin_bank_account_id'] ?? null);
                
                if ($targetHoldingAccountId) {
                    $holdingBankAccount = \App\Models\SuperAdminBankAccount::find($targetHoldingAccountId);
                    \Log::info('Holding bank before credit', ['id' => $holdingBankAccount?->id, 'balance' => $holdingBankAccount?->current_balance, 'source' => $repayment->super_admin_bank_account_id ? 'repayment_record' : 'confirmation_request']);
                    if (!$holdingBankAccount) {
                        DB::rollBack();
                        return response()->json(['message' => 'Group holding bank account not found'], 422);
                    }
                    
                    // Save the account ID to repayment record if it came from confirmation request
                    if (!$repayment->super_admin_bank_account_id) {
                        $repayment->update(['super_admin_bank_account_id' => $targetHoldingAccountId]);
                    }
                    
                    $holdingBankAccount->credit($repayment->total_amount);
                    \Log::info('Holding bank after credit', ['id' => $holdingBankAccount->id, 'balance' => $holdingBankAccount->current_balance]);
                } else {
                    DB::rollBack();
                    return response()->json(['message' => 'No super admin bank account selected for repayment. Please select a holding account.'], 422);
                }
            } else {
                // Company-to-company loan repayment (not super admin lender)
                // Validate and debit from company's bank account
                if ($repayment->bank_account_id) {
                    $borrowerBankAccount = \App\Models\BankAccount::find($repayment->bank_account_id);
                    if (!$borrowerBankAccount) {
                        DB::rollBack();
                        return response()->json(['message' => 'Company bank account not found'], 422);
                    }
                    
                    if ($borrowerBankAccount->current_balance < $repayment->total_amount) {
                        DB::rollBack();
                        return response()->json([
                            'message' => 'Insufficient funds in company bank account',
                            'details' => [
                                'account_name' => $borrowerBankAccount->account_name,
                                'current_balance' => $borrowerBankAccount->current_balance,
                                'required_amount' => $repayment->total_amount
                            ]
                        ], 422);
                    }
                    
                    $borrowerBankAccount->debit($repayment->total_amount);
                }
                
                // Credit to lender company's bank account
                if ($repayment->bank_account_id && $loan->lender_company_id) {
                    $lenderBankAccount = \App\Models\BankAccount::where('company_id', $loan->lender_company_id)
                        ->where('is_primary', true)
                        ->first();
                        
                    if ($lenderBankAccount) {
                        $lenderBankAccount->credit($repayment->total_amount);
                    }
                }
            }
            
            // Mark repayment as paid and record confirmer
            $repayment->update([
                'status'       => 'paid',
                'paid_at'      => now(),
                'confirmed_by' => $user->id,
                'confirmed_at' => now(),
            ]);
            
            // Reduce loan outstanding balance
            $newBalance = max(0, $loan->outstanding_balance - $repayment->total_amount);
            $loan->update([
                'outstanding_balance' => $newBalance,
                'status' => $newBalance <= 0 ? 'paid_off' : $loan->status,
            ]);
            
            // Mark matching scheduled repayment(s) as paid
            $remaining = $repayment->total_amount;
            $scheduled = LoanRepayment::where('loan_id', $loan->id)
                ->whereIn('status', ['scheduled', 'overdue'])
                ->where('payment_number', 'like', 'SCH-%')
                ->orderBy('due_date')
                ->get();
            foreach ($scheduled as $sch) {
                if ($remaining <= 0) break;
                if ($sch->total_amount <= $remaining + 0.01) {
                    $sch->update(['status' => 'paid', 'paid_at' => now()]);
                    $remaining -= $sch->total_amount;
                } else {
                    break;
                }
            }
            
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            \Log::error('Bank transfer failed during repayment confirmation', [
                'error' => $e->getMessage(),
                'repayment_id' => isset($repayment) ? $repayment->id : null
            ]);
            return response()->json(['message' => 'Bank transfer failed: ' . $e->getMessage()], 500);
        }
        // ────────────────────────────────────────────────────────────────────────

        // ── Update borrower's monthly financials to deduct repayment from net profit ──
        try {
            $repaymentMonth = isset($repayment) ? \Carbon\Carbon::parse($repayment->paid_at ?? now())->format('Y-m') : now()->format('Y-m');
            \App\Models\MonthlyCompanyFinancial::recalculateMonth($loan->borrower_company_id, $repaymentMonth);
        } catch (\Exception $e) {
            // Log silently; don't fail the repayment confirmation
        }
        // ───────────────────────────────────────────────────────────────────────────

        try {
            activity()->causedBy($user)->performedOn($loan)
                ->withProperties(['amount' => $repayment->total_amount, 'ip_address' => $request->ip()])
                ->log('Loan repayment confirmed by lender');
        } catch (\Exception $e) {}

        return response()->json(['data' => $repayment->fresh(), 'message' => 'Repayment confirmed – balance updated']);
    }

    public function rejectRepayment(Request $request, $repaymentId)
    {
        $user = $request->user();
        $repayment = LoanRepayment::findOrFail($repaymentId);
        $loan = \App\Models\IntercompanyLoan::findOrFail($repayment->loan_id);

        if (!$user->isSuperAdmin() && $user->company_id !== $loan->lender_company_id) {
            return response()->json(['message' => 'Unauthorized'], 403);
        }
        $request->validate(['reason' => 'nullable|string|max:500']);
        $repayment->update(['status' => 'scheduled', 'notes' => ($repayment->notes ? $repayment->notes . ' | ' : '') . 'Rejected: ' . ($request->reason ?? 'No reason given')]);
        return response()->json(['message' => 'Repayment rejected – borrower must resubmit']);
    }

    public function repay(Request $request, $id)
    {
        $user = $request->user();
        $loan = IntercompanyLoan::findOrFail($id);

        if (!$user->isSuperAdmin() && $user->company_id !== $loan->borrower_company_id) {
            return response()->json(['message' => 'Unauthorized'], 403);
        }

        $validated = $request->validate([
            'amount'           => 'required|numeric|min:1',
            'payment_date'     => 'nullable|date',
            'payment_method'   => 'nullable|string|max:50',
            'reference_number' => 'nullable|string|max:255',
            'notes'            => 'nullable|string|max:1000',
            'receipt'          => 'nullable|file|mimes:pdf,jpg,jpeg,png|max:5120',
            'bank_account_id'  => 'required|integer|exists:bank_accounts,id',
            'super_admin_bank_account_id' => 'nullable|integer|exists:super_admin_bank_accounts,id',
        ]);

        // Validate bank account belongs to company
        $bankAccount = \App\Models\BankAccount::where('id', $validated['bank_account_id'])
            ->where('company_id', $user->company_id)
            ->first();
        if (!$bankAccount) {
            return response()->json(['message' => 'Invalid bank account for your company'], 422);
        }

        $amount = $validated['amount'];
    \Log::info('Loan repay submitted', ['loan_id' => $loan->id, 'borrower_company' => $loan->borrower_company_id, 'amount' => $amount, 'bank_account_id' => $validated['bank_account_id'], 'super_admin_bank_account_id' => $validated['super_admin_bank_account_id'] ?? null, 'user_id' => $user->id]);
        if ($amount > $loan->outstanding_balance) {
            return response()->json(['message' => 'Amount exceeds outstanding balance of ₦' . number_format($loan->outstanding_balance, 2)], 400);
        }

        // Calculate principal and interest portions
        // Simple interest: total interest = principal * rate * time
        // For partial repayments, we calculate interest based on remaining balance
        $totalInterest = $loan->principal_amount * ($loan->interest_rate / 100 / 12) * $loan->term_months;
        $totalRepayable = $loan->principal_amount + $totalInterest;
        
        // Calculate the interest portion of this payment
        // Proportional to total interest vs total repayable
        $interestPortion = ($amount / $totalRepayable) * $totalInterest;
        $principalPortion = $amount - $interestPortion;

        $newBalance = $loan->outstanding_balance - $amount;

        $payDate = $validated['payment_date'] ?? now()->toDateString();
        $repayData = [
            'loan_id'          => $loan->id,
            'payment_number'   => 'PAY-' . strtoupper(uniqid()),
            'payment_date'     => $payDate,
            'due_date'         => $payDate,
            'total_amount'     => $amount,
            'principal_amount' => $principalPortion,
            'interest_amount'  => $interestPortion,
            'payment_method'   => $validated['payment_method'] ?? 'bank_transfer',
            'reference_number' => $validated['reference_number'] ?? null,
            'notes'            => $validated['notes'] ?? null,
            'status'           => 'pending_confirmation',
            'paid_by'          => $user->id,
            'bank_account_id'  => $validated['bank_account_id'],
            'super_admin_bank_account_id' => $validated['super_admin_bank_account_id'] ?? null,
        ];

        if ($request->hasFile('receipt')) {
            $repayData['receipt_path'] = $request->file('receipt')->store('loan_receipts', 'public');
        }

        $repayment = LoanRepayment::create($repayData);
        // Balance is NOT updated here — only after lender confirms

        try {
            activity()
                ->causedBy($user)
                ->performedOn($loan)
                ->withProperties(['total_amount' => $amount, 'method' => $validated['payment_method'] ?? null, 'reference' => $validated['reference_number'] ?? null, 'ip_address' => $request->ip()])
                ->log('Loan repayment submitted – awaiting lender confirmation');
        } catch (\Exception $e) {}

        return response()->json(['data' => $loan->fresh(), 'repayment' => $repayment, 'message' => 'Repayment submitted – awaiting confirmation from lender']);
    }

    private function generateRepayments($loan)
    {
        $monthlyInterestRate = $loan->interest_rate / 100 / 12;
        $remainingBalance = $loan->principal_amount;
        $monthlyPayment = $loan->principal_amount / $loan->term_months;

        for ($i = 1; $i <= $loan->term_months; $i++) {
            // Calculate interest on remaining balance
            $interestAmount = $remainingBalance * $monthlyInterestRate;
            
            // Principal portion is fixed, interest varies with remaining balance
            $totalAmount = $monthlyPayment + $interestAmount;
            
            LoanRepayment::create([
                'loan_id'          => $loan->id,
                'payment_number'   => 'SCH-' . $loan->id . '-' . str_pad($i, 3, '0', STR_PAD_LEFT),
                'payment_date'     => now()->addMonths($i)->toDateString(),
                'due_date'         => now()->addMonths($i)->toDateString(),
                'total_amount'     => round($totalAmount, 2),
                'principal_amount' => round($monthlyPayment, 2),
                'interest_amount'  => round($interestAmount, 2),
                'status'           => 'scheduled',
            ]);
            
            // Reduce remaining balance for next iteration
            $remainingBalance -= $monthlyPayment;
        }
    }
}
