<?php $__env->startPush('css'); ?>
<?php $__env->stopPush(); ?>

<?php $__env->startSection('title', 'Payroll Management'); ?>

<?php $__env->startSection('panel-actions'); ?>
    <?php if(auth()->user()->canAccess('payroll.process')): ?>
    <a href="<?php echo e(route('salaries.bulk.processor')); ?>" class="btn btn-info btn-sm">
        <i class="fas fa-file-invoice-dollar mr-1"></i> Monthly Processor
    </a>
    <a href="<?php echo e(route('salaries.create')); ?>" class="btn btn-primary btn-sm ml-1">
        <i class="fas fa-plus mr-1"></i> Generate Payslip
    </a>
    <?php endif; ?>
<?php $__env->stopSection(); ?>

<?php $__env->startSection('content'); ?>
<div class="row">
    <div class="col-12">
        <!-- Summary Widgets -->
        <div class="row mb-4">
            <div class="col-md-3">
                <div class="info-box premium-info-box bg-premium-success shadow-sm">
                    <span class="info-box-icon"><i class="fa-solid fa-money-bill-trend-up"></i></span>
                    <div class="info-box-content">
                        <span class="info-box-text text-uppercase">Total Net Payout</span>
                        <span class="info-box-number"><span class="currency-symbol"><?php echo e(\App\Models\BusinessSetting::firstOrNewDefault()->currency_symbol); ?></span><span id="widget_total_net_pay">0.00</span></span>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="info-box premium-info-box bg-premium-danger shadow-sm">
                    <span class="info-box-icon"><i class="fa-solid fa-hand-holding-dollar"></i></span>
                    <div class="info-box-content">
                        <span class="info-box-text text-uppercase">Total Deductions</span>
                        <span class="info-box-number text-white"><span class="currency-symbol"><?php echo e(\App\Models\BusinessSetting::firstOrNewDefault()->currency_symbol); ?></span><span id="widget_total_deductions">0.00</span></span>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="info-box premium-info-box bg-premium-info shadow-sm">
                    <span class="info-box-icon"><i class="fa-solid fa-users"></i></span>
                    <div class="info-box-content">
                        <span class="info-box-text text-uppercase">Records Found</span>
                        <span class="info-box-number h5 mb-0" id="widget_total_count">0</span>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="info-box premium-info-box bg-premium-primary shadow-sm">
                    <span class="info-box-icon"><i class="fa-solid fa-building-columns"></i></span>
                    <div class="info-box-content">
                        <span class="info-box-text text-uppercase">Gross Earnings</span>
                        <span class="info-box-number h5 mb-0"><span class="currency-symbol"><?php echo e(\App\Models\BusinessSetting::firstOrNewDefault()->currency_symbol); ?></span><span id="widget_total_gross">0.00</span></span>
                    </div>
                </div>
            </div>
        </div>

        <!-- Filter Section -->
        <div class="card card-primary card-outline">
            <div class="card-header">
                <h3 class="card-title fw-bold"><i class="fas fa-filter mr-2"></i>Payroll History Filter</h3>
            </div>
            <div class="card-body">
                <form id="filterForm" class="row">
                    <div class="col-md-3">
                        <div class="form-group">
                            <label>Month</label>
                            <select id="month_filter" class="form-control">
                                <option value="">All Months</option>
                                <?php for($i=1; $i<=12; $i++): ?>
                                    <option value="<?php echo e($i); ?>"><?php echo e(date('F', mktime(0, 0, 0, $i, 10))); ?></option>
                                <?php endfor; ?>
                            </select>
                        </div>
                    </div>
                    <div class="col-md-2">
                        <div class="form-group">
                            <label>Year</label>
                            <input type="number" id="year_filter" class="form-control" value="<?php echo e(date('Y')); ?>">
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="form-group">
                            <label>Employee</label>
                            <select id="employee_id_filter" class="form-control select2-ajax w-100">
                                <option value="">All Employees</option>
                            </select>
                        </div>
                    </div>
                    <div class="col-md-3" style="margin-top: 32px;">
                        <button type="button" id="applyFilter" class="btn btn-primary">Apply Filter</button>
                        <button type="button" id="resetFilter" class="btn btn-default"><i class="fas fa-undo"></i></button>
                    </div>
                </form>
            </div>
        </div>

        <!-- Table Section -->
        <div class="card card-default">
            <div class="card-header">
                <h3 class="card-title fw-bold"><i class="fas fa-money-check-alt mr-2"></i>Processed Payslips</h3>
                <div class="card-tools">
                    <?php if(auth()->user()->canAccess('payroll.export')): ?>
                    <button id="exportExcel" class="btn btn-success btn-xs">
                        <i class="fas fa-file-excel mr-1"></i> Excel
                    </button>
                    <button id="exportCSV" class="btn btn-info btn-xs ml-1">
                        <i class="fas fa-file-csv mr-1"></i> CSV
                    </button>
                    <?php endif; ?>
                </div>
            </div>
            <div class="table-responsive">
                <table class="table table-hover table-bordered table-striped w-100 mb-0" id="salaryTable">

                    <thead>
                        <tr>
                            <th>Employee</th>
                            <th>Month/Year</th>
                            <th>Basic Pay</th>
                            <th>Gross Earnings</th>
                            <th>Gross Deductions</th>
                            <th>Net Pay</th>
                            <th style="width: 200px;">Action</th>
                        </tr>
                    </thead>
                </table>
            </div>
        </div>
    </div>
</div>
<?php $__env->stopSection(); ?>

<?php $__env->startSection('modals'); ?>
<div class="modal fade" id="payrollModal" role="dialog">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title font-weight-bold"><i class="fas fa-edit mr-1"></i> Edit Payroll: <span id="modalEmpName"></span></h4>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form id="payrollEditForm">
                    <input type="hidden" id="modalEmpId">
                    <input type="hidden" id="modalSalaryId">
                    
                    <div class="row g-3">
                        <div class="col-md-6">
                            <label class="small fw-bold text-muted mb-1">Emp Code</label>
                            <input type="text" class="form-control form-control-sm" id="modal_employee_code" readonly>
                        </div>
                        <div class="col-md-6">
                            <label class="small fw-bold text-muted mb-1">Designation</label>
                            <input type="text" class="form-control form-control-sm" id="modal_designation">
                        </div>
                        <div class="col-md-4">
                            <label class="small fw-bold text-muted mb-1">Working Days</label>
                            <input type="number" step="1" class="form-control form-control-sm modal-calc-trigger" id="modal_working_days">
                        </div>
                        <div class="col-md-4">
                            <label class="small fw-bold text-muted mb-1">LOP Days</label>
                            <input type="number" step="1" class="form-control form-control-sm modal-calc-trigger" id="modal_lop_days">
                        </div>
                        <div class="col-md-4">
                            <label class="small fw-bold text-muted mb-1">Basic Salary</label>
                            <input type="number" step="0.01" class="form-control form-control-sm modal-calc-trigger" id="modal_base_salary">
                        </div>
                        
                        <div class="col-12"><hr class="my-1"></div>
                        
                        <div id="dynamicAdditionsContainer" class="row g-3 px-0 mx-0 mt-0"></div>
                        
                        <div class="col-md-6">
                            <label class="small fw-bold text-primary mb-1">Total Gross Earnings</label>
                            <input type="number" class="form-control form-control-sm fw-bold bg-light" id="modal_gross_earnings" readonly>
                        </div>

                        <div class="col-12"><hr class="my-1"></div>
                        
                        <div id="dynamicDeductionsContainer" class="row g-3 px-0 mx-0 mt-0"></div>
                        
                        <div class="col-md-6">
                            <label class="small fw-bold text-danger mb-1">Total Deductions</label>
                            <input type="number" class="form-control form-control-sm fw-bold bg-light text-danger" id="modal_gross_deductions" readonly>
                        </div>
                        <div class="col-md-6">
                            <label class="small fw-bold text-muted mb-1">Reimbursements</label>
                            <input type="number" step="0.01" class="form-control form-control-sm modal-calc-trigger" id="modal_expense_reimbursements">
                        </div>
                        
                        <div class="col-xs-12" style="margin-top: 15px; padding: 15px; background: #f8f9fa; border-top: 1px solid #eee; text-align: center;">
                            <h4 class="mb-0 fw-bold text-success" style="margin:0;">Net Pay: <span id="modal_net_pay_display">0.00</span></h4>
                            <input type="hidden" id="modal_net_pay">
                        </div>

                    </div>
                </form>
            </div>
            <div class="modal-footer bg-light">
                <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-primary px-4" id="saveModalChanges">Save Changes</button>
            </div>
        </div>
    </div>
</div>
<?php $__env->stopSection(); ?>


<?php $__env->startPush('scripts'); ?>
<script>
$(function() {
    $('.select2-ajax').select2({
        theme: 'bootstrap4',
        ajax: {
            url: "<?php echo e(route('employees.search')); ?>",
            dataType: 'json',
            delay: 250,
            data: function (params) {
                return { term: params.term };
            },
            processResults: function (data) {
                return { results: data.results };
            },
            cache: true
        },
        placeholder: 'Search for an employee...',
        allowClear: true
    });

    var table = $('#salaryTable').DataTable({
        processing: true,
        serverSide: true,
        ajax: {
            url: "<?php echo e(route('salaries.data')); ?>",
            data: function (d) {
                d.month = $('#month_filter').val();
                d.year = $('#year_filter').val();
                d.employee_id = $('#employee_id_filter').val();
            }
        },
        columns: [
            {data: 'employee', name: 'employee'},
            {data: 'month', name: 'month'},
            {data: 'base_salary', name: 'base_salary'},
            {data: 'gross_earnings', name: 'gross_earnings'},
            {data: 'gross_deductions', name: 'gross_deductions'},
            {data: 'net_pay', name: 'net_pay'},
            {data: 'action', name: 'action', orderable: false, searchable: false}
        ],
        dom: "<'row'<'col-sm-6'l><'col-sm-6'f>>" +
             "<'row'<'col-sm-12'tr>>" +
             "<'row'<'col-sm-5'i><'col-sm-7'p>>",
        scrollX: true,
        language: {
            search: "_INPUT_",
            searchPlaceholder: "Search payroll records...",
            paginate: {
                previous: '<i class="fas fa-chevron-left"></i>',
                next: '<i class="fas fa-chevron-right"></i>'
            }
        },
        drawCallback: function(settings) {
            $('.dataTables_paginate > .pagination').addClass('pagination-sm');
            
            // Update widgets from AJAX response
            if (settings.json && settings.json.aggregates) {
                const agg = settings.json.aggregates;
                $('#widget_total_net_pay').text(parseFloat(agg.total_net_pay).toLocaleString('en-US', {minimumFractionDigits: 2}));
                $('#widget_total_deductions').text(parseFloat(agg.total_gross_deductions).toLocaleString('en-US', {minimumFractionDigits: 2}));
                $('#widget_total_gross').text(parseFloat(agg.total_gross_earnings).toLocaleString('en-US', {minimumFractionDigits: 2}));
                $('#widget_total_count').text(agg.total_count);
            }
        }
    });

    $('#applyFilter').click(function(){ table.draw(); });
    $('#resetFilter').click(function(){
        $('#filterForm')[0].reset();
        $('#employee_id_filter').val(null).trigger('change');
        table.draw();
    });

    // Bootstrap 4 modal handling
        const editModal = $('#payrollModal');

    function calculateModal() {
        const basic = parseFloat($('#modal_base_salary').val()) || 0;
        
        let dynamicAdditions = 0;
        $('.modal-dynamic-addition').each(function() {
            dynamicAdditions += parseFloat($(this).val()) || 0;
        });

        const grossEarnings = basic + dynamicAdditions;
        $('#modal_gross_earnings').val(grossEarnings.toFixed(2));

        let dynamicDeductions = 0;
        $('.modal-dynamic-deduction').each(function() {
            const perc = parseFloat($(this).val()) || 0;
            dynamicDeductions += (grossEarnings * (perc/100));
        });

        const grossDeductions = dynamicDeductions;
        $('#modal_gross_deductions').val(grossDeductions.toFixed(2));


        const reimb = parseFloat($('#modal_expense_reimbursements').val()) || 0;
        const netPay = grossEarnings - grossDeductions + reimb;
        $('#modal_net_pay').val(netPay.toFixed(2));
        $('#modal_net_pay_display').text(netPay.toLocaleString('en-US', {minimumFractionDigits: 2}));
    }

    $('body').on('click', '.edit-salary', function() {
        const salaryId = $(this).data('id');
        $('#modalSalaryId').val(salaryId);
        
        $.get("<?php echo e(url('salaries')); ?>/" + salaryId, function(sal) {
            $('#modalEmpName').text(sal.employee.name);
            $('#modalEmpId').val(sal.employee_id);
            $('#modal_employee_code').val(sal.employee_code || ('ICA00' + sal.employee_id));
            $('#modal_designation').val(sal.designation);
            $('#modal_working_days').val(sal.working_days);
            $('#modal_lop_days').val(sal.lop_days);
            $('#modal_base_salary').val(sal.base_salary);
            $('#modal_hra').val(sal.hra);
            $('#modal_special_allowance').val(sal.special_allowance);
            $('#modal_conveyance').val(sal.conveyance);
            $('#modal_medical').val(sal.medical);
            $('#modal_lta').val(sal.lta);
            $('#modal_special_allowance_2').val(sal.special_allowance_2);
            $('#modal_esic_employee').val(sal.esic_employee);
            $('#modal_prof_tax').val(sal.prof_tax);
            $('#modal_income_tax').val(sal.income_tax);
            $('#modal_expense_reimbursements').val(sal.expense_reimbursements);

            // Dynamic Additions
            const additions = sal.components?.additions || [];
            $('#dynamicAdditionsContainer').empty();
            additions.forEach(add => {
                $('#dynamicAdditionsContainer').append(`
                    <div class="col-md-4">
                        <label class="small fw-bold text-muted mb-1">${add.name}</label>
                        <input type="number" step="0.01" class="form-control form-control-sm modal-calc-trigger modal-dynamic-addition" 
                            data-id="${add.id}" data-name="${add.name}" value="${add.amount}">
                    </div>
                `);
            });

            // Dynamic Deductions
            const deductions = sal.components?.deductions || [];
            $('#dynamicDeductionsContainer').empty();
            deductions.forEach(ded => {
                $('#dynamicDeductionsContainer').append(`
                    <div class="col-md-4">
                        <label class="small fw-bold text-muted mb-1">${ded.name} (%)</label>
                        <input type="number" step="0.01" class="form-control form-control-sm modal-calc-trigger modal-dynamic-deduction" 
                            data-id="${ded.id}" data-name="${ded.name}" value="${ded.percentage}">
                    </div>
                `);
            });

            calculateModal();
            editModal.modal('show');
        });
    });

    $('.modal-calc-trigger').on('input', function() {
        calculateModal();
    });

    $('#saveModalChanges').click(function() {
        const salaryId = $('#modalSalaryId').val();
        
        const additions = [];
        $('.modal-dynamic-addition').each(function() {
            additions.push({ id: $(this).data('id'), name: $(this).data('name'), amount: $(this).val() });
        });

        const deductions = [];
        $('.modal-dynamic-deduction').each(function() {
            deductions.push({ id: $(this).data('id'), name: $(this).data('name'), percentage: $(this).val() });
        });

        const data = {
            _token: "<?php echo e(csrf_token()); ?>",
            month: table.row($(`.edit-salary[data-id="${salaryId}"]`).closest('tr')).data().month_raw || (new Date()).getMonth() + 1,
            year: $('#year_filter').val(),
            salaries: {
                [$('#modalEmpId').val()]: {
                    employee_code: $('#modal_employee_code').val(),
                    designation: $('#modal_designation').val(),
                    working_days: $('#modal_working_days').val(),
                    lop_days: $('#modal_lop_days').val(),
                    base_salary: $('#modal_base_salary').val(),
                    hra: $('#modal_hra').val(),
                    special_allowance: $('#modal_special_allowance').val(),
                    conveyance: $('#modal_conveyance').val(),
                    medical: $('#modal_medical').val(),
                    lta: $('#modal_lta').val(),
                    special_allowance_2: $('#modal_special_allowance_2').val(),
                    gross_earnings: $('#modal_gross_earnings').val(),
                    esic_employee: $('#modal_esic_employee').val(),
                    prof_tax: $('#modal_prof_tax').val(),
                    income_tax: $('#modal_income_tax').val(),
                    gross_deductions: $('#modal_gross_deductions').val(),
                    expense_reimbursements: $('#modal_expense_reimbursements').val(),
                    net_pay: $('#modal_net_pay').val(),
                    additions: JSON.stringify(additions),
                    deductions: JSON.stringify(deductions)
                }
            }
        };

        const btn = $(this);
        btn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin me-2"></i>Saving...');

        $.ajax({
            url: "<?php echo e(route('salaries.bulk.save')); ?>",
            type: 'POST',
            data: JSON.stringify(data),
            contentType: 'application/json',
            success: function() {
                Swal.fire({ icon: 'success', title: 'Payroll Updated', timer: 1500 });
                editModal.modal('hide');
                table.draw(false);
                btn.prop('disabled', false).text('Save Changes');
            },
            error: function() {
                btn.prop('disabled', false).text('Save Changes');
                Swal.fire({ icon: 'error', title: 'Update Failed' });
            }
        });
    });

    // Existing delete logic
    $('body').on('click', '.delete-salary', function() {
        var id = $(this).data('id');
        Swal.fire({
            title: 'Delete this record?',
            text: "This action cannot be undone!",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#d33',
            confirmButtonText: 'Yes, delete it!',
            customClass: {
                confirmButton: 'btn btn-danger',
                cancelButton: 'btn btn-secondary'
            }
        }).then((result) => {
            if (result.isConfirmed) {
                $.ajax({
                    url: "<?php echo e(url('salaries')); ?>/" + id,
                    type: 'DELETE',
                    data: { _token: "<?php echo e(csrf_token()); ?>" },
                    success: function() {
                        Swal.fire({
                            icon: 'success',
                            title: 'Deleted!',
                            toast: true,
                            position: 'top-end',
                            showConfirmButton: false,
                            timer: 3000
                        });
                        table.draw();
                    }
                });
            }
        });
    });

    // Export Excel
    $('#exportExcel').click(function() {
        var params = new URLSearchParams({
            month: $('#month_filter').val(),
            year: $('#year_filter').val(),
            employee_id: $('#employee_id_filter').val()
        });
        window.location.href = "<?php echo e(route('salaries.export.excel')); ?>?" + params.toString();
    });

    // Export CSV
    $('#exportCSV').click(function() {
        var params = new URLSearchParams({
            month: $('#month_filter').val(),
            year: $('#year_filter').val(),
            employee_id: $('#employee_id_filter').val()
        });
        window.location.href = "<?php echo e(route('salaries.export.csv')); ?>?" + params.toString();
    });
});
</script>
<?php $__env->stopPush(); ?>

<?php echo $__env->make('layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH C:\xampp\htdocs\hrms\resources\views/salaries/index.blade.php ENDPATH**/ ?>