<?php $__env->startSection('content'); ?>
<div class="card">
        <div class="card-header">
            <div>
                <h5 class="mb-0 fw-semibold">Loan Application</h5>
            </div>
        </div>

        <div class="card-body">
            <form id="loanForm">
                <?php echo csrf_field(); ?>

                <div class="row g-3 mb-3">
                    
                    <div class="col-md-6">
                        <label class="form-label required">Employee *</label>
                        <select name="employee_id" id="employee_id" class="form-select" required>
                            <option value="">-- Select Employee --</option>
                            <?php $__currentLoopData = $employees; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $employee): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                <option value="<?php echo e($employee['id']); ?>"><?php echo e($employee['text']); ?></option>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                        </select>
                        <div class="invalid-feedback">Please select an employee</div>
                    </div>

                   
                    
                    <div class="col-md-6">
                        <label class="form-label required">Loan Name*</label>
                        <select name="loan_id" id="loan_id" class="form-select" required>
                            <option value="">-- Select Loan Type --</option>
                            <?php $__currentLoopData = $loans; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $loan): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                <option value="<?php echo e($loan->id); ?>"
                                        data-min-amount="<?php echo e($loan->min_amount); ?>"
                                        data-max-amount="<?php echo e($loan->max_amount); ?>"
                                        data-min-period="<?php echo e($loan->min_installments); ?>"
                                        data-max-period="<?php echo e($loan->max_installments); ?>"
                                        data-interest="<?php echo e($loan->interest_rate); ?>">
                                    <?php echo e($loan->name); ?>

                                </option>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                        </select>
                        <div class="invalid-feedback">Please select a loan type</div>
                    </div>

                    <div class="col-md-6">
                        <label class="form-label required">Date*</label>
                        <input type="date" name="application_date" id="application_date" class="form-control" value="<?php echo e(date('Y-m-d')); ?>" required>
                        <div class="invalid-feedback">Please select application date</div>
                    </div>

                    
                    <div class="col-md-4">
                        <label class="form-label required">Full Amount*</label>
                        <input type="number" step="0.01" name="full_amount" id="full_amount" class="form-control" placeholder="0.00" required min="0">
                        <small class="text-muted" id="amount_range"></small>
                        <div class="invalid-feedback">Please enter full amount</div>
                    </div>

                    <div class="col-md-4">
                        <label class="form-label">Approved Amount</label>
                        <input type="number" step="0.01" name="approved_amount" id="approved_amount" class="form-control" placeholder="0.00" min="0">
                        <small class="text-muted">Leave blank if not yet approved</small>
                    </div>

                    <div class="col-md-4">
                        <label class="form-label required">Interest Rate (%)*</label>
                        <input type="number" step="0.01" name="interest_rate" id="interest_rate" class="form-control" placeholder="0.00" required min="0" max="100">
                        <div class="invalid-feedback">Please enter interest rate</div>
                    </div>

                    
                    <div class="col-md-6">
                        <label class="form-label required">Repayment Period (Months)*</label>
                        <input type="number" name="repayment_period" id="repayment_period" class="form-control" placeholder="12" required min="1">
                        <small class="text-muted" id="period_range"></small>
                        <div class="invalid-feedback">Please enter repayment period</div>
                    </div>

                    <div class="col-md-6">
                        <label class="form-label required">Installment Amount*</label>
                        <input type="number" step="0.01" name="installment_amount" id="installment_amount" class="form-control" placeholder="0.00" required min="0" readonly>
                        <small class="text-muted">Auto-calculated</small>
                        <div class="invalid-feedback">Installment amount is required</div>
                    </div>

                    
                    <div class="col-md-12">
                        <label class="form-label">Remarks</label>
                        <textarea name="remarks" id="remarks" class="form-control" rows="3" placeholder="Optional notes about this loan application"></textarea>
                    </div>
                </div>
               
                <button type="submit" class="btn btn-primary">Save</button>
                <a href="<?php echo e(route('payroll.employee-loans.index')); ?>" class="btn btn-secondary">Back</a>
            </form>
        </div>
    </div>
<?php $__env->stopSection(); ?>

<?php $__env->startSection('scripts'); ?>
<script>
$(document).ready(function() {
    // Initialize Select2 for employee dropdown
    $('#employee_id').select2({
        placeholder: '-- Select Employee --',
        allowClear: true,
        width: '100%'
    });

       // Update loan constraints when loan type is selected
    $('#loan_id').on('change', function() {
        let option = $(this).find(':selected');
        let minAmount = option.data('min-amount');
        let maxAmount = option.data('max-amount');
        let minPeriod = option.data('min-period');
        let maxPeriod = option.data('max-period');
        let interest = option.data('interest');

        if (minAmount && maxAmount) {
            $('#amount_range').text(`Range: ${minAmount} - ${maxAmount}`);
            $('#full_amount').attr('min', minAmount).attr('max', maxAmount);
        } else {
            $('#amount_range').text('');
            $('#full_amount').removeAttr('min max');
        }

        if (minPeriod && maxPeriod) {
            $('#period_range').text(`Range: ${minPeriod} - ${maxPeriod} months`);
            $('#repayment_period').attr('min', minPeriod).attr('max', maxPeriod);
        } else {
            $('#period_range').text('');
        }

        if (interest) {
            $('#interest_rate').val(parseFloat(interest).toFixed(2));
            calculateInstallment();
        }
    });

    // Calculate installment when values change
    $('#full_amount, #approved_amount, #interest_rate, #repayment_period').on('input', function() {
        calculateInstallment();
    });

    function calculateInstallment() {
        let amount = parseFloat($('#approved_amount').val()) || parseFloat($('#full_amount').val()) || 0;
        let interestRate = parseFloat($('#interest_rate').val()) || 0;
        let period = parseInt($('#repayment_period').val()) || 0;

        if (amount > 0 && period > 0) {
            let interest = (amount * interestRate) / 100;
            let totalAmount = amount + interest;
            let installment = totalAmount / period;

            $('#installment_amount').val(installment.toFixed(2));
        } else {
            $('#installment_amount').val('');
        }
    }

    // Form submission
    $('#loanForm').on('submit', function(e) {
        e.preventDefault();

        let form = $(this);
        let submitBtn = form.find('button[type="submit"]');

        // Validate form
        if (!this.checkValidity()) {
            e.stopPropagation();
            form.addClass('was-validated');
            return;
        }

        submitBtn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm me-1"></span> Saving...');

        $.ajax({
            url: '<?php echo e(route("payroll.employee-loans.store")); ?>',
            type: 'POST',
            data: form.serialize(),
            success: function(response) {
                if (response.status) {
                    Swal.fire({
                        icon: 'success',
                        title: 'Success!',
                        text: response.message,
                        showConfirmButton: false,
                        timer: 1500
                    }).then(function() {
                        window.location.href = '<?php echo e(route("payroll.employee-loans.index")); ?>';
                    });
                } else {
                    Swal.fire({
                        icon: 'error',
                        title: 'Error!',
                        text: response.message || 'Failed to create loan application'
                    });
                    submitBtn.prop('disabled', false).html('<i class="bi bi-save me-1"></i> Save');
                }
            },
            error: function(xhr) {
                let errors = xhr.responseJSON?.errors;
                let errorMessage = 'Failed to create loan application';

                if (errors) {
                    errorMessage = Object.values(errors).flat().join('<br>');
                }

                Swal.fire({
                    icon: 'error',
                    title: 'Validation Error',
                    html: errorMessage
                });

                submitBtn.prop('disabled', false).html('<i class="bi bi-save me-1"></i> Save');
            }
        });
    });
});
</script>
<?php $__env->stopSection(); ?>

<?php echo $__env->make('layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH /home/codeproh/va.laraoffice.com/app/Modules/HR/Payroll/Providers/../Views/employee-loans/create.blade.php ENDPATH**/ ?>