<?php $__env->startSection('content'); ?>
<div class="card">
    <div class="card-header">
        <div class="row align-items-center">
            <div class="col">
                <h5 class="mb-0">Loan Applications</h5>
            </div>
            <div class="col-auto d-flex align-items-center gap-2">
                <button type="button" class="btn btn-info btn-sm" data-bs-toggle="modal" data-bs-target="#importModal">
                    <i class="bi bi-upload"></i> Import
                </button>
                <a href="<?php echo e(route('payroll.employee-loans.create')); ?>" class="btn btn-primary btn-sm">
                    Add Loan Application
                </a>
            </div>
        </div>       
    </div>
    <div class="card-body">
        <table class="table table-bordered table-striped w-100" id="loanapptbl">
            <thead>
                <tr>
                    <th width="50">#</th>
                    <th>No</th>
                    <th>Emp No</th>
                    <th>Name</th>
                    <th>App Date</th>
                    <th>Loan Name</th>
                    <th>Full Amount</th>
                    <th>App Amount</th>
                    <th>Interest</th>
                    <th>Repay Period</th>
                    <th>Inst Amount</th>
                    <th>Status</th>
                    <th width="120">Action</th>
                </tr>
            </thead>
        </table>
    </div>
</div>

<!-- Import Loan Applications Modal -->
<div class="modal fade" id="importModal" tabindex="-1" aria-labelledby="importModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="importModalLabel">Import Loan Applications</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <!-- Loan selection -->
                <div class="mb-3">
                    <label for="importLoanId" class="form-label fw-semibold">Loan Type <span class="text-danger">*</span></label>
                    <select id="importLoanId" class="form-select">
                        <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); ?>"><?php echo e($loan->name); ?></option>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                    </select>
                </div>

                <!-- Download template -->
                <div class="mb-3">
                    <a href="<?php echo e(route('payroll.employee-loans.import-template')); ?>" class="btn btn-outline-secondary btn-sm">
                        <i class="bi bi-download"></i> Download Template (CSV)
                    </a>
                    <small class="text-muted ms-2">
                        Required columns: <strong>emp_no, application_date, full_amount, interest_rate, repayment_period, installment_amount</strong>. Optional: <strong>remarks</strong>.
                    </small>
                </div>

                <!-- File upload drop zone -->
                <div class="mb-3">
                    <label class="form-label fw-semibold">Upload File <span class="text-danger">*</span></label>
                    <div id="importDropZone"
                         class="border border-2 border-dashed rounded p-4 text-center"
                         style="cursor:pointer; border-style:dashed !important; min-height:120px; display:flex; flex-direction:column; align-items:center; justify-content:center;">
                        <i class="bi bi-cloud-upload fs-2 text-secondary"></i>
                        <p class="mb-1 text-secondary">Drag &amp; drop a CSV or Excel file here</p>
                        <p class="text-muted small mb-2">or</p>
                        <button type="button" class="btn btn-sm btn-outline-primary" id="importBrowseBtn">Browse File</button>
                        <input type="file" id="importFileInput" accept=".csv,.xlsx,.xls" style="display:none">
                    </div>
                    <div id="importFileName" class="mt-2 text-success small"></div>
                </div>

                <!-- Error list -->
                <div id="importErrors" class="d-none">
                    <div class="alert alert-warning mb-0">
                        <strong>Rows skipped:</strong>
                        <ul id="importErrorList" class="mb-0 mt-1 ps-3"></ul>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary" id="importSubmitBtn" onclick="submitImport()">
                    <i class="bi bi-upload"></i> Import
                </button>
            </div>
        </div>
    </div>
</div>
<?php $__env->stopSection(); ?>

<?php $__env->startSection('scripts'); ?>
<script>
let table = $('#loanapptbl').DataTable({
    processing: true,
    serverSide: true,
    ajax: "<?php echo e(route('payroll.employee-loans.index')); ?>",
    order: [[4, 'desc']], // Order by application date
    dom:
        "<'row mb-3 align-items-center'<'col-md-6'l><'col-md-6 d-flex justify-content-end'f>>" +
        "<'table-responsive'tr>" +
        "<'row mt-3 align-items-center'<'col-md-6'i><'col-md-6 d-flex justify-content-end'p>>",

    language: {
        search: "",
        searchPlaceholder: "Search loan applications...",
        lengthMenu: "Show _MENU_ entries",
        info: "Showing _START_–_END_ of _TOTAL_ loan applications"
    },
    columns: [
        {data: 'DT_RowIndex', name: 'DT_RowIndex', orderable: false, searchable: false},
        {data: 'loan_number', name: 'loan_number'},
        {data: 'emp_no', name: 'employee.employee_code'},
        {data: 'emp_name', name: 'employee.first_name'},
        {data: 'application_date', name: 'application_date'},
        {data: 'loan_name', name: 'loan.name'},
        {
            data: 'full_amount',
            name: 'full_amount',
            render: function(data) {
                return parseFloat(data).toFixed(2);
            }
        },
        {
            data: 'approved_amount',
            name: 'approved_amount',
            render: function(data) {
                return data ? parseFloat(data).toFixed(2) : '-';
            }
        },
        {
            data: 'interest_rate',
            name: 'interest_rate',
            render: function(data) {
                return parseFloat(data).toFixed(2) + '%';
            }
        },
        {data: 'repayment_period', name: 'repayment_period'},
        {
            data: 'installment_amount',
            name: 'installment_amount',
            render: function(data) {
                return parseFloat(data).toFixed(2);
            }
        },
        {data: 'status', name: 'status', orderable: false, searchable: false},
        {data: 'action', name: 'action', orderable: false, searchable: false},
    ]
});

// Handle delete action
$(document).on('click', '.delete-btn', function() {
    let url = $(this).data('url');

    Swal.fire({
        title: 'Are you sure?',
        text: "You won't be able to revert this!",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#d33',
        cancelButtonColor: '#3085d6',
        confirmButtonText: 'Yes, delete it!'
    }).then((result) => {
        if (result.isConfirmed) {
            $.ajax({
                url: url,
                type: 'DELETE',
                data: {
                    _token: '<?php echo e(csrf_token()); ?>'
                },
                success: function(response) {
                    if (response.status) {
                        Swal.fire('Deleted!', response.message, 'success');
                        table.ajax.reload();
                    } else {
                        Swal.fire('Error!', response.message, 'error');
                    }
                },
                error: function(xhr) {
                    Swal.fire('Error!', 'Failed to delete loan application', 'error');
                }
            });
        }
    });
});

// Handle approve action
$(document).on('click', '.approve-btn', function() {
    let url = $(this).data('url');

    Swal.fire({
        title: 'Approve Loan?',
        text: "This will approve the loan application",
        icon: 'question',
        showCancelButton: true,
        confirmButtonColor: '#28a745',
        cancelButtonColor: '#6c757d',
        confirmButtonText: 'Yes, approve it!'
    }).then((result) => {
        if (result.isConfirmed) {
            $.ajax({
                url: url,
                type: 'POST',
                data: {
                    _token: '<?php echo e(csrf_token()); ?>'
                },
                success: function(response) {
                    if (response.status) {
                        Swal.fire('Approved!', response.message, 'success');
                        table.ajax.reload();
                    } else {
                        Swal.fire('Error!', response.message, 'error');
                    }
                }
            });
        }
    });
});

/* ============================================================
   Import modal logic
   ============================================================ */
let importSelectedFile = null;

$('#importModal').on('show.bs.modal', function () {
    importSelectedFile = null;
    $('#importFileName').text('');
    $('#importFileInput').val('');
    $('#importLoanId').val('');
    $('#importErrors').addClass('d-none');
    $('#importErrorList').empty();
    $('#importDropZone').removeClass('border-success border-danger').addClass('border-secondary');
});

$('#importBrowseBtn').on('click', function () {
    $('#importFileInput').trigger('click');
});

$('#importFileInput').on('change', function () {
    if (this.files.length > 0) importSetFile(this.files[0]);
});

$('#importDropZone').on('dragover', function (e) {
    e.preventDefault();
    $(this).addClass('bg-light');
}).on('dragleave', function () {
    $(this).removeClass('bg-light');
}).on('drop', function (e) {
    e.preventDefault();
    $(this).removeClass('bg-light');
    const file = e.originalEvent.dataTransfer.files[0];
    if (file) importSetFile(file);
});

function importSetFile(file) {
    const ext = file.name.split('.').pop().toLowerCase();
    if (!['csv', 'xlsx', 'xls'].includes(ext)) {
        Swal.fire('Invalid File', 'Please upload a CSV or Excel (.xlsx / .xls) file.', 'warning');
        return;
    }
    importSelectedFile = file;
    $('#importFileName').text('Selected: ' + file.name);
    $('#importDropZone').removeClass('border-danger').addClass('border-success');
    $('#importErrors').addClass('d-none');
    $('#importErrorList').empty();
}

function submitImport() {
    const loanId = $('#importLoanId').val();
    if (!loanId) {
        Swal.fire('Warning', 'Please select a loan type.', 'warning');
        return;
    }
    if (!importSelectedFile) {
        Swal.fire('Warning', 'Please select a file to upload.', 'warning');
        return;
    }

    const formData = new FormData();
    formData.append('_token', '<?php echo e(csrf_token()); ?>');
    formData.append('loan_id', loanId);
    formData.append('file', importSelectedFile);

    $('#importSubmitBtn').prop('disabled', true).html('<span class="spinner-border spinner-border-sm me-1"></span> Importing...');
    $('#importErrors').addClass('d-none');
    $('#importErrorList').empty();

    $.ajax({
        url: '<?php echo e(route("payroll.employee-loans.import")); ?>',
        type: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        success: function (response) {
            $('#importSubmitBtn').prop('disabled', false).html('<i class="bi bi-upload"></i> Import');

            if (response.errors && response.errors.length > 0) {
                response.errors.forEach(function (err) {
                    $('#importErrorList').append('<li>' + err + '</li>');
                });
                $('#importErrors').removeClass('d-none');
            }

            Swal.fire('Done!', response.message, response.inserted > 0 ? 'success' : 'warning').then(function () {
                if (response.inserted > 0) {
                    $('#importModal').modal('hide');
                    table.ajax.reload();
                }
            });
        },
        error: function (xhr) {
            $('#importSubmitBtn').prop('disabled', false).html('<i class="bi bi-upload"></i> Import');
            const msg = xhr.responseJSON?.message || xhr.responseJSON?.errors?.file?.[0] || 'An error occurred.';
            Swal.fire('Error!', msg, 'error');
        }
    });
}

// Handle reject action
$(document).on('click', '.reject-btn', function() {
    let url = $(this).data('url');

    Swal.fire({
        title: 'Reject Loan?',
        text: "This will reject the loan application",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#d33',
        cancelButtonColor: '#6c757d',
        confirmButtonText: 'Yes, reject it!'
    }).then((result) => {
        if (result.isConfirmed) {
            $.ajax({
                url: url,
                type: 'POST',
                data: {
                    _token: '<?php echo e(csrf_token()); ?>'
                },
                success: function(response) {
                    if (response.status) {
                        Swal.fire('Rejected!', response.message, 'success');
                        table.ajax.reload();
                    } else {
                        Swal.fire('Error!', response.message, 'error');
                    }
                }
            });
        }
    });
});
</script>
<?php $__env->stopSection(); ?>

<?php echo $__env->make('layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH /media/madu/E8460E1D460DECDE/projects/laraoffice/app/Modules/HR/Payroll/Providers/../Views/employee-loans/index.blade.php ENDPATH**/ ?>