@extends('layouts.app')

@section('content')
<div class="container-fluid py-4">
    <div class="row">
        <div class="col-12">
            <div class="page-header" style="margin-bottom: 25px;">
                <div class="pull-right" style="margin-top: 20px;">
                    <a href="{{ route('salaries.index') }}" class="btn btn-default">
                        <i class="fas fa-arrow-left"></i> Back to List
                    </a>
                </div>
                <h2 class="fw-bold text-primary" style="margin-bottom: 5px;">Generate Monthly Payroll</h2>
                <p class="text-muted">Breakdown earnings and deductions according to high-end enterprise standards.</p>
                <div class="clearfix"></div>
            </div>

            <form action="{{ route('salaries.store') }}" method="POST" id="payroll-form">
                @csrf
                
                <!-- Step 1: Employee & Period -->
                <div class="panel panel-default mb-4">
                    <div class="panel-body" style="padding: 25px;">
                        <div class="row">
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label class="control-label text-uppercase small fw-bold text-muted">Employee Selection</label>
                                    <select name="employee_id" id="employee_id" class="form-control select2-ajax w-100" required>
                                        <option value="">Search for an employee...</option>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-2">
                                <div class="form-group">
                                    <label class="control-label text-uppercase small fw-bold text-muted">Payroll Month</label>
                                    <select name="month" class="form-control" required>
                                        @for($i=1; $i<=12; $i++)
                                            <option value="{{ $i }}" {{ old('month', date('m')) == $i ? 'selected' : '' }}>
                                                {{ date('F', mktime(0, 0, 0, $i, 10)) }}
                                            </option>
                                        @endfor
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-2">
                                <div class="form-group">
                                    <label class="control-label text-uppercase small fw-bold text-muted">Payroll Year</label>
                                    <input type="number" name="year" class="form-control" value="{{ old('year', date('Y')) }}" required>
                                </div>
                            </div>
                            <div class="col-md-2">
                                <div class="form-group">
                                    <label class="control-label text-uppercase small fw-bold text-muted">Working Days</label>
                                    <input type="number" name="working_days" id="working_days" class="form-control" value="30" required>
                                </div>
                            </div>
                            <div class="col-md-2">
                                <div class="form-group">
                                    <label class="control-label text-uppercase small fw-bold text-muted">LOP Days</label>
                                    <input type="number" name="lop_days" id="lop_days" class="form-control" value="0" required>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="row">
                    <!-- Step 2: Earnings -->
                    <div class="col-lg-6">
                        <div class="panel panel-default" style="height: 100%;">
                            <div class="panel-heading">
                                <span class="label label-success pull-right" style="margin-top: 3px;">Total: {{ $settings->currency_symbol ?? '₹' }}<span id="gross_earnings_display">0.00</span></span>
                                <h5 class="panel-title mb-0 fw-bold"><i class="fas fa-hand-holding-dollar text-success" style="margin-right: 5px;"></i>Earnings (Monthly)</h5>
                            </div>
                            <div class="panel-body">
                            
                            <div class="row mb-3">
                                <label class="col-sm-4 col-form-label pb-0">Basic Pay</label>
                                <div class="col-sm-8">
                                    <input type="number" step="0.01" name="base_salary" id="base_salary" class="form-control calc-input" required>
                                    <small class="text-muted">Master Basic from profile.</small>
                                </div>
                            </div>
                            
                            <div class="row mb-3">
                                <label class="col-sm-4 col-form-label">HRA</label>
                                <div class="col-sm-8">
                                    <input type="number" step="0.01" name="hra" id="hra" class="form-control calc-input" placeholder="0.00">
                                </div>
                            </div>

                            <div class="row mb-3">
                                <label class="col-sm-4 col-form-label">Special Allowance</label>
                                <div class="col-sm-8">
                                    <input type="number" step="0.01" name="special_allowance" id="special_allowance" class="form-control calc-input" placeholder="0.00">
                                </div>
                            </div>

                            <div class="row mb-3">
                                <label class="col-sm-4 col-form-label">Conveyance</label>
                                <div class="col-sm-8">
                                    <input type="number" step="0.01" name="conveyance" id="conveyance" class="form-control calc-input" placeholder="0.00">
                                </div>
                            </div>

                            <div class="row mb-3">
                                <label class="col-sm-4 col-form-label">Medical</label>
                                <div class="col-sm-8">
                                    <input type="number" step="0.01" name="medical" id="medical" class="form-control calc-input" placeholder="0.00">
                                </div>
                            </div>

                            <div class="row mb-3">
                                <label class="col-sm-4 col-form-label">LTA</label>
                                <div class="col-sm-8">
                                    <input type="number" step="0.01" name="lta" id="lta" class="form-control calc-input" placeholder="0.00">
                                </div>
                            </div>

                            <input type="hidden" name="gross_earnings" id="gross_earnings" value="0">
                        </div>
                    </div>

                    <!-- Step 3: Deductions -->
                    <div class="col-lg-6">
                        <div class="panel panel-default" style="height: 100%;">
                            <div class="panel-heading">
                                <span class="label label-danger pull-right" style="margin-top: 3px;">Total: {{ $settings->currency_symbol ?? '₹' }}<span id="gross_deductions_display">0.00</span></span>
                                <h5 class="panel-title mb-0 fw-bold"><i class="fas fa-hand-holding-heart text-danger" style="margin-right: 5px;"></i>Deductions (Monthly)</h5>
                            </div>
                            <div class="panel-body">

                            <div class="row mb-3">
                                <label class="col-sm-5 col-form-label">ESIC (Employee)</label>
                                <div class="col-sm-7">
                                    <input type="number" step="0.01" name="esic_employee" id="esic_employee" class="form-control calc-input" placeholder="0.00">
                                </div>
                            </div>

                            <div class="row mb-3">
                                <label class="col-sm-5 col-form-label">ESIC (Employer)</label>
                                <div class="col-sm-7">
                                    <input type="number" step="0.01" name="esic_employer" id="esic_employer" class="form-control calc-input" placeholder="0.00">
                                </div>
                            </div>

                            <div class="row mb-3">
                                <label class="col-sm-5 col-form-label">Gratuity Provision</label>
                                <div class="col-sm-7">
                                    <input type="number" step="0.01" name="gratuity" id="gratuity" class="form-control calc-input" placeholder="0.00">
                                </div>
                            </div>

                            <div class="row mb-3">
                                <label class="col-sm-5 col-form-label">Professional Tax</label>
                                <div class="col-sm-7">
                                    <input type="number" step="0.01" name="prof_tax" id="prof_tax" class="form-control calc-input" placeholder="0.00">
                                </div>
                            </div>

                            <div class="row mb-3">
                                <label class="col-sm-5 col-form-label">Income Tax (TDS)</label>
                                <div class="col-sm-7">
                                    <input type="number" step="0.01" name="income_tax" id="income_tax" class="form-control calc-input" placeholder="0.00">
                                </div>
                            </div>

                            <input type="hidden" name="gross_deductions" id="gross_deductions" value="0">
                            
                            <!-- Legacy Compatibility -->
                            <input type="hidden" name="bonus" id="legacy_bonus" value="0">
                            <input type="hidden" name="deductions" id="legacy_deductions" value="0">
                        </div>
                    </div>
                </div>

                <!-- Final Calculations -->
                <div class="panel panel-primary mt-4" style="margin-top: 25px; background: #f0f7ff;">
                    <div class="panel-body">
                        <div class="row">
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label class="control-label text-uppercase small fw-bold text-muted">Expense Reimbursements</label>
                                    <div class="input-group">
                                        <span class="input-group-addon bg-light">{{ $settings->currency_symbol ?? '₹' }}</span>
                                        <input type="number" step="0.01" name="expense_reimbursements" id="expense_reimbursements" class="form-control calc-input" placeholder="0.00">
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-8 text-right">
                                <p class="mb-0 text-muted small text-uppercase fw-bold">Calculated Net Pay</p>
                                <h2 class="mb-0 fw-bold text-primary" id="net_pay_display" style="margin-top: 0;">{{ $settings->currency_symbol ?? '₹' }}0.00</h2>
                                <input type="hidden" name="net_pay" id="net_pay" value="0">
                                <input type="hidden" name="net_salary" id="net_salary" value="0"> <!-- Legacy mapping -->
                            </div>
                        </div>
                    </div>
                </div>

                <div class="mt-4" style="margin-top: 25px; text-align: right;">
                    <a href="{{ route('salaries.index') }}" class="btn btn-default px-4">Cancel</a>
                    <button type="submit" class="btn btn-primary px-5">
                        <i class="fas fa-check-circle"></i> Finalize Payroll
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>
@endsection

@push('scripts')
<script>
$(function() {
    $('.select2-ajax').select2({
        theme: 'bootstrap',
        ajax: {
            url: "{{ 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...',
        minimumInputLength: 1
    });

    // Fetch employee data and auto-fill
    $('#employee_id').on('select2:select', function (e) {
        var id = e.params.data.id;
        $.ajax({
            url: "{{ url('employees') }}/" + id,
            type: 'GET',
            headers: { 'Accept': 'application/json' },
            success: function(data) {
                const basic = parseFloat(data.base_salary) || 0;
                $('#base_salary').val(basic);
                
                // Auto-calculation logic for standard components
                $('#hra').val((basic * 0.4).toFixed(2)); // Standard 40%
                $('#conveyance').val("1600.00"); // Standard fixed
                $('#medical').val("1250.00"); // Standard fixed
                
                // Initial calculation
                calculatePayroll();
            }
        });
    });

    function calculatePayroll() {
        // Earnings
        let basic = parseFloat($('#base_salary').val()) || 0;
        let hra = parseFloat($('#hra').val()) || 0;
        let sa = parseFloat($('#special_allowance').val()) || 0;
        let conv = parseFloat($('#conveyance').val()) || 0;
        let med = parseFloat($('#medical').val()) || 0;
        let lta = parseFloat($('#lta').val()) || 0;

        let grossEarnings = basic + hra + sa + conv + med + lta;
        $('#gross_earnings').val(grossEarnings);
        $('#gross_earnings_display').text(grossEarnings.toLocaleString('en-IN', { minimumFractionDigits: 2 }));

        // Auto-Deductions (ESIC)
        if (grossEarnings <= 21000) {
            $('#esic_employee').val((grossEarnings * 0.0075).toFixed(2));
            $('#esic_employer').val((grossEarnings * 0.0325).toFixed(2));
        } else {
            $('#esic_employee').val(0);
            $('#esic_employer').val(0);
        }

        // Deductions
        let esicEme = parseFloat($('#esic_employee').val()) || 0;
        let esicEmr = parseFloat($('#esic_employer').val()) || 0;
        let grat = parseFloat($('#gratuity').val()) || 0;
        let profTax = parseFloat($('#prof_tax').val()) || 0;
        let incTax = parseFloat($('#income_tax').val()) || 0;

        let grossDeductions = esicEme + profTax + incTax; // Employer side often excluded from Net but tracked
        $('#gross_deductions').val(grossDeductions);
        $('#gross_deductions_display').text(grossDeductions.toLocaleString('en-IN', { minimumFractionDigits: 2 }));

        // Final Pay
        let reimb = parseFloat($('#expense_reimbursements').val()) || 0;
        let netPay = grossEarnings - grossDeductions + reimb;

        $('#net_pay').val(netPay);
        $('#net_salary').val(netPay); // Legacy
        $('#net_pay_display').text('{{ $settings->currency_symbol ?? '₹' }}' + netPay.toLocaleString('en-IN', { minimumFractionDigits: 2 }));
    }

    $('.calc-input').on('input', function() {
        calculatePayroll();
    });

    // Handle AJAX form submission for better feedback
    $('#payroll-form').on('submit', function(e) {
        e.preventDefault();
        const btn = $(this).find('button[type="submit"]');
        const originalText = btn.html();
        btn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin me-1"></i> Processing...');

        $.ajax({
            url: $(this).attr('action'),
            type: 'POST',
            data: $(this).serialize(),
            success: function(response) {
                Swal.fire({
                    icon: 'success',
                    title: 'Payroll Generated',
                    text: response.success,
                    showConfirmButton: false,
                    timer: 2000
                }).then(() => {
                    window.location.href = "{{ route('salaries.index') }}";
                });
            },
            error: function(xhr) {
                btn.prop('disabled', false).html(originalText);
                let errors = xhr.responseJSON.errors;
                let errorMsg = '';
                for (let key in errors) {
                    errorMsg += errors[key][0] + '<br>';
                }
                Swal.fire({
                    icon: 'error',
                    title: 'Generation Failed',
                    html: errorMsg
                });
            }
        });
    });
});
</script>
@endpush
