@extends('layouts.dashboard.superadminapp')

@section('title', 'Employee Salary Details')

@section('styles')
<!-- Select2 CSS -->
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<link href="https://cdn.jsdelivr.net/npm/select2-bootstrap-5-theme@1.3.0/dist/select2-bootstrap-5-theme.min.css" rel="stylesheet" />
<style>
    div.dt-buttons {
        float: left;
        display: flex !important;
    }
    .dataTable {
        overflow-x: auto !important;
        display: table !important;
    }
    .dt-buttons .btn {
        margin-right: 0.5rem !important;
        padding: 0.25rem 0.75rem !important;
        font-size: 0.95rem !important;
    }
    /* Select2 styling */
    .select2-container--bootstrap-5 .select2-selection {
        min-height: 38px;
    }
    .select2-container--bootstrap-5 .select2-selection--multiple .select2-selection__rendered {
        padding: 0 0.375rem;
    }
    .select2-container--bootstrap-5 .select2-selection--multiple .select2-selection__choice {
        background-color: #4e73df;
        border: none;
        color: #fff;
        padding: 2px 8px;
        margin: 3px 3px 3px 0;
    }
    .select2-container--bootstrap-5 .select2-selection--multiple .select2-selection__choice__remove {
        color: #fff;
        margin-right: 5px;
    }
</style>
@endsection

@section('content')

<!-- Page Heading -->
<x-layout.page-header title="UEPL | Employee Salary Details" icon="user-tie" iconColor="primary" />

<!-- Generate Payroll Card -->
<div class="card shadow mb-4">
    <div class="card-header py-3" style="background: linear-gradient(135deg, #28a745 0%, #218838 100%);">
        <h6 class="m-0 font-weight-bold text-white">
            <i class="fas fa-calculator mr-2"></i> Auto Generate Payroll
        </h6>
    </div>
    <div class="card-body">
        <form id="generatePayrollForm">
            @csrf
            <div class="row align-items-end">
                <div class="col-md-3 mb-3">
                    <label class="small font-weight-bold">Select Month <span class="text-danger">*</span></label>
                    <input type="month" class="form-control" id="generate_month" name="month_year" value="{{ date('Y-m') }}" required>
                </div>
                <div class="col-md-3 mb-3">
                    <label class="small font-weight-bold">Department (Optional)</label>
                    <select class="form-control" id="generate_department" name="department">
                        <option value="">All Departments</option>
                        @php
                            $departments = \App\Models\EmployeeDetails::distinct()->pluck('department')->filter()->values();
                        @endphp
                        @foreach($departments as $dept)
                            <option value="{{ $dept }}">{{ $dept }}</option>
                        @endforeach
                    </select>
                </div>
                <div class="col-md-3 mb-3">
                    <label class="small font-weight-bold">Employee(s) (Optional)</label>
                    <select class="form-control" id="generate_employee" name="employee_id[]" multiple>
                        @foreach($employees as $emp)
                            <option value="{{ $emp->id }}" data-department="{{ $emp->department }}">{{ $emp->employee_id }} - {{ $emp->name }}</option>
                        @endforeach
                    </select>
                    <small class="text-muted">Leave empty for all employees</small>
                </div>
                <div class="col-md-3 mb-3">
                    <button type="submit" class="btn btn-success btn-block" id="generateBtn">
                        <i class="fas fa-cogs mr-1"></i> Generate Payroll
                    </button>
                </div>
            </div>
        </form>
        <div class="alert alert-info small mb-0">
            <i class="fas fa-info-circle mr-1"></i>
            <strong>Auto-calculation:</strong> Payroll will be calculated based on attendance records, approved leaves, OT hours, and salary structure (incentive per hour). Employees without salary structure will be skipped.
        </div>
    </div>
</div>

<!-- Filter Card -->
<div class="card shadow mb-4">
    <div class="card-header py-3" style="background: linear-gradient(135deg, #6c757d 0%, #495057 100%);">
        <h6 class="m-0 font-weight-bold text-white">
            <i class="fas fa-filter mr-2"></i> Filter Salary Records
        </h6>
    </div>
    <div class="card-body">
        <form id="filterForm">
            <div class="row align-items-end">
                <div class="col-md-3 mb-3">
                    <label class="small font-weight-bold">Month & Year</label>
                    <input type="month" class="form-control" id="filter_month" name="month_year">
                </div>
                <div class="col-md-3 mb-3">
                    <label class="small font-weight-bold">Department</label>
                    <select class="form-control" id="filter_department" name="department">
                        <option value="">All Departments</option>
                        @foreach($departments as $dept)
                            <option value="{{ $dept }}">{{ $dept }}</option>
                        @endforeach
                    </select>
                </div>
                <div class="col-md-3 mb-3">
                    <label class="small font-weight-bold">Employee(s)</label>
                    <select class="form-control" id="filter_employee" name="employee_id[]" multiple>
                        @foreach($employees as $emp)
                            <option value="{{ $emp->id }}" data-department="{{ $emp->department }}">{{ $emp->employee_id }} - {{ $emp->name }}</option>
                        @endforeach
                    </select>
                    <small class="text-muted">Leave empty for all employees</small>
                </div>
                <div class="col-md-3 mb-3">
                    <button type="submit" class="btn btn-primary">
                        <i class="fas fa-search mr-1"></i> Apply Filter
                    </button>
                    <button type="button" class="btn btn-secondary" id="clearFilterBtn">
                        <i class="fas fa-times mr-1"></i> Clear
                    </button>
                </div>
            </div>
        </form>
    </div>
</div>

<!-- Alerts -->
@if(session('success'))
    <div class="alert alert-success alert-dismissible fade show" role="alert">
        <i class="fas fa-check-circle mr-2"></i>{{ session('success') }}
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">&times;</span>
        </button>
    </div>
@endif
@if(session('error'))
    <div class="alert alert-danger alert-dismissible fade show" role="alert">
        <i class="fas fa-exclamation-circle mr-2"></i>{{ session('error') }}
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">&times;</span>
        </button>
    </div>
@endif

<!-- Salary Details Card -->
<div class="card shadow mb-4">
    <div class="card-header py-3 d-flex justify-content-between align-items-center" style="background: linear-gradient(135deg, #4e73df 0%, #224abe 100%);">
        <h6 class="m-0 font-weight-bold text-white">
            <i class="fas fa-money-check-alt mr-2"></i> Salary Details List
        </h6>
        <div>
            <button class="btn btn-warning btn-sm mr-2" id="downloadSelectedBtn" style="display: none;">
                <i class="fas fa-file-archive mr-1"></i> Download Selected Payslips (<span id="selectedCount">0</span>)
            </button>
            <button class="btn btn-light btn-sm" id="addSalaryBtn">
                <i class="fas fa-plus mr-1"></i> Add Salary Details
            </button>
        </div>
    </div>
    <div class="card-body">
        <div class="mb-2">
            <button class="btn btn-outline-secondary btn-sm" id="selectAllBtn">
                <i class="fas fa-check-square mr-1"></i> Select All
            </button>
            <button class="btn btn-outline-secondary btn-sm" id="deselectAllBtn">
                <i class="fas fa-square mr-1"></i> Deselect All
            </button>
            <button class="btn btn-success btn-sm ml-2" id="bulkApproveBtn" style="display: none;">
                <i class="fas fa-check mr-1"></i> Approve Selected
            </button>
            <button class="btn btn-danger btn-sm" id="bulkRejectBtn" style="display: none;">
                <i class="fas fa-times mr-1"></i> Reject Selected
            </button>
            <span class="ml-3 text-muted small" id="selectionInfo"></span>
        </div>
        <div class="table-responsive">
            <table class="table table-bordered table-striped table-sm" id="salaryTable" width="100%" cellspacing="0">
                <thead class="thead-light">
                    <tr>
                        <th width="40" class="text-center">
                            <input type="checkbox" id="checkAll" title="Select All">
                        </th>
                        <th>Month & Year</th>
                        <th>Employee ID</th>
                        <th>Employee Name</th>
                        <th>Basic & DA</th>
                        <th>HRA</th>
                        <th>Conveyance</th>
                        <th>Washing Allow.</th>
                        <th>Fixed Salary</th>
                        <th>Days Worked</th>
                        <th>Leave Given</th>
                        <th>Total Days</th>
                        <th>Drawn Salary</th>
                        <th>Incentive Hrs</th>
                        <th>Incentive Rate</th>
                        <th>Incentive Amt</th>
                        <th>Attendance Bonus</th>
                        <th>Gross Salary</th>
                        <th>ESI</th>
                        <th>PF</th>
                        <th>PT</th>
                        <th>Advance Ded.</th>
                        <th>Net Salary</th>
                        <th>Payment Mode</th>
                        <th>Status</th>
                        <th width="150" class="text-center">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    @foreach($salaryDetails as $salary)
                        <tr id="row-{{ $salary->id }}">
                            <td class="text-center">
                                <input type="checkbox" class="salary-checkbox" value="{{ $salary->id }}"
                                       data-employee="{{ $salary->employee->name ?? 'Unknown' }}"
                                       data-month="{{ $salary->month_year }}">
                            </td>
                            <td>{{ \Carbon\Carbon::parse($salary->month_year)->format('M Y') }}</td>
                            <td>{{ $salary->employee->employee_id ?? '-' }}</td>
                            <td>{{ $salary->employee->name ?? '-' }}</td>
                            <td>{{ number_format($salary->basic_da, 2) }}</td>
                            <td>{{ number_format($salary->hra, 2) }}</td>
                            <td>{{ number_format($salary->conveyance, 2) }}</td>
                            <td>{{ number_format($salary->washing_allowance, 2) }}</td>
                            <td>{{ number_format($salary->fixed_salary, 2) }}</td>
                            <td>{{ intval($salary->no_of_days_worked) }}</td>
                            <td>{{ intval($salary->leave_given) }}</td>
                            <td>{{ intval($salary->total_days_for_salary) }}</td>
                            <td>{{ number_format($salary->drawn_salary, 2) }}</td>
                            <td>{{ $salary->incentive_hrs }}</td>
                            <td>{{ number_format($salary->incentive_rate, 2) }}</td>
                            <td>{{ number_format($salary->incentive_amount, 2) }}</td>
                            <td>{{ number_format($salary->attendance_bonus, 2) }}</td>
                            <td><strong>{{ number_format($salary->gross_salary, 2) }}</strong></td>
                            <td>{{ number_format($salary->esi, 2) }}</td>
                            <td>{{ number_format($salary->pf, 2) }}</td>
                            <td>{{ number_format($salary->pt, 2) }}</td>
                            <td>{{ number_format($salary->advance_deduction, 2) }}</td>
                            <td><strong class="text-success">{{ number_format($salary->net_salary, 2) }}</strong></td>
                            <td>
                                @if($salary->payment_mode)
                                    <span class="badge badge-info">{{ $salary->payment_mode }}</span>
                                @else
                                    -
                                @endif
                            </td>
                            <td> 
                                @php $status = $salary->approval_status ?? 'pending'; @endphp
                                @if($status === 'approved')
                                    <span class="badge badge-success"><i class="fas fa-check mr-1"></i>Approved</span>
                                @elseif($status === 'rejected')
                                    <span class="badge badge-danger" title="{{ $salary->rejection_reason }}"><i class="fas fa-times mr-1"></i>Rejected</span>
                                @else
                                    <span class="badge badge-warning"><i class="fas fa-clock mr-1"></i>Pending</span>
                                @endif
                            </td>
                            <td>
                                <div class="text-center" style="white-space: nowrap;">
                                    @php $status = $salary->approval_status ?? 'pending'; @endphp
                                    @if($status === 'pending')
                                        <button class="btn btn-success btn-sm approve-btn" data-id="{{ $salary->id }}" title="Approve">
                                            <i class="fa fa-check"></i>
                                        </button>
                                        <button class="btn btn-danger btn-sm reject-btn" data-id="{{ $salary->id }}" title="Reject">
                                            <i class="fa fa-times"></i>
                                        </button>
                                    @endif
                                    <a href="{{ url('/superadmin/salary-details/' . $salary->id . '/payslip') }}" class="btn btn-info btn-sm" title="Download Payslip" target="_blank">
                                        <i class="fa fa-file-pdf"></i>
                                    </a>
                                    <button class="btn btn-warning btn-sm edit-btn" data-id="{{ $salary->id }}" title="Edit">
                                        <i class="fa fa-edit"></i>
                                    </button>
                                    <button class="btn btn-danger btn-sm delete-btn" data-id="{{ $salary->id }}" title="Delete">
                                        <i class="fa fa-trash"></i>
                                    </button>
                                </div>
                            </td>
                        </tr>
                    @endforeach
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Add/Edit Salary Modal -->
<div class="modal fade" id="salaryModal" tabindex="-1" role="dialog" aria-labelledby="salaryModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-xl" role="document">
        <div class="modal-content">
            <form id="salaryForm">
                @csrf
                <input type="hidden" id="salaryIdHidden" name="salaryIdHidden">
                <div class="modal-header" style="background: linear-gradient(135deg, #4e73df 0%, #224abe 100%);">
                    <h5 class="modal-title text-white" id="salaryModalLabel">
                        <i class="fas fa-plus-circle mr-2"></i> Add Salary Details
                    </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">
                    <div id="formError" class="alert alert-danger" style="display: none;"></div>

                    <!-- Row 1: Basic Info -->
                    <div class="row">
                        <div class="col-md-4 mb-3">
                            <label class="small font-weight-bold">Month & Year <span class="text-danger">*</span></label>
                            <input type="month" class="form-control" id="month_year" name="month_year" required>
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="small font-weight-bold">Employee ID <span class="text-danger">*</span></label>
                            <select class="form-control" id="employee_id" name="employee_id" required>
                                <option value="">Select Employee</option>
                                @foreach($employees as $employee)
                                    <option value="{{ $employee->id }}" data-name="{{ $employee->name }}">
                                        {{ $employee->employee_id }} - {{ $employee->name }}
                                    </option>
                                @endforeach
                            </select>
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="small font-weight-bold">Employee Name</label>
                            <input type="text" class="form-control" id="employee_name" name="employee_name" readonly>
                        </div>
                    </div>

                    <!-- Row 2: Salary Components -->
                    <div class="row">
                        <div class="col-md-3 mb-3">
                            <label class="small font-weight-bold">Basic & DA</label>
                            <input type="number" class="form-control" step="0.01" id="basic_da" name="basic_da">
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="small font-weight-bold">HRA</label>
                            <input type="number" class="form-control" step="0.01" id="hra" name="hra">
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="small font-weight-bold">Conveyance</label>
                            <input type="number" class="form-control" step="0.01" id="conveyance" name="conveyance">
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="small font-weight-bold">Washing Allowance</label>
                            <input type="number" class="form-control" step="0.01" id="washing_allowance" name="washing_allowance">
                        </div>
                    </div>

                    <!-- Row 3: Fixed & Days -->
                    <div class="row">
                        <div class="col-md-3 mb-3">
                            <label class="small font-weight-bold">Fixed Salary</label>
                            <input type="number" class="form-control" step="0.01" id="fixed_salary" name="fixed_salary">
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="small font-weight-bold">No. of Days Worked</label>
                            <input type="number" class="form-control" id="no_of_days_worked" name="no_of_days_worked">
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="small font-weight-bold">Leave Given</label>
                            <input type="number" class="form-control" id="leave_given" name="leave_given">
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="small font-weight-bold">Total Days for Salary</label>
                            <input type="number" class="form-control" id="total_days_for_salary" name="total_days_for_salary">
                        </div>
                    </div>

                    <!-- Row 4: Drawn & Incentive -->
                    <div class="row">
                        <div class="col-md-3 mb-3">
                            <label class="small font-weight-bold">Drawn Salary</label>
                            <input type="number" class="form-control" step="0.01" id="drawn_salary" name="drawn_salary">
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="small font-weight-bold">Incentive Hrs</label>
                            <input type="number" class="form-control" step="0.01" id="incentive_hrs" name="incentive_hrs">
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="small font-weight-bold">Incentive Rate</label>
                            <input type="number" class="form-control" step="0.01" id="incentive_rate" name="incentive_rate">
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="small font-weight-bold">Incentive Amount</label>
                            <input type="number" class="form-control" step="0.01" id="incentive_amount" name="incentive_amount">
                        </div>
                    </div>

                    <!-- Row 5: Bonus & Gross -->
                    <div class="row">
                        <div class="col-md-4 mb-3">
                            <label class="small font-weight-bold">Attendance Bonus</label>
                            <input type="number" class="form-control" step="0.01" id="attendance_bonus" name="attendance_bonus">
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="small font-weight-bold">Gross Salary</label>
                            <input type="number" class="form-control" step="0.01" id="gross_salary" name="gross_salary">
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="small font-weight-bold">ESI</label>
                            <input type="number" class="form-control" step="0.01" id="esi" name="esi">
                        </div>
                    </div>

                    <!-- Row 6: Deductions -->
                    <div class="row">
                        <div class="col-md-3 mb-3">
                            <label class="small font-weight-bold">PF</label>
                            <input type="number" class="form-control" step="0.01" id="pf" name="pf">
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="small font-weight-bold">PT</label>
                            <input type="number" class="form-control" step="0.01" id="pt" name="pt">
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="small font-weight-bold">Advance Deduction</label>
                            <input type="number" class="form-control" step="0.01" id="advance_deduction" name="advance_deduction">
                        </div>
                        <div class="col-md-3 mb-3">
                            <label class="small font-weight-bold">Net Salary</label>
                            <input type="number" class="form-control" step="0.01" id="net_salary" name="net_salary">
                        </div>
                    </div>

                    <!-- Row 7: Payment Mode -->
                    <div class="row">
                        <div class="col-md-4 mb-3">
                            <label class="small font-weight-bold">Payment Mode</label>
                            <select class="form-control" id="payment_mode" name="payment_mode">
                                <option value="">Select Payment Mode</option>
                                <option value="Cash">Cash</option>
                                <option value="Bank" selected>Bank Transfer</option>
                                <option value="Cheque">Cheque</option>
                                <option value="Other">Other</option>
                            </select>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary btn-sm" data-dismiss="modal">
                        <i class="fa fa-times mr-1"></i> Cancel
                    </button>
                    <button type="submit" class="btn btn-primary btn-sm" id="saveSalaryBtn">
                        <i class="fa fa-save mr-1"></i> Save Salary Details
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Rejection Modal -->
<div class="modal fade" id="rejectModal" tabindex="-1" role="dialog" aria-labelledby="rejectModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header bg-danger text-white">
                <h5 class="modal-title" id="rejectModalLabel">
                    <i class="fas fa-times-circle mr-2"></i> Reject 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">
                <input type="hidden" id="rejectPayrollId">
                <input type="hidden" id="rejectBulk" value="false">
                <div class="form-group">
                    <label class="font-weight-bold">Rejection Reason <span class="text-danger">*</span></label>
                    <textarea class="form-control" id="rejectionReason" rows="3" placeholder="Enter reason for rejection..." required></textarea>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-danger" id="confirmRejectBtn">
                    <i class="fas fa-times mr-1"></i> Confirm Rejection
                </button>
            </div>
        </div>
    </div>
</div>

@endsection

@section('scripts')
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script>
// Store all employees data for filtering
const allEmployees = @json($employeesForJs);

$(document).ready(function() {
    // Initialize Select2 for multi-select employee dropdowns
    $('#generate_employee').select2({
        theme: 'bootstrap-5',
        placeholder: 'Select employee(s) or leave empty for all',
        allowClear: true,
        width: '100%'
    });

    $('#filter_employee').select2({
        theme: 'bootstrap-5',
        placeholder: 'Select employee(s) or leave empty for all',
        allowClear: true,
        width: '100%'
    });

    // Function to filter employees by department
    function filterEmployeesByDepartment(departmentSelect, employeeSelect) {
        const selectedDept = $(departmentSelect).val();
        const $empSelect = $(employeeSelect);

        // Clear current selection
        $empSelect.val(null).trigger('change');

        // Remove all options
        $empSelect.empty();

        // Filter and add options
        allEmployees.forEach(function(emp) {
            if (!selectedDept || emp.department === selectedDept) {
                const option = new Option(emp.employee_id + ' - ' + emp.name, emp.id, false, false);
                $(option).attr('data-department', emp.department);
                $empSelect.append(option);
            }
        });

        // Refresh Select2
        $empSelect.trigger('change');
    }

    // Department change handler for Generate Payroll section
    $('#generate_department').on('change', function() {
        filterEmployeesByDepartment(this, '#generate_employee');
    });

    // Department change handler for Filter section
    $('#filter_department').on('change', function() {
        filterEmployeesByDepartment(this, '#filter_employee');
    });

    // DataTable initialization
    $('#salaryTable').DataTable({
        dom: 'Bfrtip',
        buttons: [
            { extend: 'copy', className: 'btn btn-secondary btn-sm' },
            { extend: 'csv', className: 'btn btn-secondary btn-sm' },
            { extend: 'excel', className: 'btn btn-secondary btn-sm' },
            { extend: 'pdf', className: 'btn btn-secondary btn-sm' },
            { extend: 'print', className: 'btn btn-secondary btn-sm' },
            { extend: 'colvis', className: 'btn btn-secondary btn-sm' }
        ],
        pageLength: 10,
        scrollX: true,
        responsive: false,
        language: {
            emptyTable: "No salary details found"
        }
    });

    // Add Salary Button
    $('#addSalaryBtn').on('click', function() {
        resetForm();
        $('#salaryModalLabel').html('<i class="fas fa-plus-circle mr-2"></i> Add Salary Details');
        $('#salaryModal').modal('show');
    });

    // Reset form function
    function resetForm() {
        $('#salaryForm')[0].reset();
        $('#salaryIdHidden').val('');
        $('#formError').hide();
        $('#employee_name').val('');
        // Set default payment mode to Bank Transfer for new entries
        $('#payment_mode').val('Bank');
    }

    // Employee selection - auto-fill name
    $('#employee_id').on('change', function() {
        const selectedOption = $(this).find('option:selected');
        const employeeName = selectedOption.data('name') || '';
        $('#employee_name').val(employeeName);
    });

    // Edit Salary
    $(document).on('click', '.edit-btn', function() {
        const id = $(this).data('id');
        resetForm();

        $.ajax({
            url: '{{ url("/superadmin/salary-details") }}/' + id,
            type: 'GET',
            success: function(salary) {
                $('#salaryIdHidden').val(id);
                $('#month_year').val(salary.month_year);
                $('#employee_id').val(salary.employee_id);
                $('#employee_name').val(salary.employee_name);
                $('#basic_da').val(salary.basic_da);
                $('#hra').val(salary.hra);
                $('#conveyance').val(salary.conveyance);
                $('#washing_allowance').val(salary.washing_allowance);
                $('#fixed_salary').val(salary.fixed_salary);
                $('#no_of_days_worked').val(parseInt(salary.no_of_days_worked));
                $('#leave_given').val(parseInt(salary.leave_given));
                $('#total_days_for_salary').val(parseInt(salary.total_days_for_salary));
                $('#drawn_salary').val(salary.drawn_salary);
                $('#incentive_hrs').val(salary.incentive_hrs);
                $('#incentive_rate').val(salary.incentive_rate);
                $('#incentive_amount').val(salary.incentive_amount);
                $('#attendance_bonus').val(salary.attendance_bonus);
                $('#gross_salary').val(salary.gross_salary);
                $('#esi').val(salary.esi);
                $('#pf').val(salary.pf);
                $('#pt').val(salary.pt);
                $('#advance_deduction').val(salary.advance_deduction);
                $('#net_salary').val(salary.net_salary);
                $('#payment_mode').val(salary.payment_mode);

                $('#salaryModalLabel').html('<i class="fas fa-edit mr-2"></i> Edit Salary Details');
                $('#salaryModal').modal('show');
            },
            error: function() {
                Swal.fire('Error!', 'Failed to fetch salary data.', 'error');
            }
        });
    });

    // Save Salary (Add/Edit)
    $('#salaryForm').on('submit', function(e) {
        e.preventDefault();

        const id = $('#salaryIdHidden').val();
        const formData = $(this).serialize();

        let url, method;
        if (id) {
            url = '{{ url("/superadmin/salary-details") }}/' + id;
            method = 'PUT';
        } else {
            url = '{{ url("/superadmin/salary-details/store") }}';
            method = 'POST';
        }

        $.ajax({
            url: url,
            type: method,
            data: formData,
            headers: {
                'X-CSRF-TOKEN': '{{ csrf_token() }}'
            },
            success: function(response) {
                $('#salaryModal').modal('hide');
                Swal.fire({
                    icon: 'success',
                    title: 'Success!',
                    text: id ? 'Salary details updated successfully!' : 'Salary details added successfully!',
                    timer: 1500,
                    showConfirmButton: false
                }).then(() => {
                    location.reload();
                });
            },
            error: function(xhr) {
                if (xhr.status === 422) {
                    const errors = xhr.responseJSON.errors;
                    if (errors) {
                        const firstError = Object.values(errors)[0][0];
                        $('#formError').text(firstError).show();
                    } else {
                        $('#formError').text('Validation failed. Please check all fields.').show();
                    }
                } else {
                    $('#formError').text('Server error. Please try again.').show();
                }
            }
        });
    });

    // Delete Salary
    $(document).on('click', '.delete-btn', function() {
        const id = $(this).data('id');

        Swal.fire({
            title: 'Delete Salary Record?',
            text: "Are you sure you want to delete this salary record?",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#d33',
            cancelButtonColor: '#3085d6',
            confirmButtonText: 'Yes, Delete!',
            reverseButtons: true
        }).then((result) => {
            if (result.isConfirmed) {
                $.ajax({
                    url: '{{ url("/superadmin/salary-details") }}/' + id,
                    type: 'DELETE',
                    headers: {
                        'X-CSRF-TOKEN': '{{ csrf_token() }}'
                    },
                    success: function(response) {
                        $('#row-' + id).remove();
                        Swal.fire('Deleted!', 'Salary record deleted successfully.', 'success');
                    },
                    error: function() {
                        Swal.fire('Error!', 'Failed to delete salary record.', 'error');
                    }
                });
            }
        });
    });

    // Reset modal on close
    $('#salaryModal').on('hidden.bs.modal', function() {
        resetForm();
    });

    // Auto-calculate fields
    function calculateTotals() {
        const daysWorked = parseFloat($('#no_of_days_worked').val()) || 0;
        const leaveGiven = parseFloat($('#leave_given').val()) || 0;
        // Total Days should ideally be Days in Month, but let's stick to what we have or just use Worked + Leave if that's the logic.
        // User implied: Total Days = Days Worked + Leave Given (if paid).
        // Actually, normally Total Days for Salary = Days in Month. 
        // Let's assume Total Days for Salary needs to be set. 
        // If we fetched stats, we might want to default Total Days to current month's days count.
        
        const totalDays = parseFloat($('#total_days_for_salary').val()) || 0;
        
        // Fixed Salary
        const basic = parseFloat($('#basic_da').val()) || 0;
        const hra = parseFloat($('#hra').val()) || 0;
        const conv = parseFloat($('#conveyance').val()) || 0;
        const wash = parseFloat($('#washing_allowance').val()) || 0;
        const fixedSalary = (basic + hra + conv + wash).toFixed(2);
        $('#fixed_salary').val(fixedSalary);

        // Drawn Salary Calculation
        // Logic: (Fixed Salary / Days in Month) * (Days Worked + Paid Leave)
        // OR just (Fixed Salary / Total Days for Salary) * (Days Worked + Leave Given)
        let drawnSalary = 0;
        if (totalDays > 0) {
           const payableDays = daysWorked + leaveGiven; // Assuming leave_given is paid leave
           drawnSalary = (fixedSalary / totalDays * payableDays).toFixed(2);
        }
        $('#drawn_salary').val(drawnSalary);

        // Incentive
        const incentiveHrs = parseFloat($('#incentive_hrs').val()) || 0;
        const incentiveRate = parseFloat($('#incentive_rate').val()) || 0;
        const incentiveAmt = (incentiveHrs * incentiveRate).toFixed(2);
        $('#incentive_amount').val(incentiveAmt);

        // Gross
        const attendanceBonus = parseFloat($('#attendance_bonus').val()) || 0;
        const gross = (parseFloat(drawnSalary) + parseFloat(incentiveAmt) + attendanceBonus).toFixed(2);
        $('#gross_salary').val(gross);

        // Deductions & Net
        const esi = parseFloat($('#esi').val()) || 0;
        const pf = parseFloat($('#pf').val()) || 0;
        const pt = parseFloat($('#pt').val()) || 0;
        const advance = parseFloat($('#advance_deduction').val()) || 0;
        
        const net = (gross - esi - pf - pt - advance).toFixed(2);
        $('#net_salary').val(net);
    }

    $('#no_of_days_worked, #leave_given, #incentive_hrs, #incentive_rate, #attendance_bonus, #esi, #pf, #pt, #advance_deduction, #total_days_for_salary').on('input', calculateTotals);

    // Fetch Structure & Stats
    function fetchSalaryData() {
        const empId = $('#employee_id').val();
        const monthYear = $('#month_year').val();

        if (empId) {
            // 1. Fetch Master Structure
            $.ajax({
                url: '{{ url("/superadmin/salary-structure/get") }}/' + empId,
                type: 'GET',
                success: function(res) {
                    if(res.success) {
                        const s = res.data;
                        $('#basic_da').val(s.basic_da);
                        $('#hra').val(s.hra);
                        $('#conveyance').val(s.conveyance);
                        $('#washing_allowance').val(s.washing_allowance);
                        $('#fixed_salary').val(s.fixed_salary);
                        // Calculate totals immediately to update drawn salary if month is selected
                        calculateTotals();
                    }
                }
            });
        }

        if (empId && monthYear) {
            // 2. Fetch Monthly Stats
            $.ajax({
                url: '{{ url("/superadmin/employee/monthly-stats") }}/' + empId + '/' + monthYear,
                type: 'GET',
                success: function(res) {
                    $('#no_of_days_worked').val(res.days_worked);
                    $('#leave_given').val(res.leave_given); 
                    
                    // Auto-set Days in Month
                    const [year, month] = monthYear.split('-');
                    const daysInMonth = new Date(year, month, 0).getDate();
                    $('#total_days_for_salary').val(daysInMonth);

                    calculateTotals();
                }
            });
        }
    }

    $('#employee_id, #month_year').on('change', fetchSalaryData);

    // ============ GENERATE PAYROLL FUNCTIONALITY ============
    $('#generatePayrollForm').on('submit', function(e) {
        e.preventDefault();

        const btn = $('#generateBtn');
        const originalText = btn.html();

        Swal.fire({
            title: 'Generate Payroll?',
            text: 'This will calculate and generate payroll for the selected month. Existing records will be updated.',
            icon: 'question',
            showCancelButton: true,
            confirmButtonColor: '#28a745',
            cancelButtonColor: '#6c757d',
            confirmButtonText: 'Yes, Generate!',
            reverseButtons: true
        }).then((result) => {
            if (result.isConfirmed) {
                btn.html('<i class="fas fa-spinner fa-spin mr-1"></i> Generating...').prop('disabled', true);

                $.ajax({
                    url: '{{ route("superadmin.payroll.generate") }}',
                    type: 'POST',
                    data: $(this).serialize(),
                    headers: {
                        'X-CSRF-TOKEN': '{{ csrf_token() }}'
                    },
                    success: function(response) {
                        btn.html(originalText).prop('disabled', false);

                        let message = response.message;
                        if (response.errors && response.errors.length > 0) {
                            message += '<br><br><small class="text-muted">Skipped: ' + response.errors.slice(0, 5).join('<br>') + '</small>';
                            if (response.errors.length > 5) {
                                message += '<br><small class="text-muted">... and ' + (response.errors.length - 5) + ' more</small>';
                            }
                        }

                        Swal.fire({
                            icon: 'success',
                            title: 'Payroll Generated!',
                            html: message,
                            confirmButtonColor: '#28a745'
                        }).then(() => {
                            location.reload();
                        });
                    },
                    error: function(xhr) {
                        btn.html(originalText).prop('disabled', false);
                        let errorMsg = 'Failed to generate payroll.';
                        if (xhr.responseJSON && xhr.responseJSON.message) {
                            errorMsg = xhr.responseJSON.message;
                        }
                        Swal.fire('Error!', errorMsg, 'error');
                    }
                });
            }
        });
    });

    // ============ FILTER FUNCTIONALITY ============
    // DataTable is already initialized above, get reference
    let salaryDataTable = $('#salaryTable').DataTable();

    $('#filterForm').on('submit', function(e) {
        e.preventDefault();

        const monthYear = $('#filter_month').val();
        const department = $('#filter_department').val();
        const employeeIds = $('#filter_employee').val(); // Array of IDs

        // Build filter URL with array support
        let url = '{{ route("superadmin.payroll.data") }}?';
        if (monthYear) url += 'month_year=' + monthYear + '&';
        if (department) url += 'department=' + encodeURIComponent(department) + '&';
        if (employeeIds && employeeIds.length > 0) {
            employeeIds.forEach(function(id) {
                url += 'employee_id[]=' + id + '&';
            });
        }

        $.ajax({
            url: url,
            type: 'GET',
            success: function(response) {
                if (response.success) {
                    // Clear and redraw table
                    salaryDataTable.clear();

                    response.data.forEach(function(salary) {
                        const empName = salary.employee ? salary.employee.name : '-';
                        const empId = salary.employee ? salary.employee.employee_id : '-';

                        salaryDataTable.row.add([
                            '<input type="checkbox" class="salary-checkbox" value="' + salary.id + '" data-employee="' + empName + '" data-month="' + salary.month_year + '">',
                            salary.month_year,
                            empId,
                            empName,
                            parseFloat(salary.basic_da || 0).toFixed(2),
                            parseFloat(salary.hra || 0).toFixed(2),
                            parseFloat(salary.conveyance || 0).toFixed(2),
                            parseFloat(salary.washing_allowance || 0).toFixed(2),
                            parseFloat(salary.fixed_salary || 0).toFixed(2),
                            salary.no_of_days_worked || 0,
                            salary.leave_given || 0,
                            salary.total_days_for_salary || 0,
                            parseFloat(salary.drawn_salary || 0).toFixed(2),
                            salary.incentive_hrs || 0,
                            parseFloat(salary.incentive_rate || 0).toFixed(2),
                            parseFloat(salary.incentive_amount || 0).toFixed(2),
                            parseFloat(salary.attendance_bonus || 0).toFixed(2),
                            '<strong>' + parseFloat(salary.gross_salary || 0).toFixed(2) + '</strong>',
                            parseFloat(salary.esi || 0).toFixed(2),
                            parseFloat(salary.pf || 0).toFixed(2),
                            parseFloat(salary.pt || 0).toFixed(2),
                            parseFloat(salary.advance_deduction || 0).toFixed(2),
                            '<strong class="text-success">' + parseFloat(salary.net_salary || 0).toFixed(2) + '</strong>',
                            salary.payment_mode ? '<span class="badge badge-info">' + salary.payment_mode + '</span>' : '-',
                            '<div class="text-center" style="white-space: nowrap;">' +
                                '<a href="/superadmin/salary-details/' + salary.id + '/payslip" class="btn btn-info btn-sm" title="Download Payslip" target="_blank"><i class="fa fa-file-pdf"></i></a> ' +
                                '<button class="btn btn-warning btn-sm edit-btn" data-id="' + salary.id + '" title="Edit"><i class="fa fa-edit"></i></button> ' +
                                '<button class="btn btn-danger btn-sm delete-btn" data-id="' + salary.id + '" title="Delete"><i class="fa fa-trash"></i></button>' +
                            '</div>'
                        ]);
                    });

                    salaryDataTable.draw();

                    // Reset selection state after filter
                    $('#checkAll').prop('checked', false);
                    $('#checkAll').prop('indeterminate', false);
                    updateSelectionCount();

                    Swal.fire({
                        icon: 'success',
                        title: 'Filter Applied',
                        text: 'Found ' + response.data.length + ' record(s)',
                        timer: 1500,
                        showConfirmButton: false
                    });
                }
            },
            error: function() {
                Swal.fire('Error!', 'Failed to filter data.', 'error');
            }
        });
    });

    // Clear filter
    $('#clearFilterBtn').on('click', function() {
        $('#filterForm')[0].reset();
        // Reset Select2 dropdowns
        $('#filter_employee').val(null).trigger('change');
        $('#filter_department').val('').trigger('change');
        // Repopulate employee dropdown with all employees
        repopulateEmployees('#filter_employee');
        location.reload();
    });

    // Helper function to repopulate employee dropdown
    function repopulateEmployees(selectId) {
        const $select = $(selectId);
        $select.empty();
        allEmployees.forEach(function(emp) {
            const option = new Option(emp.employee_id + ' - ' + emp.name, emp.id, false, false);
            $(option).attr('data-department', emp.department);
            $select.append(option);
        });
        $select.trigger('change');
    }

    // ============ CHECKBOX SELECTION & BULK DOWNLOAD ============
    function updateSelectionCount() {
        const count = $('.salary-checkbox:checked').length;
        $('#selectedCount').text(count);
        $('#selectionInfo').text(count > 0 ? count + ' record(s) selected' : '');

        if (count > 0) {
            $('#downloadSelectedBtn').show();
            $('#bulkApproveBtn').show();
            $('#bulkRejectBtn').show();
        } else {
            $('#downloadSelectedBtn').hide();
            $('#bulkApproveBtn').hide();
            $('#bulkRejectBtn').hide();
        }
    }

    // Individual checkbox change
    $(document).on('change', '.salary-checkbox', function() {
        updateSelectionCount();

        // Update "check all" state
        const total = $('.salary-checkbox').length;
        const checked = $('.salary-checkbox:checked').length;
        $('#checkAll').prop('checked', total === checked);
        $('#checkAll').prop('indeterminate', checked > 0 && checked < total);
    });

    // Check all checkbox in header
    $('#checkAll').on('change', function() {
        $('.salary-checkbox').prop('checked', $(this).is(':checked'));
        updateSelectionCount();
    });

    // Select All button
    $('#selectAllBtn').on('click', function() {
        $('.salary-checkbox').prop('checked', true);
        $('#checkAll').prop('checked', true);
        updateSelectionCount();
    });

    // Deselect All button
    $('#deselectAllBtn').on('click', function() {
        $('.salary-checkbox').prop('checked', false);
        $('#checkAll').prop('checked', false);
        $('#checkAll').prop('indeterminate', false);
        updateSelectionCount();
    });

    // Download Selected Payslips as ZIP
    $('#downloadSelectedBtn').on('click', function() {
        const selectedIds = [];
        $('.salary-checkbox:checked').each(function() {
            selectedIds.push(parseInt($(this).val()));
        });

        if (selectedIds.length === 0) {
            Swal.fire('Warning', 'Please select at least one payslip to download.', 'warning');
            return;
        }

        const btn = $(this);
        const originalText = btn.html();

        Swal.fire({
            title: 'Download Payslips?',
            html: 'You are about to download <strong>' + selectedIds.length + '</strong> payslip(s) as a ZIP file.',
            icon: 'question',
            showCancelButton: true,
            confirmButtonColor: '#f6c23e',
            cancelButtonColor: '#6c757d',
            confirmButtonText: 'Yes, Download!',
            reverseButtons: true
        }).then((result) => {
            if (result.isConfirmed) {
                btn.html('<i class="fas fa-spinner fa-spin mr-1"></i> Preparing ZIP...').prop('disabled', true);

                // Create a form and submit to download
                const form = $('<form>', {
                    'method': 'POST',
                    'action': '{{ route("superadmin.payslip.bulk-download") }}'
                });

                form.append($('<input>', {
                    'type': 'hidden',
                    'name': '_token',
                    'value': '{{ csrf_token() }}'
                }));

                selectedIds.forEach(function(id) {
                    form.append($('<input>', {
                        'type': 'hidden',
                        'name': 'ids[]',
                        'value': id
                    }));
                });

                $('body').append(form);
                form.submit();
                form.remove();

                // Reset button after a delay
                setTimeout(function() {
                    btn.html(originalText).prop('disabled', false);
                }, 2000);
            }
        });
    });

    // Initialize count on page load
    updateSelectionCount();

    // ============ PAYROLL APPROVAL SYSTEM ============

    // Single Approve button click
    $(document).on('click', '.approve-btn', function() {
        const id = $(this).data('id');
        const btn = $(this);

        Swal.fire({
            title: 'Approve Payroll?',
            text: 'Are you sure you want to approve this payroll record?',
            icon: 'question',
            showCancelButton: true,
            confirmButtonColor: '#28a745',
            cancelButtonColor: '#6c757d',
            confirmButtonText: 'Yes, Approve'
        }).then((result) => {
            if (result.isConfirmed) {
                btn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i>');
                $.ajax({
                    url: '{{ url("/superadmin/payroll") }}/' + id + '/approve',
                    type: 'POST',
                    data: { _token: '{{ csrf_token() }}' },
                    success: function(response) {
                        if (response.success) {
                            Swal.fire('Approved!', response.message, 'success').then(() => {
                                location.reload();
                            });
                        } else {
                            Swal.fire('Error!', response.message, 'error');
                            btn.prop('disabled', false).html('<i class="fa fa-check"></i>');
                        }
                    },
                    error: function(xhr) {
                        Swal.fire('Error!', 'Failed to approve payroll.', 'error');
                        btn.prop('disabled', false).html('<i class="fa fa-check"></i>');
                    }
                });
            }
        });
    });

    // Single Reject button click
    $(document).on('click', '.reject-btn', function() {
        const id = $(this).data('id');
        $('#rejectPayrollId').val(id);
        $('#rejectBulk').val('false');
        $('#rejectionReason').val('');
        $('#rejectModal').modal('show');
    });

    // Bulk Approve button click
    $('#bulkApproveBtn').on('click', function() {
        const btn = $(this);

        // Collect numeric IDs from checked checkboxes
        const selectedIds = $('.salary-checkbox:checked')
            .map(function() {
                const val = $(this).val();
                return val && !isNaN(val) ? parseInt(val, 10) : null;
            })
            .get()
            .filter(id => id !== null); // Remove any nulls

        if (selectedIds.length === 0) {
            Swal.fire('Warning', 'Please select at least one valid payroll record.', 'warning');
            return;
        }

        Swal.fire({
            title: 'Bulk Approve?',
            text: `Are you sure you want to approve ${selectedIds.length} payroll record(s)?`,
            icon: 'question',
            showCancelButton: true,
            confirmButtonColor: '#28a745',
            cancelButtonColor: '#6c757d',
            confirmButtonText: 'Yes, Approve All'
        }).then((result) => {
            if (result.isConfirmed) {
                btn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin mr-1"></i> Processing...');

                $.ajax({
                    url: '{{ route("superadmin.payroll.bulk-approve") }}',
                    type: 'POST',
                    contentType: 'application/json', // Important: send as JSON
                    data: JSON.stringify({
                        _token: '{{ csrf_token() }}',
                        ids: selectedIds
                    }),
                    success: function(response) {
                        Swal.fire('Approved!', response.message, 'success').then(() => {
                            location.reload();
                        });
                    },
                    error: function(xhr) {
                        console.log(xhr.responseJSON); // Debug
                        let errorMsg = 'Failed to bulk approve payroll.';
                        if (xhr.responseJSON && xhr.responseJSON.message) {
                            errorMsg = xhr.responseJSON.message;
                        }
                        Swal.fire('Error!', errorMsg, 'error');
                    },
                    complete: function() {
                        btn.prop('disabled', false).html('<i class="fas fa-check mr-1"></i> Approve Selected');
                    }
                });
            }
        });
    });

    // Bulk Reject button click
    $('#bulkRejectBtn').on('click', function() {
        const selectedIds = [];
        $('.salary-checkbox:checked').each(function() {
            selectedIds.push($(this).val());
        });

        if (selectedIds.length === 0) {
            Swal.fire('Warning', 'Please select at least one record.', 'warning');
            return;
        }

        $('#rejectPayrollId').val(selectedIds.join(','));
        $('#rejectBulk').val('true');
        $('#rejectionReason').val('');
        $('#rejectModal').modal('show');
    });

    // Confirm rejection
    $('#confirmRejectBtn').on('click', function() {
        const reason = $('#rejectionReason').val().trim();
        if (!reason) {
            Swal.fire('Error', 'Please enter a rejection reason.', 'error');
            return;
        }

        const isBulk = $('#rejectBulk').val() === 'true';
        const btn = $(this);
        btn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin mr-1"></i> Processing...');

        if (isBulk) {
            // Bulk reject
            const ids = $('#rejectPayrollId').val().split(',').map(id => parseInt(id));
            $.ajax({
                url: '{{ route("superadmin.payroll.bulk-reject") }}',
                type: 'POST',
                data: {
                    _token: '{{ csrf_token() }}',
                    ids: ids,
                    reason: reason
                },
                success: function(response) {
                    $('#rejectModal').modal('hide');
                    if (response.success) {
                        Swal.fire('Rejected!', response.message, 'success').then(() => {
                            location.reload();
                        });
                    } else {
                        Swal.fire('Error!', response.message, 'error');
                    }
                    btn.prop('disabled', false).html('<i class="fas fa-times mr-1"></i> Confirm Rejection');
                },
                error: function(xhr) {
                    $('#rejectModal').modal('hide');
                    Swal.fire('Error!', 'Failed to bulk reject payroll.', 'error');
                    btn.prop('disabled', false).html('<i class="fas fa-times mr-1"></i> Confirm Rejection');
                }
            });
        } else {
            // Single reject
            const id = $('#rejectPayrollId').val();
            $.ajax({
                url: '{{ url("/superadmin/payroll") }}/' + id + '/reject',
                type: 'POST',
                data: {
                    _token: '{{ csrf_token() }}',
                    reason: reason
                },
                success: function(response) {
                    $('#rejectModal').modal('hide');
                    if (response.success) {
                        Swal.fire('Rejected!', response.message, 'success').then(() => {
                            location.reload();
                        });
                    } else {
                        Swal.fire('Error!', response.message, 'error');
                    }
                    btn.prop('disabled', false).html('<i class="fas fa-times mr-1"></i> Confirm Rejection');
                },
                error: function(xhr) {
                    $('#rejectModal').modal('hide');
                    Swal.fire('Error!', 'Failed to reject payroll.', 'error');
                    btn.prop('disabled', false).html('<i class="fas fa-times mr-1"></i> Confirm Rejection');
                }
            });
        }
    });
});
</script>
@endsection
