@extends('layouts.app')

@push('css')
<style>
    .excel-container {
        overflow-x: auto;
        background: #f4f6f9;
        max-height: 70vh;
        width: 100%;
        border: 1px solid #dee2e6;
    }
    .excel-table {
        width: 100%;
        border-collapse: separate;
        border-spacing: 0;
        background: white;
        font-size: 13px;
    }
    .excel-table th {
        background: #f8f9fa;
        color: #495057;
        font-weight: 700;
        text-align: center;
        padding: 10px;
        position: sticky;
        top: 0;
        z-index: 10;
        border-bottom: 2px solid #dee2e6;
        border-right: 1px solid #dee2e6;
        white-space: nowrap;
    }
    .excel-table td {
        border-bottom: 1px solid #eee;
        border-right: 1px solid #eee;
        padding: 8px 12px;
        vertical-align: middle;
    }
    .sticky-col-1 { position: sticky; left: 0; background: #fff !important; z-index: 11 !important; border-right: 2px solid #dee2e6 !important; }
    
    .row-net-pay { font-weight: 700; color: #28a745; }
    .row-lop-days { color: #dc3545; font-weight: 600; }
    
    .modal-calc-trigger { border-bottom: 2px solid #eee; transition: border-color 0.2s; }
    .modal-calc-trigger:focus { border-color: #007bff; box-shadow: none; }
</style>
@endpush

@section('title', 'Payroll Processor')

@section('panel-actions')
    <div class="d-flex align-items-center">
        <form action="{{ route('salaries.bulk.processor') }}" method="GET" class="form-inline mr-2">
            <select name="month" class="form-select form-control-sm mr-1" style="width: auto;">
                @for($i=1; $i<=12; $i++)
                    <option value="{{ $i }}" {{ $month == $i ? 'selected' : '' }}>{{ date('F', mktime(0, 0, 0, $i, 10)) }}</option>
                @endfor
            </select>
            <input type="number" name="year" class="form-control form-control-sm mr-1" style="width: 80px;" value="{{ $year }}">
            <button type="submit" class="btn btn-default btn-sm"><i class="fas fa-sync"></i></button>
        </form>
        <button id="finalizeBatch" class="btn btn-primary btn-sm px-4 shadow-sm fw-bold" {{ $salaries->count() > 0 ? 'disabled' : '' }}>
            <i class="fas fa-check-double mr-1"></i> Process Payroll
        </button>
    </div>
@endsection

@section('content')
<div class="container-fluid">
    <!-- Summary Widgets -->
    <div class="row mb-4">
        <div class="col-md-4">
            <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">{{ \App\Models\BusinessSetting::firstOrNewDefault()->currency_symbol }}</span><span id="widget_total_net_pay">0.00</span></span>
                </div>
            </div>
        </div>
        <div class="col-md-4">
            <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">{{ \App\Models\BusinessSetting::firstOrNewDefault()->currency_symbol }}</span><span id="widget_total_deductions">0.00</span></span>
                </div>
            </div>
        </div>
        <div class="col-md-4">
            <div class="info-box premium-info-box bg-premium-info shadow-sm">
                <span class="info-box-icon"><i class="fa-solid fa-user-check"></i></span>
                <div class="info-box-content">
                    <span class="info-box-text text-uppercase">Employees Selected</span>
                    <span class="info-box-number h5 mb-0" id="widget_total_count">0</span>
                </div>
            </div>
        </div>
    </div>

    <div class="card card-outline card-primary shadow-sm">
    <div class="card-header border-0">
        <h3 class="card-title font-weight-bold"><i class="fas fa-users-cog mr-2"></i>Bulk Payroll Generation for {{ date('F', mktime(0, 0, 0, $month, 10)) }} {{ $year }}</h3>
        <div class="card-tools">
             <a href="{{ route('salaries.index') }}" class="btn btn-tool text-primary">
                <i class="fas fa-list-ul mr-1"></i> Processed Payroll
            </a>
        </div>
    </div>
    
    @if($salaries->count() > 0)
    <div class="px-4 py-2">
        <div class="alert alert-info border-0 shadow-sm mb-0 d-flex align-items-center" style="border-radius: 0.75rem;">
            <i class="fas fa-info-circle fa-2x mr-3 text-info"></i>
            <div>
                <h6 class="font-weight-bold mb-1">Payroll already processed!</h6>
                <p class="mb-0 small">Records for this month already exist. You can still process again to overwrite, or visit the <a href="{{ route('salaries.index') }}" class="font-weight-bold text-info">Processed Payroll</a> list to edit individual records.</p>
            </div>
        </div>
    </div>
    @endif

    <div class="card-body p-0">
        <div class="excel-container">
            <table class="excel-table table-hover" id="payrollGrid">
                <thead>
                    <tr>
                        <th style="width: 40px;"><input type="checkbox" id="selectAll" checked></th>
                        <th class="sticky-col-1">Employee Name</th>
                        <th>Code</th>
                        <th>Designation</th>
                        <th class="text-center">Working</th>
                        <th class="text-center text-danger">LOP</th>
                        <th class="text-right">Net Salary</th>
                        <th class="text-center">Action</th>
                    </tr>
                </thead>
                <tbody>
                    @foreach($employees as $emp)
                    @php
                        $sal = $salaries->get($emp->id);
                        $basic = $sal ? $sal->base_salary : $emp->base_salary;
                        $designation = $sal ? $sal->designation : ($emp->designation ?? 'Staff');
                        $department = $sal ? $sal->department : ($emp->department ?? 'Operations');
                        $empCode = $sal ? $sal->employee_code : "ICA01{$emp->id}";
                        $workingDays = $sal ? $sal->working_days : $emp->calculated_working_days;
                        $lopDays = $sal ? $sal->lop_days : $emp->calculated_lop_days;
                        
                        $dynAdditionsTotal = 0;
                        foreach($emp->additions as $dynAdd) { 
                            if ($dynAdd->value_type === 'percentage') {
                                $dynAdditionsTotal += ($basic * ($dynAdd->percentage / 100));
                            } else {
                                $dynAdditionsTotal += $dynAdd->amount; 
                            }
                        }
                        
                        $grossEarnings = $basic + $dynAdditionsTotal;
                        
                        $dynDeductionsTotal = 0;
                        foreach($emp->deductions as $dynDed) {
                             if ($dynDed->value_type === 'fixed') {
                                 $dynDeductionsTotal += $dynDed->amount;
                             } else {
                                 $dynDeductionsTotal += ($grossEarnings * ($dynDed->percentage / 100));
                             }
                        }
                        
                        $grossDeductions = $dynDeductionsTotal;
                        $reimb = $sal->expense_reimbursements ?? 0;
                        $netPay = $grossEarnings - $grossDeductions + $reimb;

                        $encodedAdditions = $emp->additions->map(function($a) {
                            return [
                                "id" => $a->addition_type_id,
                                "name" => $a->additionType->name ?? 'Addition',
                                "value_type" => $a->value_type,
                                "amount" => $a->amount,
                                "percentage" => $a->percentage
                            ];
                        })->toJson();

                        $encodedDeductions = $emp->deductions->map(function($d) {
                            return [
                                "id" => $d->deduction_type_id,
                                "name" => $d->deductionType->name ?? 'Deduction',
                                "value_type" => $d->value_type,
                                "percentage" => $d->percentage,
                                "amount" => $d->amount
                            ];
                        })->toJson();
                    @endphp
                    <tr data-emp-id="{{ $emp->id }}">
                        <td class="text-center"><input type="checkbox" class="row-select" checked></td>
                        <td class="sticky-col-1">
                            <span class="font-weight-bold">{{ $emp->name }}</span>
                            {{-- Legacy Hidden State --}}
                            <input type="hidden" data-key="employee_name" value="{{ $emp->name }}">
                            <input type="hidden" data-key="employee_code" value="{{ $empCode }}">
                            <input type="hidden" data-key="designation" value="{{ $designation }}">
                            <input type="hidden" data-key="department" value="{{ $department }}">
                            <input type="hidden" data-key="working_days" value="{{ $workingDays }}">
                            <input type="hidden" data-key="lop_days" value="{{ $lopDays }}">
                            <input type="hidden" data-key="base_salary" value="{{ $basic }}">
                            <input type="hidden" data-key="gross_earnings" value="{{ $grossEarnings }}">
                            <input type="hidden" data-key="gross_deductions" value="{{ $grossDeductions }}">
                            <input type="hidden" data-key="expense_reimbursements" value="{{ $reimb }}">
                            <input type="hidden" data-key="net_pay" value="{{ $netPay }}">
                            <input type="hidden" data-key="additions" value='{!! $encodedAdditions !!}'>
                            <input type="hidden" data-key="deductions" value='{!! $encodedDeductions !!}'>
                        </td>
                        <td>{{ $empCode }}</td>
                        <td><span class="badge badge-light border">{{ $designation }}</span></td>
                        <td class="text-center row-working-days">{{ $workingDays }}</td>
                        <td class="text-center row-lop-days">{{ $lopDays }}</td>
                        <td class="text-right row-net-pay">{{ number_format($netPay, 2) }}</td>
                        <td class="text-center">
                            <button class="btn-crm-edit btn-edit-payroll" title="Manual Adjustment">
                                <i class="fas fa-edit"></i>
                            </button>
                        </td>
                    </tr>
                    @endforeach
                </tbody>
            </table>
        </div>
    </div>
    <div class="card-footer">
        <small class="text-muted"><i class="fas fa-info-circle mr-1"></i> Net Salary = (Basic + Fixed Additions) - (Deductions % of Gross) + Reimbursements.</small>
    </div>
</div>
@endsection

@section('modals')
<div class="modal fade" id="payrollModal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header bg-primary py-2 text-white">
                <h5 class="modal-title font-weight-bold" id="modalEmpName">Edit Payroll</h5>
                <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body p-4">
                <form id="payrollEditForm">
                    <input type="hidden" id="modalEmpId">
                    <div class="row">
                        <div class="col-md-4">
                            <div class="form-group">
                                <label class="small font-weight-bold">Emp Code</label>
                                <input type="text" class="form-control form-control-sm" id="modal_employee_code">
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="form-group">
                                <label class="small font-weight-bold">Designation</label>
                                <input type="text" class="form-control form-control-sm" id="modal_designation">
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="form-group">
                                <label class="small font-weight-bold">Base Salary</label>
                                <input type="number" step="0.01" class="form-control form-control-sm modal-calc-trigger" id="modal_base_salary">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label class="small font-weight-bold">Working Days</label>
                                <input type="number" class="form-control form-control-sm modal-calc-trigger" id="modal_working_days">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label class="small font-weight-bold text-danger">LOP Days</label>
                                <input type="number" class="form-control form-control-sm modal-calc-trigger text-danger" id="modal_lop_days">
                            </div>
                        </div>
                    </div>

                    <div id="dynamicAdditionsContainer" class="row border-top pt-3"></div>
                    <div class="row mb-3">
                        <div class="col-md-12">
                            <div class="bg-light p-2 text-right">
                                <span class="small font-weight-bold text-muted mr-2">Calculated Gross:</span>
                                <span class="font-weight-bold" id="gross_display">0.00</span>
                                <input type="hidden" id="modal_gross_earnings">
                            </div>
                        </div>
                    </div>

                    <div id="dynamicDeductionsContainer" class="row border-top pt-3"></div>
                    <div class="row mb-3">
                        <div class="col-md-12">
                             <div class="bg-light p-2 text-right">
                                <span class="small font-weight-bold text-muted mr-2">Calculated Total Deductions:</span>
                                <span class="font-weight-bold text-danger" id="deduction_display">0.00</span>
                                <input type="hidden" id="modal_gross_deductions">
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6 ml-auto">
                            <div class="form-group text-right">
                                <label class="small font-weight-bold">Reimbursements</label>
                                <input type="number" step="0.01" class="form-control form-control-sm modal-calc-trigger" id="modal_expense_reimbursements">
                            </div>
                        </div>
                    </div>

                    <div class="bg-success p-3 rounded text-center shadow-inner mt-2">
                        <h4 class="mb-0 font-weight-bold">NET PAYABLE: <span id="modal_net_pay_display">0.00</span></h4>
                        <input type="hidden" id="modal_net_pay">
                    </div>
                </form>
            </div>
            <div class="modal-footer bg-light p-2">
                <button type="button" class="btn btn-secondary btn-sm" data-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-primary btn-sm px-4" id="saveModalChanges">Apply Adjusted Payload</button>
            </div>
        </div>
    </div>
</div>
@endsection

@push('scripts')
<script>
$(function() {
    function updateGlobalTotals() {
        let totalNet = 0;
        let totalDed = 0;
        let count = 0;

        $('.row-select:checked').each(function() {
            const row = $(this).closest('tr');
            totalNet += parseFloat(row.find('[data-key="net_pay"]').val()) || 0;
            totalDed += parseFloat(row.find('[data-key="gross_deductions"]').val()) || 0;
            count++;
        });

        $('#widget_total_net_pay').text(totalNet.toLocaleString('en-US', {minimumFractionDigits: 2}));
        $('#widget_total_deductions').text(totalDed.toLocaleString('en-US', {minimumFractionDigits: 2}));
        $('#widget_total_count').text(count);
    }

    // Initial load
    updateGlobalTotals();

    function calculateModal() {
        const basic = parseFloat($('#modal_base_salary').val()) || 0;
        let dynamicAdditions = 0;
        $('.modal-dynamic-addition').each(function() {
            const val = parseFloat($(this).val()) || 0;
            const type = $(this).data('type');
            if (type === 'percentage') {
                dynamicAdditions += (basic * (val / 100));
            } else {
                dynamicAdditions += val;
            }
        });
        
        const grossEarnings = basic + dynamicAdditions;
        $('#modal_gross_earnings').val(grossEarnings.toFixed(2));
        $('#gross_display').text(grossEarnings.toLocaleString());

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

        $('#modal_gross_deductions').val(dynamicDeductions.toFixed(2));
        $('#deduction_display').text(dynamicDeductions.toLocaleString());

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

    $('body').on('click', '.btn-edit-payroll', function() {
        const row = $(this).closest('tr');
        const empId = row.data('emp-id');
        $('#modalEmpId').val(empId);
        $('#modalEmpName').text('Edit Payroll: ' + row.find('[data-key="employee_name"]').val());

        row.find('input[type="hidden"]').each(function() {
            const key = $(this).data('key');
            if (key !== 'additions' && key !== 'deductions') {
                $(`#modal_${key}`).val($(this).val());
            }
        });

        const additions = JSON.parse(row.find('[data-key="additions"]').val() || '[]');
        $('#dynamicAdditionsContainer').empty();
        additions.forEach(add => {
            const isPerc = add.value_type === 'percentage';
            const displayVal = isPerc ? add.percentage : add.amount;
            const labelSuffix = isPerc ? '(%)' : '';
            $('#dynamicAdditionsContainer').append(`
                <div class="col-md-4">
                    <div class="form-group">
                        <label class="small font-weight-bold text-muted">${add.name} ${labelSuffix}</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}" data-type="${add.value_type}" value="${displayVal}">
                    </div>
                </div>
            `);
        });

        const deductions = JSON.parse(row.find('[data-key="deductions"]').val() || '[]');
        $('#dynamicDeductionsContainer').empty();
        deductions.forEach(ded => {
            const isFixed = ded.value_type === 'fixed';
            const displayVal = isFixed ? ded.amount : ded.percentage;
            const labelSuffix = isFixed ? '' : '(%)';
            $('#dynamicDeductionsContainer').append(`
                <div class="col-md-6">
                    <div class="form-group">
                        <label class="small font-weight-bold text-muted">${ded.name} ${labelSuffix}</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}" data-type="${ded.value_type}" value="${displayVal}">
                    </div>
                </div>
            `);
        });

        calculateModal();
        $('#payrollModal').modal('show');
    });

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

    $('#selectAll').on('change', function() {
        $('.row-select').prop('checked', $(this).prop('checked'));
        updateGlobalTotals();
    });

    $('body').on('change', '.row-select', function() {
        updateGlobalTotals();
    });

    $('#saveModalChanges').click(function() {
        const empId = $('#modalEmpId').val();
        const row = $(`tr[data-emp-id="${empId}"]`);

        $('#payrollEditForm input').each(function() {
            const id = $(this).attr('id');
            if (id && id.startsWith('modal_') && !$(this).hasClass('modal-dynamic-addition') && !$(this).hasClass('modal-dynamic-deduction')) {
                const key = id.replace('modal_', '');
                row.find(`input[data-key="${key}"]`).val($(this).val());
            }
        });

        row.find('.row-working-days').text($('#modal_working_days').val());
        row.find('.row-lop-days').text($('#modal_lop_days').val());
        row.find('.row-net-pay').text(parseFloat($('#modal_net_pay').val()).toLocaleString('en-US', {minimumFractionDigits: 2}));
        
        const additions = [];
        $('.modal-dynamic-addition').each(function() {
            const val = $(this).val();
            const type = $(this).data('type');
            additions.push({ 
                id: $(this).data('id'), 
                name: $(this).data('name'), 
                value_type: type,
                amount: type === 'fixed' ? val : 0,
                percentage: type === 'percentage' ? val : 0
            });
        });
        row.find('[data-key="additions"]').val(JSON.stringify(additions));

        const deductions = [];
        $('.modal-dynamic-deduction').each(function() {
            const val = $(this).val();
            const type = $(this).data('type');
            deductions.push({ 
                id: $(this).data('id'), 
                name: $(this).data('name'), 
                value_type: type,
                percentage: type === 'percentage' ? val : 0,
                amount: type === 'fixed' ? val : 0
            });
        });
        row.find('[data-key="deductions"]').val(JSON.stringify(deductions));

        $('#payrollModal').modal('hide');
        updateGlobalTotals();
    });

    $('#finalizeBatch').click(function() {
        const btn = $(this);
        const originalHtml = btn.html();
        
        const salaries = {};
        const rowsToProcess = $('#payrollGrid tbody tr').filter(function() {
            return $(this).find('.row-select').is(':checked');
        });

        if (rowsToProcess.length === 0) {
            Swal.fire({ icon: 'warning', title: 'Selection Error', text: 'Select at least one employee.' });
            return;
        }

        rowsToProcess.each(function() {
            const row = $(this);
            const empId = row.data('emp-id');
            const rowData = {};
            row.find('input[type="hidden"]').each(function() {
                rowData[$(this).data('key')] = $(this).val();
            });
            salaries[empId] = rowData;
        });

        const data = {
            _token: "{{ csrf_token() }}",
            month: "{{ $month }}",
            year: "{{ $year }}",
            salaries: salaries
        };

        btn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin mr-1"></i>Finalizing...');

        $.ajax({
            url: "{{ route('salaries.bulk.save') }}",
            type: 'POST',
            data: JSON.stringify(data),
            contentType: 'application/json',
            success: function(response) {
                Swal.fire({ icon: 'success', title: 'Success', text: 'Batch finalized!', timer: 1500, showConfirmButton: false }).then(() => {
                    window.location.reload();
                });
            },
            error: function(xhr) {
                btn.prop('disabled', false).html(originalHtml);
                Swal.fire({ icon: 'error', title: 'Error', text: xhr.responseJSON.error || 'Ajax failure.' });
            }
        });
    });
});
</script>
@endpush
