<?php $__env->startSection('title', 'নতুন ঋণ আবেদন'); ?>

<?php $__env->startSection('content'); ?>
<div class="container-fluid">
    <nav aria-label="breadcrumb">
        <ol class="breadcrumb">
            <li class="breadcrumb-item"><a href="<?php echo e(route('dashboard')); ?>">ড্যাশবোর্ড</a></li>
            <li class="breadcrumb-item"><a href="<?php echo e(route('loans.index')); ?>">ঋণ তালিকা</a></li>
            <li class="breadcrumb-item active" aria-current="page">নতুন ঋণ আবেদন</li>
        </ol>
    </nav>
    
    <div class="card shadow">
        <div class="card-header py-3">
            <h6 class="m-0 font-weight-bold">নতুন ঋণ আবেদন</h6>
            <p class="text-sm text-success mb-0">সকল ঋণ ৩ মাসের জন্য। প্রতি মাস ৬% হারে মুনাফা।</p>
        </div>
        <div class="card-body">
            <?php if($errors->any()): ?>
            <div class="alert alert-danger">
                <ul class="mb-0">
                    <?php $__currentLoopData = $errors->all(); $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $error): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                    <li><?php echo e($error); ?></li>
                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                </ul>
            </div>
            <?php endif; ?>
            
            <form method="POST" action="<?php echo e(route('loans.store')); ?>" id="loanForm">
                <?php echo csrf_field(); ?>
                
                <!-- Hidden field for duration (always 3 months) -->
                <input type="hidden" name="duration_months" value="3">
                
                <div class="row g-3">
                    <!-- Member Selection -->
                    <div class="col-md-6">
                        <label for="member_id" class="form-label">সদস্য নির্বাচন *</label>
                        <select class="form-select <?php $__errorArgs = ['member_id'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>" id="member_id" name="member_id" required>
                            <option value="">সদস্য নির্বাচন করুন</option>
                            <?php $__currentLoopData = $members ?? []; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $member): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                            <?php
                                $currentLoan = $member->loans()
                                    ->whereIn('status', ['approved', 'disbursed', 'active'])
                                    ->sum('loan_amount');
                                $loanLimit = $member->loan_limit ?? 500000;
                                $availableLimit = max(0, $loanLimit - $currentLoan);
                            ?>
                            <option value="<?php echo e($member->member_id); ?>" 
                                    <?php echo e(old('member_id') == $member->member_id ? 'selected' : ''); ?>

                                    data-loan-limit="<?php echo e($loanLimit); ?>"
                                    data-current-loan="<?php echo e($currentLoan); ?>"
                                    data-available-limit="<?php echo e($availableLimit); ?>">
                                <?php echo e($member->member_id); ?> - <?php echo e($member->name); ?> (<?php echo e($member->phone); ?>)
                                <?php if($availableLimit < 1000): ?>
                                    - ঋণ সীমা অতিক্রম
                                <?php endif; ?>
                            </option>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                        </select>
                        <?php $__errorArgs = ['member_id'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                            <div class="invalid-feedback"><?php echo e($message); ?></div>
                        <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                        <div id="member_loan_info" class="mt-2 small" style="display: none;">
                            <!-- মেম্বার লোন তথ্য এখানে দেখানো হবে -->
                        </div>
                    </div>
                    
                    <!-- Loan Type -->
                    <div class="col-md-6">
                        <label for="loan_type" class="form-label">ঋণের ধরন *</label>
                        <select class="form-select <?php $__errorArgs = ['loan_type'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>" id="loan_type" name="loan_type" required>
                            <option value="">ঋণের ধরন নির্বাচন করুন</option>
                            <option value="regular" <?php echo e(old('loan_type') == 'regular' ? 'selected' : ''); ?>>নিয়মিত</option>
                            <option value="emergency" <?php echo e(old('loan_type') == 'emergency' ? 'selected' : ''); ?>>জরুরী</option>
                            <option value="business" <?php echo e(old('loan_type') == 'business' ? 'selected' : ''); ?>>ব্যবসায়িক</option>
                            <option value="agriculture" <?php echo e(old('loan_type') == 'agriculture' ? 'selected' : ''); ?>>কৃষি</option>
                            <option value="education" <?php echo e(old('loan_type') == 'education' ? 'selected' : ''); ?>>শিক্ষা</option>
                            <option value="medical" <?php echo e(old('loan_type') == 'medical' ? 'selected' : ''); ?>>চিকিৎসা</option>
                            <option value="housing" <?php echo e(old('loan_type') == 'housing' ? 'selected' : ''); ?>>গৃহ নির্মাণ</option>
                            <option value="vehicle" <?php echo e(old('loan_type') == 'vehicle' ? 'selected' : ''); ?>>যানবাহন</option>
                        </select>
                        <?php $__errorArgs = ['loan_type'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                            <div class="invalid-feedback"><?php echo e($message); ?></div>
                        <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                    </div>
                    
                    <!-- Loan Amount -->
                    <div class="col-md-6">
                        <label for="loan_amount" class="form-label">ঋণের পরিমাণ *</label>
                        <div class="input-group">
                            <input type="number" class="form-control <?php $__errorArgs = ['loan_amount'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>" 
                                   id="loan_amount" name="loan_amount" 
                                   value="<?php echo e(old('loan_amount')); ?>" 
                                   min="1000" 
                                   max="500000" 
                                   step="500" 
                                   required
                                   data-available-limit="500000">
                            <span class="input-group-text">৳</span>
                        </div>
                        <small class="text-muted">সর্বনিম্ন ১,০০০৳ এবং সর্বোচ্চ ৫,০০,০০০৳</small>
                        <?php $__errorArgs = ['loan_amount'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                            <div class="invalid-feedback"><?php echo e($message); ?></div>
                        <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                    </div>
                    
                    <!-- Interest Rate (Fixed at 6%) -->
                    <div class="col-md-6">
                        <label for="interest_rate" class="form-label">সুদের হার (%) *</label>
                        <div class="input-group">
                            <input type="number" class="form-control <?php $__errorArgs = ['interest_rate'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>" 
                                   id="interest_rate" name="interest_rate" 
                                   value="6" min="6" max="6" step="0.01" required readonly 
                                   style="background-color: #f8f9fa;">
                            <span class="input-group-text">%</span>
                        </div>
                        <small class="text-success">সুদ হার স্থির (৬%)</small>
                        <?php $__errorArgs = ['interest_rate'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                            <div class="invalid-feedback"><?php echo e($message); ?></div>
                        <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                    </div>
                    
                    <!-- Duration Display (Fixed at 3 months) -->
                    <div class="col-md-6">
                        <label class="form-label">ঋণের মেয়াদ *</label>
                        <div class="form-control" style="background-color: #f8f9fa;">
                            <strong>৩ মাস</strong>
                        </div>
                        <small class="text-success">সকল ঋণ ৩ মাসের জন্য</small>
                    </div>
                    
                    <!-- Purpose -->
                    <div class="col-md-6">
                        <label for="purpose" class="form-label">ঋণের উদ্দেশ্য *</label>
                        <textarea class="form-control <?php $__errorArgs = ['purpose'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>" 
                                  id="purpose" name="purpose" rows="3" required><?php echo e(old('purpose')); ?></textarea>
                        <?php $__errorArgs = ['purpose'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                            <div class="invalid-feedback"><?php echo e($message); ?></div>
                        <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                    </div>
                    
                    <!-- Loan Date -->
                    <div class="col-md-6">
                        <label for="loan_date" class="form-label">ঋণের তারিখ *</label>
                        <input type="date" class="form-control <?php $__errorArgs = ['loan_date'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>" 
                               id="loan_date" name="loan_date" 
                               value="<?php echo e(old('loan_date', date('Y-m-d'))); ?>" required>
                        <?php $__errorArgs = ['loan_date'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                            <div class="invalid-feedback"><?php echo e($message); ?></div>
                        <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                    </div>
                    
                    <!-- Guarantor 1 -->
                    <div class="col-md-6">
                        <label for="guarantor1_id" class="form-label">১ম গ্যারান্টর *</label>
                        <select class="form-select <?php $__errorArgs = ['guarantor1_id'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>" 
                                id="guarantor1_id" name="guarantor1_id" required>
                            <option value="">গ্যারান্টর নির্বাচন করুন</option>
                            <?php $__currentLoopData = $guarantors ?? []; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $guarantor): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                            <option value="<?php echo e($guarantor->member_id); ?>" 
                                    <?php echo e(old('guarantor1_id') == $guarantor->member_id ? 'selected' : ''); ?>>
                                <?php echo e($guarantor->member_id); ?> - <?php echo e($guarantor->name); ?>

                            </option>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                        </select>
                        <?php $__errorArgs = ['guarantor1_id'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                            <div class="invalid-feedback"><?php echo e($message); ?></div>
                        <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                    </div>
                    
                    <!-- Guarantor 2 -->
                    <div class="col-md-6">
                        <label for="guarantor2_id" class="form-label">২য় গ্যারান্টর *</label>
                        <select class="form-select <?php $__errorArgs = ['guarantor2_id'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>" 
                                id="guarantor2_id" name="guarantor2_id" required>
                            <option value="">গ্যারান্টর নির্বাচন করুন</option>
                            <?php $__currentLoopData = $guarantors ?? []; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $guarantor): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                            <option value="<?php echo e($guarantor->member_id); ?>" 
                                    <?php echo e(old('guarantor2_id') == $guarantor->member_id ? 'selected' : ''); ?>>
                                <?php echo e($guarantor->member_id); ?> - <?php echo e($guarantor->name); ?>

                            </option>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                        </select>
                        <?php $__errorArgs = ['guarantor2_id'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                            <div class="invalid-feedback"><?php echo e($message); ?></div>
                        <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                    </div>
                    
                    <!-- Notes -->
                    <div class="col-12">
                        <label for="notes" class="form-label">মন্তব্য (যদি থাকে)</label>
                        <textarea class="form-control <?php $__errorArgs = ['notes'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>" 
                                  id="notes" name="notes" rows="2"><?php echo e(old('notes')); ?></textarea>
                        <?php $__errorArgs = ['notes'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                            <div class="invalid-feedback"><?php echo e($message); ?></div>
                        <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                    </div>
                </div>
                
                <!-- Calculation Preview -->
                <div class="alert alert-info mt-3" id="calculationPreview" style="display: none;">
                    <h6 class="fw-bold">আনুমানিক হিসাব (৩ মাসের জন্য):</h6>
                    <div class="row">
                        <div class="col-md-3">
                            <strong>ঋণের পরিমাণ:</strong> <span id="previewLoanAmount">0.00</span> ৳
                        </div>
                        <div class="col-md-3">
                            <strong>মাসিক সুদ:</strong> <span id="previewMonthlyInterest">0.00</span> ৳
                        </div>
                        <div class="col-md-3">
                            <strong>মোট সুদ:</strong> <span id="previewTotalInterest">0.00</span> ৳
                        </div>
                        <div class="col-md-3">
                            <strong>মোট পরিশোধযোগ্য:</strong> <span id="previewTotalPayable">0.00</span> ৳
                        </div>
                    </div>
                    <hr>
                    <h6 class="fw-bold mt-2">কিস্তি পরিশোধ সিডিউল:</h6>
                    <div class="table-responsive">
                        <table class="table table-sm table-bordered">
                            <thead>
                                <tr>
                                    <th>কিস্তি নং</th>
                                    <th>তারিখ</th>
                                    <th>কিস্তির ধরন</th>
                                    <th>পরিমাণ</th>
                                </tr>
                            </thead>
                            <tbody id="installmentSchedule">
                                <!-- কিস্তি তথ্য এখানে দেখানো হবে -->
                            </tbody>
                        </table>
                    </div>
                </div>
                
                <div class="mt-4">
                    <button type="submit" class="btn btn-primary" id="submitBtn">
                        <i class="fas fa-save me-1"></i>ঋণ আবেদন জমা দিন
                    </button>
                    <a href="<?php echo e(route('loans.index')); ?>" class="btn btn-secondary">
                        <i class="fas fa-times me-1"></i>বাতিল
                    </a>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const loanAmount = document.getElementById('loan_amount');
    const interestRate = document.getElementById('interest_rate');
    const loanDate = document.getElementById('loan_date');
    const memberSelect = document.getElementById('member_id');
    const calculationPreview = document.getElementById('calculationPreview');
    const memberLoanInfo = document.getElementById('member_loan_info');
    const submitBtn = document.getElementById('submitBtn');
    
    // Elements to show calculation
    const previewLoanAmount = document.getElementById('previewLoanAmount');
    const previewMonthlyInterest = document.getElementById('previewMonthlyInterest');
    const previewTotalInterest = document.getElementById('previewTotalInterest');
    const previewTotalPayable = document.getElementById('previewTotalPayable');
    const installmentSchedule = document.getElementById('installmentSchedule');
    
    // Member loan limit info
    if (memberSelect) {
        memberSelect.addEventListener('change', function() {
            const selectedOption = this.options[this.selectedIndex];
            if (selectedOption.value) {
                const loanLimit = parseFloat(selectedOption.getAttribute('data-loan-limit')) || 0;
                const currentLoan = parseFloat(selectedOption.getAttribute('data-current-loan')) || 0;
                const availableLimit = parseFloat(selectedOption.getAttribute('data-available-limit')) || 0;
                
                memberLoanInfo.style.display = 'block';
                
                if (availableLimit < 1000) {
                    // If available limit is less than minimum loan amount
                    memberLoanInfo.innerHTML = `
                        <div class="alert alert-warning p-2 mb-2">
                            <i class="fas fa-exclamation-triangle me-1"></i>
                            এই সদস্যের ঋণ নেওয়ার আর সীমা নেই।
                        </div>
                        <div class="small">
                            <span class="text-muted">সর্বোচ্চ ঋণ সীমা: ${formatNumber(loanLimit)} ৳</span><br>
                            <span class="text-muted">বর্তমান ঋণ: ${formatNumber(currentLoan)} ৳</span><br>
                            <span class="text-danger fw-bold">প্রাপ্তব্য সীমা: ${formatNumber(availableLimit)} ৳</span>
                        </div>
                    `;
                    
                    // Disable loan amount input and submit button
                    loanAmount.disabled = true;
                    submitBtn.disabled = true;
                    loanAmount.value = '';
                    loanAmount.setAttribute('title', 'ঋণ সীমা অতিক্রম করেছে');
                    loanAmount.setAttribute('max', '500000'); // Set max to default
                    loanAmount.setAttribute('data-available-limit', availableLimit);
                    
                    // Hide calculation preview
                    calculationPreview.style.display = 'none';
                } else {
                    memberLoanInfo.innerHTML = `
                        <div class="small">
                            <span class="text-success">সর্বোচ্চ ঋণ সীমা: ${formatNumber(loanLimit)} ৳</span><br>
                            <span class="text-info">বর্তমান ঋণ: ${formatNumber(currentLoan)} ৳</span><br>
                            <span class="text-primary fw-bold">প্রাপ্তব্য সীমা: ${formatNumber(availableLimit)} ৳</span>
                        </div>
                    `;
                    
                    // Enable loan amount input and submit button
                    loanAmount.disabled = false;
                    submitBtn.disabled = false;
                    
                    // Calculate maximum allowed loan amount
                    const maxAllowed = Math.min(500000, availableLimit);
                    
                    // Update max attribute only if available limit is at least 1000
                    if (maxAllowed >= 1000) {
                        loanAmount.max = maxAllowed;
                        loanAmount.setAttribute('title', `সর্বোচ্চ: ${formatNumber(maxAllowed)} ৳`);
                    } else {
                        loanAmount.max = 500000; // Set to default max
                        loanAmount.setAttribute('title', 'ঋণ সীমা অতিক্রম করেছে');
                    }
                    
                    // Store available limit in data attribute
                    loanAmount.setAttribute('data-available-limit', maxAllowed);
                    
                    // Calculate loan details
                    calculateLoanDetails();
                }
            } else {
                memberLoanInfo.style.display = 'none';
                loanAmount.disabled = false;
                submitBtn.disabled = false;
                loanAmount.max = 500000;
                loanAmount.removeAttribute('title');
                loanAmount.setAttribute('data-available-limit', 500000);
                calculationPreview.style.display = 'none';
            }
        });
    }
    
    // Function to format numbers
    function formatNumber(num) {
        return parseFloat(num).toLocaleString('en-BD', {
            minimumFractionDigits: 2,
            maximumFractionDigits: 2
        });
    }
    
    // Function to calculate loan details according to your business rules
    function calculateLoanDetails() {
        if (loanAmount.value && interestRate.value && loanDate.value) {
            const principal = parseFloat(loanAmount.value);
            const rate = parseFloat(interestRate.value);
            const months = 3; // Fixed at 3 months
            
            // Calculate monthly interest (6% of principal)
            const monthlyInterest = (principal * rate) / 100;
            
            // Calculate total interest for 3 months
            const totalInterest = monthlyInterest * months;
            
            // Calculate total payable
            const totalPayable = principal + totalInterest;
            
            // Update preview
            previewLoanAmount.textContent = formatNumber(principal);
            previewMonthlyInterest.textContent = formatNumber(monthlyInterest);
            previewTotalInterest.textContent = formatNumber(totalInterest);
            previewTotalPayable.textContent = formatNumber(totalPayable);
            
            // Generate installment schedule
            generateInstallmentSchedule(principal, monthlyInterest);
            
            // Show preview
            calculationPreview.style.display = 'block';
        } else {
            calculationPreview.style.display = 'none';
        }
    }
    
    // Function to generate installment schedule
    function generateInstallmentSchedule(principal, monthlyInterest) {
        let scheduleHTML = '';
        const start = new Date(loanDate.value);
        
        // First month: Only interest
        const date1 = new Date(start);
        date1.setMonth(date1.getMonth() + 1);
        scheduleHTML += `
            <tr>
                <td>১</td>
                <td>${date1.toLocaleDateString('bn-BD')}</td>
                <td>শুধু সুদ (৬%)</td>
                <td>${formatNumber(monthlyInterest)} ৳</td>
            </tr>
        `;
        
        // Second month: Only interest
        const date2 = new Date(start);
        date2.setMonth(date2.getMonth() + 2);
        scheduleHTML += `
            <tr>
                <td>২</td>
                <td>${date2.toLocaleDateString('bn-BD')}</td>
                <td>শুধু সুদ (৬%)</td>
                <td>${formatNumber(monthlyInterest)} ৳</td>
            </tr>
        `;
        
        // Third month: Interest + Principal
        const date3 = new Date(start);
        date3.setMonth(date3.getMonth() + 3);
        scheduleHTML += `
            <tr>
                <td>৩</td>
                <td>${date3.toLocaleDateString('bn-BD')}</td>
                <td>সুদ (৬%) + আসল</td>
                <td>${formatNumber(monthlyInterest + principal)} ৳</td>
            </tr>
        `;
        
        installmentSchedule.innerHTML = scheduleHTML;
    }
    
    // Add event listeners to all calculation fields
    [loanAmount, interestRate, loanDate].forEach(input => {
        input.addEventListener('input', calculateLoanDetails);
        input.addEventListener('change', calculateLoanDetails);
    });
    
    // Initial calculation if fields are already filled
    if (loanAmount.value && loanDate.value) {
        calculateLoanDetails();
    }
    
    // Form validation for guarantors
    const guarantor1Select = document.getElementById('guarantor1_id');
    const guarantor2Select = document.getElementById('guarantor2_id');
    
    function validateGuarantors() {
        if (guarantor1Select.value && guarantor2Select.value && guarantor1Select.value === guarantor2Select.value) {
            alert('একই ব্যক্তিকে দুটি গ্যারান্টর হিসেবে নির্বাচন করা যাবে না।');
            guarantor2Select.value = '';
        }
    }
    
    if (guarantor1Select && guarantor2Select) {
        guarantor1Select.addEventListener('change', validateGuarantors);
        guarantor2Select.addEventListener('change', validateGuarantors);
    }
    
    // Form submission validation
    document.getElementById('loanForm').addEventListener('submit', function(e) {
        let isValid = true;
        const errorMessages = [];
        
        // Check if member is selected
        const memberId = memberSelect.value;
        if (!memberId) {
            errorMessages.push('সদস্য নির্বাচন করুন');
            isValid = false;
        }
        
        // Check loan amount
        const loanAmountValue = parseFloat(loanAmount.value) || 0;
        const availableLimit = parseFloat(loanAmount.getAttribute('data-available-limit')) || 0;
        const maxAllowed = parseFloat(loanAmount.max) || 500000;
        
        if (loanAmountValue < 1000) {
            errorMessages.push('ঋণের পরিমাণ কমপক্ষে ১,০০০৳ হতে হবে');
            isValid = false;
        }
        
        if (loanAmountValue > maxAllowed) {
            if (availableLimit < 1000) {
                errorMessages.push('এই সদস্যের ঋণ নেওয়ার আর সীমা নেই');
            } else {
                errorMessages.push(`ঋণের পরিমাণ সর্বোচ্চ ${formatNumber(maxAllowed)}৳ হতে পারে`);
            }
            isValid = false;
        }
        
        // Check if loan amount input is disabled (no available limit)
        if (loanAmount.disabled) {
            errorMessages.push('এই সদস্যের ঋণ নেওয়ার আর সীমা নেই');
            isValid = false;
        }
        
        // Guarantor validation
        const guarantor1 = document.getElementById('guarantor1_id').value;
        const guarantor2 = document.getElementById('guarantor2_id').value;
        
        if (guarantor1 && guarantor2 && guarantor1 === guarantor2) {
            errorMessages.push('একই ব্যক্তিকে দুটি গ্যারান্টর হিসেবে নির্বাচন করা যাবে না');
            isValid = false;
        }
        
        if (memberId && (memberId === guarantor1 || memberId === guarantor2)) {
            errorMessages.push('আপনি নিজের গ্যারান্টর হতে পারবেন না');
            isValid = false;
        }
        
        // Date validation
        const loanDateValue = document.getElementById('loan_date').value;
        if (loanDateValue) {
            const loanDate = new Date(loanDateValue);
            const today = new Date();
            today.setHours(0, 0, 0, 0);
            
            if (loanDate < today) {
                errorMessages.push('ঋণের তারিখ অতীতের হতে পারে না');
                isValid = false;
            }
        }
        
        if (!isValid) {
            e.preventDefault();
            
            // Show error messages
            const errorHtml = `
                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                    <h5><i class="fas fa-exclamation-triangle me-2"></i>সাবধান!</h5>
                    <ul class="mb-0">
                        ${errorMessages.map(msg => `<li>${msg}</li>`).join('')}
                    </ul>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            `;
            
            // Remove existing alerts
            const existingAlert = document.querySelector('.alert.alert-danger');
            if (existingAlert) {
                existingAlert.remove();
            }
            
            // Insert error at top of form
            document.querySelector('.card-body').insertAdjacentHTML('afterbegin', errorHtml);
            
            // Scroll to error
            window.scrollTo({
                top: 0,
                behavior: 'smooth'
            });
            
            return false;
        }
    });
});
</script>
<?php $__env->stopSection(); ?>
<?php echo $__env->make('layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH /home/naowarin/somoti.naowarinternational.my.id/resources/views/loans/create.blade.php ENDPATH**/ ?>