@extends('schoolLayout.app')

@section('content')
    <style>
        label.error {
            color: red;
            font-size: 14px;
            display: inline-block;
            margin-top: 5px;
        }

        input.error,
        select.error {
            border: 1px solid red;
        }

        .bulk-promotion-section {
            background-color: #f8fafc;
            border: 1px solid #e2e8f0;
            border-radius: 0.5rem;
            padding: 1.5rem;
            margin-top: 2rem;
        }
    </style>

    <div class="w-full mx-auto bg-[#f9fafc] mt-10 bg-white p-8 rounded-lg shadow-md">
        <h2 class="text-2xl mb-6">Bulk Class Promotion</h2>

        <form action="{{ route('promotions.bulk') }}" method="POST" id="admForm">
            @csrf
            @include('successError')

            <!-- Bulk Promotion Section -->
            <div class="grid grid-cols-1 md:grid-cols-3 gap-4 bg-blue-50 p-4 rounded-lg">
                <div>
                    <label class="block mb-1">Current Class</label>
                    <select name="current_class_id" id="current-class-select" class="w-full p-2 border rounded">
                        <option value="">Select Class</option>
                        @foreach ($classes as $class)
                            <option value="{{ $class->id }}">{{ $class->name }}</option>
                        @endforeach
                    </select>
                </div>

                <div>
                    <label class="block mb-1">Promote To</label>
                    <select name="next_class_id" id="next-class-select" class="w-full p-2 border rounded">
                        <option value="">Select Target Class</option>
                        @foreach ($classes as $class)
                            <option value="{{ $class->id }}" {{ $class->name == 'Nursery' ? 'selected' : '' }}>
                                {{ $class->name }}
                            </option>
                        @endforeach
                    </select>
                </div>

                <div class="flex items-end">
                    <button type="submit"
                        class="bg-[#0197FF] text-white px-4 py-2 rounded hover:bg-blue-700 promotion-button">
                        Promote Entire Class
                    </button>
                </div>
            </div>

            <!-- Fee Structure -->
            <div id="fee-structure-container" class="mt-8">
                <label class="block mb-2 font-semibold">Fee Structure</label>
                <p id="fee-error" class="text-red-500 text-sm hidden">Please select at least one fee.</p>
                <div id="fee-checkboxes" class="grid grid-cols-2 gap-2">
                    <!-- Fees will be loaded here -->
                </div>

                <!-- Total Fee Amount -->
                <div class="mt-4">
                    <label class="block font-semibold">Total Amount</label>
                    <input type="text" name="total_amount" id="total_amount"
                        class="w-full p-2 border rounded bg-gray-100" readonly value="0.00" />
                </div>
            </div>
        </form>
    </div>

    <script>
        $(document).ready(function() {
            // Fetch Nursery fee structure on load
            const defaultClassId = $('#next-class-select').val();
            if (defaultClassId) {
                fetchFeeStructureHTML(defaultClassId);
            }

            // Change class event
            $('#next-class-select').on('change', function() {
                let selectedClassId = $(this).val();
                if (selectedClassId) {
                    fetchFeeStructureHTML(selectedClassId);
                } else {
                    $('#fee-checkboxes').html('');
                    $('#total_amount').val('0.00');
                }
            });

            // Fetch fee structure
            function fetchFeeStructureHTML(classId) {
                $.get(`{{ route('fetch-fee-structure-promote-bulk') }}?class_id=${classId}`, function(response) {
                    $('#fee-checkboxes').html(response.html);
                    calculateTotalFee(); // recalculate
                });
            }

            function calculateTotalFee() {
                let total = 0;
                $('.feeCheckbox').each(function() {
                    if ($(this).is(':checked')) {
                        const feeId = $(this).attr('name').match(/\[(\d+)\]/)[1];
                        const editableInput = $(`input[name="fees[${feeId}][editable_amount]"]`);
                        const amount = parseFloat(editableInput.val()) || 0;
                        total += amount;
                    }
                });
                $('#total_amount').val(total.toFixed(2));
            }

            // Bind checkbox toggle and editable amount change
            $(document).on('change', '.feeCheckbox', calculateTotalFee);
            $(document).on('input', '.editableAmountInput', calculateTotalFee);

            // Recalculate on checkbox change
            $(document).on('change', '.feeCheckbox', calculateTotalFee);

            // jQuery Validation
            $('#admForm').validate({
                ignore: [],
                rules: {
                    current_class_id: {
                        required: true
                    },
                    next_class_id: {
                        required: true,
                        notEqualTo: '#current-class-select',
                    }
                },
                messages: {
                    current_class_id: "Please select current class",
                    next_class_id: {
                        required: "Please select promotion class",
                        notEqualTo: "Promotion class must be different",
                    }
                },
                submitHandler: function(form) {
                    // At least one fee checkbox
                    if ($('.feeCheckbox:checked').length === 0) {
                        $('#fee-error').removeClass('hidden');
                        return false;
                    } else {
                        $('#fee-error').addClass('hidden');
                    }

                    form.submit();
                }
            });

            // Custom validator for notEqualTo
            $.validator.addMethod("notEqualTo", function(value, element, param) {
                return value !== $(param).val();
            }, "Please choose a different value");
        });
    </script>
@endsection
