@extends('layouts.dashboard.adminapp')

@section('title', 'Salary Structure Master')

@section('styles')
<style>
    .card-header-gradient {
        background: linear-gradient(135deg, #4e73df 0%, #224abe 100%);
        color: white;
    }
</style>
@endsection

@section('content')

<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 | Salary Structure Master</h1>
    <button class="btn btn-success btn-sm" data-toggle="modal" data-target="#bulkUploadModal">
        <i class="fas fa-file-upload mr-1"></i> Bulk Upload
    </button>
</div>

<!-- Success/Error 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

<div class="row">
    <!-- Form Section -->
    <div class="col-lg-5">
        <div class="card shadow mb-4">
            <div class="card-header card-header-gradient py-3">
                <h6 class="m-0 font-weight-bold">
                    <i class="fas fa-edit mr-2"></i> Define Salary Structure
                </h6>
            </div>
            <div class="card-body">
                <form id="salaryStructureForm">
                    @csrf
                    <div class="form-group">
                        <label class="small font-weight-bold">Select Employee <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 $emp)
                                <option value="{{ $emp->id }}">{{ $emp->employee_id }} - {{ $emp->name }}</option>
                            @endforeach
                        </select>
                    </div>

                    <div class="row">
                        <div class="col-md-6 form-group">
                            <label class="small font-weight-bold">Basic & DA</label>
                            <input type="number" step="0.01" class="form-control" name="basic_da" id="basic_da">
                        </div>
                        <div class="col-md-6 form-group">
                            <label class="small font-weight-bold">HRA</label>
                            <input type="number" step="0.01" class="form-control" name="hra" id="hra">
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-6 form-group">
                            <label class="small font-weight-bold">Conveyance</label>
                            <input type="number" step="0.01" class="form-control" name="conveyance" id="conveyance">
                        </div>
                        <div class="col-md-6 form-group">
                            <label class="small font-weight-bold">Washing Allow.</label>
                            <input type="number" step="0.01" class="form-control" name="washing_allowance" id="washing_allowance">
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="small font-weight-bold">Incentive per Hour</label>
                        <input type="number" step="0.01" class="form-control" name="incentive_per_hour" id="incentive_per_hour" placeholder="e.g. 50.00">
                    </div>

                    <div class="form-group">
                        <label class="small font-weight-bold">Fixed Salary (Total)</label>
                        <input type="number" step="0.01" class="form-control bg-light" name="fixed_salary" id="fixed_salary">
                        <small class="text-muted">Auto-calculated sum of components</small>
                    </div>

                    <hr>
                    <h6 class="small font-weight-bold text-primary">Statutory Rates (Optional Overrides)</h6>
                    <div class="row">
                        <div class="col-md-4 form-group">
                            <label class="small font-weight-bold">PF %</label>
                            <input type="number" step="0.01" class="form-control" name="pf_percentage" id="pf_percentage" placeholder="Default: 12%">
                        </div>
                        <div class="col-md-4 form-group">
                            <label class="small font-weight-bold">ESI %</label>
                            <input type="number" step="0.01" class="form-control" name="esi_percentage" id="esi_percentage" placeholder="Default: 0.75%">
                        </div>
                        <div class="col-md-4 form-group">
                            <label class="small font-weight-bold">PT %</label>
                            <input type="number" step="0.01" class="form-control" name="pt_percentage" id="pt_percentage" placeholder="Professional Tax %">
                        </div>
                    </div>

                    <button type="submit" class="btn btn-primary btn-block">
                        <i class="fas fa-save mr-1"></i> Save Structure
                    </button>
                </form>
            </div>
        </div>
    </div>

    <!-- List Section -->
    <div class="col-lg-7">
        <div class="card shadow mb-4">
            <div class="card-header py-3">
                <h6 class="m-0 font-weight-bold text-primary">Existing Structures</h6>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-bordered table-sm" id="structureTable" width="100%" cellspacing="0">
                        <thead class="thead-light">
                            <tr>
                                <th>Employee</th>
                                <th>Basic</th>
                                <th>HRA</th>
                                <th>Conv.</th>
                                <th>Incentive/Hr</th>
                                <th>Total</th>
                                <th>PT %</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            @foreach($structures as $st)
                                <tr>
                                    <td>
                                        <div class="font-weight-bold">{{ $st->employee->name ?? 'N/A' }}</div>
                                        <small class="text-muted">{{ $st->employee->employee_id ?? '-' }}</small>
                                    </td>
                                    <td>{{ $st->basic_da }}</td>
                                    <td>{{ $st->hra }}</td>
                                    <td>{{ $st->conveyance }}</td>
                                    <td>{{ $st->incentive_per_hour ?? '-' }}</td>
                                    <td class="font-weight-bold text-success">{{ $st->fixed_salary }}</td>
                                    <td>{{ $st->pt_percentage ?? '-' }}%</td>
                                    <td>
                                        <button class="btn btn-sm btn-info edit-btn"
                                            data-id="{{ $st->employee_id }}"
                                            data-basic="{{ $st->basic_da }}"
                                            data-hra="{{ $st->hra }}"
                                            data-conv="{{ $st->conveyance }}"
                                            data-wash="{{ $st->washing_allowance }}"
                                            data-incentive="{{ $st->incentive_per_hour }}"
                                            data-fixed="{{ $st->fixed_salary }}"
                                            data-pf="{{ $st->pf_percentage }}"
                                            data-esi="{{ $st->esi_percentage }}"
                                            data-pt="{{ $st->pt_percentage }}"
                                        >
                                            Edit
                                        </button>
                                    </td>
                                </tr>
                            @endforeach
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Bulk Upload Modal -->
<div class="modal fade" id="bulkUploadModal" tabindex="-1" role="dialog" aria-labelledby="bulkUploadModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header bg-success text-white">
                <h5 class="modal-title" id="bulkUploadModalLabel">
                    <i class="fas fa-file-upload mr-2"></i> Bulk Upload Salary Structure
                </h5>
                <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <form action="{{ route('admin.salary-structure.import') }}" method="POST" enctype="multipart/form-data">
                @csrf
                <div class="modal-body">
                    <div class="alert alert-info">
                        <i class="fas fa-info-circle mr-2"></i>
                        <strong>Instructions:</strong>
                        <ul class="mb-0 mt-2">
                            <li>Download the sample Excel file and fill in the salary structure data</li>
                            <li>Employee ID must match existing employee IDs in the system</li>
                            <li>All amount fields should be numeric values</li>
                            <li>Percentage fields should be between 0 and 100</li>
                            <li>Existing salary structures will be updated if employee ID already exists</li>
                        </ul>
                    </div>

                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label class="font-weight-bold">
                                    <i class="fas fa-file-excel text-success mr-1"></i> Upload Excel File
                                </label>
                                <input type="file" class="form-control-file" name="import_file" accept=".xlsx,.xls" required>
                                <small class="text-muted">Accepted formats: .xlsx, .xls</small>
                            </div>
                        </div>
                    </div>

                    <div class="table-responsive mt-3">
                        <p class="font-weight-bold text-muted small">Expected Columns:</p>
                        <table class="table table-sm table-bordered">
                            <thead class="thead-light">
                                <tr>
                                    <th>Column</th>
                                    <th>Description</th>
                                    <th>Required</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr><td>Employee ID</td><td>Employee's unique ID (e.g., 1001)</td><td><span class="badge badge-danger">Yes</span></td></tr>
                                <tr><td>Basic & DA</td><td>Basic salary + DA amount</td><td><span class="badge badge-secondary">No</span></td></tr>
                                <tr><td>HRA</td><td>House Rent Allowance</td><td><span class="badge badge-secondary">No</span></td></tr>
                                <tr><td>Conveyance</td><td>Conveyance Allowance</td><td><span class="badge badge-secondary">No</span></td></tr>
                                <tr><td>Washing Allowance</td><td>Washing Allowance</td><td><span class="badge badge-secondary">No</span></td></tr>
                                <tr><td>Incentive per Hour</td><td>Hourly incentive rate</td><td><span class="badge badge-secondary">No</span></td></tr>
                                <tr><td>Fixed Salary</td><td>Total fixed salary</td><td><span class="badge badge-secondary">No</span></td></tr>
                                <tr><td>PF %</td><td>Provident Fund percentage</td><td><span class="badge badge-secondary">No</span></td></tr>
                                <tr><td>ESI %</td><td>ESI percentage</td><td><span class="badge badge-secondary">No</span></td></tr>
                                <tr><td>PT %</td><td>Professional Tax percentage</td><td><span class="badge badge-secondary">No</span></td></tr>
                            </tbody>
                        </table>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">
                        <i class="fas fa-times mr-1"></i> Cancel
                    </button>
                    <button type="submit" class="btn btn-success">
                        <i class="fas fa-upload mr-1"></i> Upload & Import
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

@endsection

@section('scripts')
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
    $(document).ready(function() {
        $('#structureTable').DataTable();

        // Auto Calculate Total
        $('#basic_da, #hra, #conveyance, #washing_allowance').on('input', function() {
            let basic = parseFloat($('#basic_da').val()) || 0;
            let hra = parseFloat($('#hra').val()) || 0;
            let conv = parseFloat($('#conveyance').val()) || 0;
            let wash = parseFloat($('#washing_allowance').val()) || 0;
            $('#fixed_salary').val((basic + hra + conv + wash).toFixed(2));
        });

        // Form Submit
        $('#salaryStructureForm').on('submit', function(e) {
            e.preventDefault();
            $.ajax({
                url: "{{ route('admin.salary-structure.store') }}",
                type: "POST",
                data: $(this).serialize(),
                success: function(response) {
                    Swal.fire('Success', response.message, 'success').then(() => location.reload());
                },
                error: function(xhr) {
                    Swal.fire('Error', 'Failed to save salary structure', 'error');
                }
            });
        });

        // Edit Button Click
        $('.edit-btn').on('click', function() {
            let empId = $(this).data('id');
            $('#employee_id').val(empId).trigger('change');
            $('#basic_da').val($(this).data('basic'));
            $('#hra').val($(this).data('hra'));
            $('#conveyance').val($(this).data('conv'));
            $('#washing_allowance').val($(this).data('wash'));
            $('#incentive_per_hour').val($(this).data('incentive'));
            $('#fixed_salary').val($(this).data('fixed'));
            $('#pf_percentage').val($(this).data('pf'));
            $('#esi_percentage').val($(this).data('esi'));
            $('#pt_percentage').val($(this).data('pt'));

            $('html, body').animate({
                scrollTop: $("#salaryStructureForm").offset().top - 100
            }, 500);
        });
    });
</script>
@endsection
