@extends('layouts.dashboard.superadminapp')

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

@section('styles')
<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;
    }
</style>
@endsection

@section('content')

<!-- Page Heading -->
<div class="bg-white p-2 d-sm-flex align-items-center justify-content-between mb-4">
    <h1 class="h5 mb-0 text-gray-800">UEPL | Employee Salary Details</h1>
    <div class="display-date">
        <span id="day">day</span>,
        <span id="daynum">00</span>
        <span id="month">month</span>
        <span id="year">0000</span>
    </div>
    <div class="display-time"></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>
        <button class="btn btn-light btn-sm" id="addSalaryBtn">
            <i class="fas fa-plus mr-1"></i> Add Salary Details
        </button>
    </div>
    <div class="card-body">
        <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>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 width="100" class="text-center">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    @foreach($salaryDetails as $salary)
                        <tr id="row-{{ $salary->id }}">
                            <td>{{ $salary->month_year }}</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>{{ $salary->no_of_days_worked }}</td>
                            <td>{{ $salary->leave_given }}</td>
                            <td>{{ $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>
                                <div class="text-center" style="white-space: nowrap;">
                                    <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">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>

@endsection

@section('scripts')
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
$(document).ready(function() {
    // 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('');
    }

    // 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(salary.no_of_days_worked);
                $('#leave_given').val(salary.leave_given);
                $('#total_days_for_salary').val(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 = '{{ route("superadmin.salary.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 (optional enhancement)
    function calculateTotals() {
        const daysWorked = parseFloat($('#no_of_days_worked').val()) || 0;
        const leaveGiven = parseFloat($('#leave_given').val()) || 0;
        $('#total_days_for_salary').val(daysWorked + leaveGiven);

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

    // 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);
</script>
@endsection
