@extends('layouts.dashboard.managerapp')

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

@section('styles')
    <link rel="stylesheet" href="https://cdn.datatables.net/buttons/2.4.1/css/buttons.bootstrap5.min.css">
    <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;
        }

        /* Popup overlay for form */
        .new-employer-popup-overlay {
            display: none;
            position: fixed;
            z-index: 1055;
            top: 0;
            left: 0;
            width: 100vw;
            height: 100vh;
            background: rgba(40, 40, 40, 0.35);
            justify-content: center;
            align-items: center;
        }

        .new-employer-popup-content {
            background: #fff;
            padding: 2rem;
            border-radius: 18px;
            min-width: 420px;
            max-width: 600px;
            margin: auto;
            box-shadow: 0 5px 30px rgba(0, 0, 0, .1);
        }

        .profile-img {
            object-fit: cover;
        }

        .new-employer-popup-buttons {
            display: flex;
            gap: 1rem;
            justify-content: flex-end;
        }

        .salary-popup-overlay {
            display: none;
            position: fixed;
            z-index: 1055;
            top: 0;
            left: 0;
            width: 100vw;
            height: 100vh;
            background: rgba(40, 40, 40, 0.35);
            justify-content: center;
            align-items: center;
        }

        .salary-popup-content {
            background: #fff;
            padding: 2rem;
            border-radius: 18px;
            min-width: 420px;
            max-width: 900px;
            max-height: 90vh;
            /* NEW: limit popup height */
            overflow-y: auto;
            /* NEW: vertical scroll */
            margin: auto;
            box-shadow: 0 5px 30px rgba(0, 0, 0, .1);
        }

        @media (max-width: 600px) {
            .salary-popup-content {
                min-width: 90vw;
                max-width: 98vw;
                padding: 1rem;
            }

            .row>[class^='col-md-'] {
                flex: 0 0 100%;
                max-width: 100%;
            }
        }
    </style>
@endsection

@section('content')
    <div class="container-fluid bg-white">
        <div class="p-2 d-sm-flex align-items-center justify-content-between mb-4">
            <h1 class="h5 mb-0 text-gray-800">
                <i class="fas fa-rupee-sign me-2"></i>
                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>

        <div class="card">
            <div class="card-header">
                <a href="#" class="btn btn-primary btn-sm" id="openSalaryPopup" style="float: right">
                    <i class="fas fa-plus"></i> Add Salary Details
                </a>
            </div>
            <div class="card-header d-flex justify-content-between align-items-center">
                <span><i class="fas fa-table me-2"></i> Salary Details List</span>
            </div>
            <div class="card-body">
                @if (session('success'))
                    <div class="alert alert-success">{{ session('success') }}</div>
                @endif
                <div class="table-responsive">
                    <table class="table table-striped table-hover table-bordered" id="salaryTable" width="100%"
                        style="display: inline-table;">
                        <thead>
                            <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 Allowance</th>
                                <th>Fixed Salary</th>
                                <th>No. of Days Worked</th>
                                <th>Leave Given</th>
                                <th>Total Days for Salary</th>
                                <th>Drawn Salary</th>
                                <th>Incentive Hrs</th>
                                <th>Incentive Rate</th>
                                <th>Incentive Amount</th>
                                <th>Attendance Bonus</th>
                                <th>Gross Salary</th>
                                <th>ESI</th>
                                <th>PF</th>
                                <th>PT</th>
                                <th>Advance Deduction</th>
                                <th>Net Salary</th>
                                <th>Payment Mode</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            @foreach ($salaryDetails as $salary)
                                <tr>
                                    <td>{{ $salary->month_year }}</td>
                                    <td>{{ $salary->employee->employee_id ?? '' }}</td>
                                    <td>{{ $salary->employee->name ?? '' }}</td>
                                    <td>{{ $salary->basic_da }}</td>
                                    <td>{{ $salary->hra }}</td>
                                    <td>{{ $salary->conveyance }}</td>
                                    <td>{{ $salary->washing_allowance }}</td>
                                    <td>{{ $salary->fixed_salary }}</td>
                                    <td>{{ $salary->no_of_days_worked }}</td>
                                    <td>{{ $salary->leave_given }}</td>
                                    <td>{{ $salary->total_days_for_salary }}</td>
                                    <td>{{ $salary->drawn_salary }}</td>
                                    <td>{{ $salary->incentive_hrs }}</td>
                                    <td>{{ $salary->incentive_rate }}</td>
                                    <td>{{ $salary->incentive_amount }}</td>
                                    <td>{{ $salary->attendance_bonus }}</td>
                                    <td>{{ $salary->gross_salary }}</td>
                                    <td>{{ $salary->esi }}</td>
                                    <td>{{ $salary->pf }}</td>
                                    <td>{{ $salary->pt }}</td>
                                    <td>{{ $salary->advance_deduction }}</td>
                                    <td>{{ $salary->net_salary }}</td>
                                    <td>{{ $salary->payment_mode }}</td>
                                    <td>
                                        <a href="javascript:void(0);" class="btn btn-warning btn-sm me-1"
                                            onclick="editSalaryDetail({{ $salary->id }})">Edit</a>
                                        <form action="{{ url('/manager/salary-details/' . $salary->id) }}" method="POST"
                                            style="display:inline;" class="delete-salary-form">
                                            @csrf
                                            @method('DELETE')
                                            <button type="submit" class="btn btn-danger btn-sm"
                                                onclick="return confirm('Delete this salary record?')">Delete</button>
                                        </form>
                                    </td>
                                </tr>
                            @endforeach
                        </tbody>
                    </table>
                </div>

            </div>
        </div>
    </div>

    <!-- Salary Details Popup -->
    <div class="salary-popup-overlay" id="salary-popup-overlay">
        <form class="salary-popup-content" id="salaryForm" method="POST" action="{{ url('/manager/salary-details/store') }}">
            @csrf
            <h5>Employee Salary Details</h5>
            <br>
            <div class="row">
                <div class="col-md-4">
                    <label for="month_year">Month & Year <span class="required">*</span></label>
                    <input type="month" id="month_year" name="month_year" required>
                </div>
                <div class="col-md-4">
                    <label for="employee_id">Employee ID <span class="required">*</span></label>
                    <select id="employee_id" name="employee_id" required>
                        <option value="">Select Employee ID</option>
                        @foreach ($employees as $employee)
                            <option value="{{ $employee->id }}">{{ $employee->employee_id }}</option>
                        @endforeach
                    </select>
                </div>
                <div class="col-md-4">
                    <label for="employee_name">Employee Name</label>
                    <input type="text" id="employee_name" name="employee_name" readonly>
                </div>
            </div>
            <br>
            <div class="row">
                <div class="col-md-4">
                    <label for="basic_da">Basic & DA</label>
                    <input type="number" step="0.01" name="basic_da" id="basic_da">
                </div>
                <div class="col-md-4">
                    <label for="hra">HRA</label>
                    <input type="number" step="0.01" name="hra" id="hra">
                </div>
                <div class="col-md-4">
                    <label for="conveyance">Conveyance</label>
                    <input type="number" step="0.01" name="conveyance" id="conveyance">
                </div>
            </div>
            <br>
            <div class="row">
                <div class="col-md-4">
                    <label for="washing_allowance">Washing Allowance</label>
                    <input type="number" step="0.01" name="washing_allowance" id="washing_allowance">
                </div>
                <div class="col-md-4">
                    <label for="fixed_salary">Fixed Salary</label>
                    <input type="number" step="0.01" name="fixed_salary" id="fixed_salary">
                </div>
                <div class="col-md-4">
                    <label for="no_of_days_worked">No. of Days Worked</label>
                    <input type="number" name="no_of_days_worked" id="no_of_days_worked">
                </div>
            </div>
            <br>
            <div class="row">
                <div class="col-md-4">
                    <label for="leave_given">Leave Given</label>
                    <input type="number" name="leave_given" id="leave_given">
                </div>
                <div class="col-md-4">
                    <label for="total_days_for_salary">Total Days for Salary</label>
                    <input type="number" name="total_days_for_salary" id="total_days_for_salary">
                </div>
                <div class="col-md-4">
                    <label for="drawn_salary">Drawn Salary</label>
                    <input type="number" step="0.01" name="drawn_salary" id="drawn_salary">
                </div>
            </div>
            <br>
            <div class="row">
                <div class="col-md-4">
                    <label for="incentive_hrs">Incentive Hrs</label>
                    <input type="number" step="0.01" name="incentive_hrs" id="incentive_hrs">
                </div>
                <div class="col-md-4">
                    <label for="incentive_rate">Incentive Rate</label>
                    <input type="number" step="0.01" name="incentive_rate" id="incentive_rate">
                </div>
                <div class="col-md-4">
                    <label for="incentive_amount">Incentive Amount</label>
                    <input type="number" step="0.01" name="incentive_amount" id="incentive_amount">
                </div>
            </div>
            <br>
            <div class="row">
                <div class="col-md-4">
                    <label for="attendance_bonus">Attendance Bonus</label>
                    <input type="number" step="0.01" name="attendance_bonus" id="attendance_bonus">
                </div>
                <div class="col-md-4">
                    <label for="gross_salary">Gross Salary</label>
                    <input type="number" step="0.01" name="gross_salary" id="gross_salary">
                </div>
                <div class="col-md-4">
                    <label for="esi">ESI</label>
                    <input type="number" step="0.01" name="esi" id="esi">
                </div>
            </div>
            <br>
            <div class="row">
                <div class="col-md-4">
                    <label for="pf">PF</label>
                    <input type="number" step="0.01" name="pf" id="pf">
                </div>
                <div class="col-md-4">
                    <label for="pt">PT</label>
                    <input type="number" step="0.01" name="pt" id="pt">
                </div>
                <div class="col-md-4">
                    <label for="advance_deduction">Advance Deduction</label>
                    <input type="number" step="0.01" name="advance_deduction" id="advance_deduction">
                </div>
            </div>
            <br>
            <div class="row">
                <div class="col-md-4">
                    <label for="net_salary">Net Salary</label>
                    <input type="number" step="0.01" name="net_salary" id="net_salary">
                </div>
                <div class="col-md-4">
                    <label for="payment_mode">Payment Mode</label>
                    <select name="payment_mode" id="payment_mode">
                        <option value="">Select</option>
                        <option value="Cash">Cash</option>
                        <option value="Bank">Bank</option>
                        <option value="Cheque">Cheque</option>
                        <option value="Other">Other</option>
                    </select>
                </div>
            </div>
            <br>
            <div class="d-flex justify-content-end gap-2">
                <button class="btn btn-success" type="submit">Save</button>
                <button class="btn btn-danger" type="button" id="closeSalaryPopup">Close</button>
            </div>
        </form>
    </div>

@endsection

@section('scripts')
    <script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.bootstrap5.min.js"></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,
                responsive: true,
                language: {
                    "emptyTable": "No salary details found"
                }
            });

            // Popup logic
            $('#openSalaryPopup').on('click', function(event) {
                event.preventDefault();
                $('#salary-popup-overlay').css('display', 'flex');
                $('#salaryForm').trigger('reset');
                $('#salaryForm').attr('action', '{{ url('/manager/salary-details/store') }}');
                $('#salaryForm input[name="_method"]').remove();
            });

            $('#closeSalaryPopup').on('click', function() {
                $('#salary-popup-overlay').hide();
            });

            // Employee Name autofill
            $('#employee_id').on('change', function() {
                var empId = $(this).val();
                if (empId) {
                    $.ajax({
                        url: '{{ url('manager/employee') }}/' + empId + '/name',
                        method: 'GET',
                        success: function(res) {
                            $('#employee_name').val(res.name);
                        }
                    });
                } else {
                    $('#employee_name').val('');
                }
            });
        });
        // Edit Salary Detail (AJAX)
        function editSalaryDetail(salaryId) {
            const baseUrl = @json(url('/'));
            const popupOverlay = document.getElementById('salary-popup-overlay');
            popupOverlay.style.display = 'flex';
            $('#salaryForm').trigger('reset');
            // Set action URL for update
            $('#salaryForm').attr('action', `${baseUrl}/manager/salary-details/${salaryId}`);
            // If method hidden input doesn't exist, add it
            if ($('#salaryForm input[name="_method"]').length === 0) {
                $('#salaryForm').append('<input type="hidden" name="_method" value="PUT">');
            } else {
                $('#salaryForm input[name="_method"]').val('PUT');
            }

            $.ajax({
                url: `${baseUrl}/manager/salary-details/${salaryId}`,
                type: 'GET',
                success: function(salary) {
                    $('#month_year').val(salary.month_year);
                    $('#employee_id').val(salary.employee_id).change();
                    $('#employee_name').val(salary
                        .employee_name); // This can be fetched via AJAX on select change
                    $('#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);
                },
                error: function() {
                    alert('Failed to fetch salary data.');
                }
            });
        }
    </script>
@endsection
