@extends('layouts.master')

@section('content')
<style>
    /* Chrome, Safari, Edge, Opera */
    input[type="number"]::-webkit-outer-spin-button,
    input[type="number"]::-webkit-inner-spin-button {
        -webkit-appearance: none;
        margin: 0;
    }

    /* Firefox */
    input[type="number"]{
        -moz-appearance: textfield;
    }
</style>
<div class="fee__setup">
    <div class="col-md-12 col-xl-12 col-xxl-12 m-auto">
        @if ($errors->any())
            <div class="alert alert-warning m-3" role="alert">
                <ul>
                    @foreach ($errors->all() as $error)
                        <li>{{ $error }}</li>
                    @endforeach
                </ul>
            </div>
        @endif
        <div class="card">
            <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between border-bottom mb-3">
                <h6 class="m-0 table__top__txt">Edit Class Fees</h6>
                <a href="{{ route('class_fees.index') }}" class="btn btn-sm btn-light-blue">View All</a>
            </div>
            <div class="card-body">
                <form action="{{ route('class_fees.update') }}" method="POST">
                    @csrf
                    @method('PUT')
                    <div class="row">
                        @php
                            $class_details = $fee_details->first();
                        @endphp
                        <div class="col-lg-3 col-md-4 col-sm-6">
                            <div class="form-group">
                                <label for="student_class_id">Class</label>
                                <input type="hidden" name="student_class_id" value="{{ $class_details->student_class_id }}">
                                <input type="text" class="form-control" id="student_class_id" value="{{ $class_details->class_name }}" readonly>
                            </div>
                        </div>
                        <div class="col-lg-3 col-md-4 col-sm-6">
                            <div class="form-group">
                                <label for="academic_year_id">Academic Year</label>
                                <input type="hidden" name="academic_year_id" value="{{$class_details->academic_year_id}}">
                                <input type="text" class="form-control" value="{{$class_details->year}}" readonly>
                            </div>
                        </div>
                        <div class="col-lg-3 col-md-4 col-sm-6">
                            <div class="form-group">
                                <label for="tuition_fee">Tuition Fee</label>
                                <input type="number" name="tution_fee" class="form-control tution_fee" id="tution_fee" placeholder="Enter Amount">
                            </div>
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="table-responsive">
                            <table class="table table-bordered">
                                <thead class="thead-light">
                                    <tr>
                                        <th width="180" style="color: var(--light-blue-active) !important">Fee Type</th>
                                        @for ($i = 1; $i <= 12; $i++)
                                            <th class="text-center">{{ DateTime::createFromFormat('!m', $i)->format('M') }}</th>
                                        @endfor
                                    </tr>
                                </thead>
                                <tbody>
                                    @foreach ($feeTypes as $feeType)
                                        <tr>
                                            <td>{{ $feeType->code }}</td>
                                            @for ($i = 1; $i <= 12; $i++)
                                                @php
                                                    $month = $i;
                                                    $amount = $structuredData[$feeType->code][$month] ?? 0;
                                                    $monthName = DateTime::createFromFormat('!m', $i)->format('M');
                                                @endphp
                                                <td>
                                                    <input
                                                        name="{{ $feeType->code . '_' . $monthName }}"
                                                        type="number"
                                                        min="0"
                                                        class="form-control fee-type-field {{ $loop->first ? 'Tuition' : '' }}"
                                                        value="{{ (int) $amount }}"

                                                    >
                                                </td>
                                            @endfor
                                        </tr>
                                    @endforeach
                                </tbody>
                                <tfoot>
                                    <tr id="monthlyTotalRow">
                                        <td><b>Total</b></td>
                                        @for ($i = 1; $i <= 12; $i++)
                                            <td class="text-center">
                                                <b id="total_{{ DateTime::createFromFormat('!m', $i)->format('M') }}">0</b>
                                            </td>
                                        @endfor
                                    </tr>
                                    <tr id="grandTotalRow">
                                        <td><b>Grand Total</b></td>
                                        <td class="text-center" colspan="12">
                                            <b id="grand-total">0</b>
                                        </td>
                                    </tr>
                                </tfoot>
                            </table>
                        </div>
                    </div>
                    <br>
                    <button type="submit" class="btn btn-submit float-right">Update</button>
                    <a href="{{ route('class_fees.index') }}" type="button" class="btn btn-default float-right mr-3" data-dismiss="modal">Discard</a>
                </form>
            </div>
        </div>
    </div>
</div>
@endsection
@section('scripts')

<script>
    function calculateMonthlyTotals() {
        const months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
        let grandTotal = 0;

        months.forEach(month => {
            let total = 0;
            document.querySelectorAll(`input[name$='_${month}']`).forEach(input => {
                const val = parseFloat(input.value) || 0;
                total += val;
            });
            document.getElementById(`total_${month}`).textContent = total;
            grandTotal += total;
        });

        document.getElementById('grand-total').textContent = grandTotal;
    }

    calculateMonthlyTotals();

    $(document).ready(function () {
        $('input[type="number"]').on('input', function () {
            this.value = this.value.replace(/[^0-9]/g, '');
        });

        $('#tution_fee').on('keyup',function () {
            $('.Tuition').val($(this).val());
        });

        function calculateMonthlyTotals() {
            const months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
            let grandTotal = 0;

            months.forEach(month => {
                let total = 0;
                document.querySelectorAll(`input[name$='_${month}']`).forEach(input => {
                    const val = parseFloat(input.value) || 0;
                    total += val;
                });
                document.getElementById(`total_${month}`).textContent = total;
                grandTotal += total;
            });

            // Update grand total
            document.getElementById('grand-total').textContent = grandTotal;
        }

        // Call on page load
        calculateMonthlyTotals();

        // Bind event listeners
        document.querySelectorAll('.fee-type-field').forEach(input => {
            input.addEventListener('input', calculateMonthlyTotals);
        });


        // Select All checkbox change event
        $('#selectAll').change(function () {
            if (this.checked) {
                // Check all checkboxes in the table body
                $('.feeTypeCheckbox').prop('checked', true);
            } else {
                // Uncheck all checkboxes in the table body
                $('.feeTypeCheckbox').prop('checked', false);
            }
            updateInputStates(); // Update input states after checkbox change
        });
        // Individual checkbox change event
        $('.feeTypeCheckbox').change(function () {
            // Check if all checkboxes are checked
            if ($('.feeTypeCheckbox:checked').length === $('.feeTypeCheckbox').length) {
                $('#selectAll').prop('checked', true);
            } else {
                $('#selectAll').prop('checked', false);
            }
            updateInputStates(); // Update input states after checkbox change
        });
        // Function to update input states based on checkbox state
        function updateInputStates() {
            $('.feeTypeCheckbox').each(function () {
                const amountInput = $(this).closest('tr').find('.amountInput');
                amountInput.prop('disabled', !this.checked);
                if (!this.checked) {
                    amountInput.val(''); // Clear input value if checkbox is unchecked
                }
            });
        }
    });
</script>
@endsection
