@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-gross-earnings { font-weight: 700; color: #007bff; }
    
    .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', 'Master Payroll Report')

@section('panel-actions')
    <button id="saveReport" class="btn btn-primary btn-sm px-3 shadow-sm">
        <i class="fas fa-sync-alt mr-1"></i> Sync to Payslips
    </button>
@endsection

@section('content')
<div class="card card-outline card-info">
    <div class="card-header">
        <h3 class="card-title"><i class="fas fa-file-excel mr-2"></i>Master Payroll Interface</h3>
        <div class="card-tools">
            <form id="filterForm" class="form-inline">
                <select name="month" id="month" class="form-control form-control-sm mr-2">
                    @for($i=1; $i<=12; $i++)
                        <option value="{{ $i }}" {{ request('month', date('m')) == $i ? 'selected' : '' }}>{{ date('F', mktime(0, 0, 0, $i, 10)) }}</option>
                    @endfor
                </select>
                <input type="number" name="year" id="year" class="form-control form-control-sm mr-2" style="width: 80px;" value="{{ request('year', date('Y')) }}">
                <button type="submit" class="btn btn-default btn-sm"><i class="fas fa-search"></i></button>
            </form>
        </div>
    </div>
    <div class="card-body p-0">
        <div class="excel-container">
            <table class="excel-table" id="payrollTable">
                <thead>
                    <tr>
                        <th class="sticky-col-1">Employee Name</th>
                        <th>Emp Code</th>
                        <th class="text-center">Working</th>
                        <th class="text-center text-danger">LOP</th>
                        <th class="text-right">Gross Earnings</th>
                        <th class="text-center" style="width: 150px;">Operations</th>
                    </tr>
                </thead>
                <tbody id="payrollData">
                    <!-- Loaded via AJAX -->
                </tbody>
            </table>
        </div>
    </div>
    <div class="card-footer">
        <small class="text-muted"><i class="fas fa-lightbulb mr-1"></i> Changes made here are persistent. Click Sync to update all employee payslips for the selected period.</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-info py-2 text-white">
                <h5 class="modal-title font-weight-bold" id="modalEmpName">Edit Report Row</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 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">Total Gross:</span>
                                <span class="font-weight-bold text-primary" 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">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-info p-3 rounded text-center shadow-inner mt-2">
                        <h4 class="mb-0 font-weight-bold text-white">REVISED NET: <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-info btn-sm px-4 text-white" id="saveModalChanges">Apply Row Adjustment</button>
            </div>
        </div>
    </div>
</div>
@endsection

@push('scripts')
<script>
$(function() {
    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));
        $('#gross_display').text(grossEarnings.toLocaleString());

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

    function loadReport() {
        const params = $('#filterForm').serialize();
        $('#payrollData').html('<tr><td colspan="6" class="text-center p-5"><i class="fas fa-spinner fa-spin mr-2"></i>Gathering Report Data...</td></tr>');
        
        $.get("{{ route('salaries.report.data') }}?" + params, function(response) {
            const container = $('#payrollData');
            container.empty();
            if(response.data.length === 0) {
                container.append('<tr><td colspan="6" class="text-center p-5 text-muted">No records found for this period.</td></tr>');
                return;
            }
            response.data.forEach(sal => {
                const empCode = sal.employee_code || 'ICA01' + sal.employee_id;
                container.append(`
                    <tr data-emp-id="${sal.employee_id}">
                        <td class="d-none">
                            <input type="hidden" data-key="employee_email" value="${sal.employee_email || ''}">
                            <input type="hidden" data-key="employee_code" value="${empCode}">
                            <input type="hidden" data-key="employee_name" value="${sal.employee}">
                            <input type="hidden" data-key="designation" value="${sal.employee_designation || 'Staff'}">
                            <input type="hidden" data-key="department" value="${sal.employee_department || 'Operations'}">
                            <input type="hidden" data-key="working_days" value="${sal.working_days}">
                            <input type="hidden" data-key="lop_days" value="${sal.lop_days}">
                            <input type="hidden" data-key="base_salary" value="${sal.base_salary}">
                            <input type="hidden" data-key="gross_earnings" value="${sal.gross_earnings}">
                            <input type="hidden" data-key="gross_deductions" value="${sal.gross_deductions}">
                            <input type="hidden" data-key="expense_reimbursements" value="${sal.expense_reimbursements || 0}">
                            <input type="hidden" data-key="net_pay" value="${sal.net_pay || sal.net_salary}">
                            <input type="hidden" data-key="additions" value='${JSON.stringify(sal.components?.additions || [])}'>
                            <input type="hidden" data-key="deductions" value='${JSON.stringify(sal.components?.deductions || [])}'>
                        </td>
                        <td class="sticky-col-1 font-weight-bold">${sal.employee}</td>
                        <td class="text-muted">${empCode}</td>
                        <td class="text-center">${sal.working_days}</td>
                        <td class="text-center text-danger">${sal.lop_days}</td>
                        <td class="text-right row-gross-earnings">${parseFloat(sal.gross_earnings).toLocaleString('en-US', {minimumFractionDigits: 2})}</td>
                        <td class="text-center">
                            <div class="btn-group">
                                <a href="{{ url('payslips') }}/${sal.id}" target="_blank" class="btn btn-xs btn-default" title="View"><i class="fas fa-eye"></i></a>
                                <button class="btn btn-xs btn-info btn-edit-report" title="Edit"><i class="fas fa-edit"></i></button>
                                <button class="btn btn-xs btn-danger btn-delete-report" data-id="${sal.id}" title="Delete"><i class="fas fa-trash"></i></button>
                            </div>
                        </td>
                    </tr>
                `);
            });
        });
    }

    loadReport();
    $('#filterForm').submit(function(e) { e.preventDefault(); loadReport(); });

    $('body').on('click', '.btn-edit-report', function() {
        const row = $(this).closest('tr');
        const empId = row.data('emp-id');
        $('#modalEmpId').val(empId);
        $('#modalEmpName').text('Modify Report: ' + 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 => {
            $('#dynamicAdditionsContainer').append(`
                <div class="col-md-4">
                    <div class="form-group">
                        <label class="small font-weight-bold text-muted">${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>
                </div>
            `);
        });

        const deductions = JSON.parse(row.find('[data-key="deductions"]').val() || '[]');
        $('#dynamicDeductionsContainer').empty();
        deductions.forEach(ded => {
            $('#dynamicDeductionsContainer').append(`
                <div class="col-md-6">
                    <div class="form-group">
                        <label class="small font-weight-bold text-muted">${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>
                </div>
            `);
        });

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

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

    $('#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-gross-earnings').text(parseFloat($('#modal_gross_earnings').val()).toLocaleString('en-US', {minimumFractionDigits: 2}));
        
        const additions = [];
        $('.modal-dynamic-addition').each(function() {
            additions.push({ id: $(this).data('id'), name: $(this).data('name'), amount: $(this).val() });
        });
        row.find('[data-key="additions"]').val(JSON.stringify(additions));

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

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

    $('body').on('click', '.btn-delete-report', function() {
        const id = $(this).data('id');
        Swal.fire({
            title: 'Delete from report?',
            text: "This record will be removed permanently.",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#d33',
            confirmButtonText: 'Yes, delete it!'
        }).then((result) => {
            if (result.isConfirmed) {
                $.ajax({
                    url: "{{ url('salaries') }}/" + id,
                    type: 'DELETE',
                    data: { _token: "{{ csrf_token() }}" },
                    success: function() { loadReport(); Swal.fire({ icon: 'success', title: 'Removed!', timer: 1000, showConfirmButton: false }); }
                });
            }
        });
    });

    $('#saveReport').click(function() {
        const salaries = {};
        $('#payrollData tr').each(function() {
            const row = $(this);
            const empId = row.data('emp-id');
            if (!empId) return;
            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').val(), year: $('#year').val(), salaries: salaries };
        const btn = $(this);
        btn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin mr-2"></i>Syncing...');

        $.ajax({
            url: "{{ route('salaries.bulk.save') }}",
            type: 'POST',
            data: JSON.stringify(data),
            contentType: 'application/json',
            success: function() {
                Swal.fire({ icon: 'success', title: 'Data Synchronized', text: 'All changes reflected in payslips.' });
                btn.prop('disabled', false).html('<i class="fas fa-sync-alt mr-1"></i> Sync to Payslips');
            },
            error: function() {
                btn.prop('disabled', false).html('<i class="fas fa-sync-alt mr-1"></i> Sync to Payslips');
                Swal.fire({ icon: 'error', title: 'Sync Failed', text: 'Please check your connection.' });
            }
        });
    });
});
</script>
@endpush
