@extends('layouts.master')

@section('content')
    <style>
        .custom-switch-inline {
            display: inline-block;
            margin-left: 10px; /* add some space between the label and the checkbox */
        }

        .custom-switch-inline .custom-control-label {
            margin-left: 5px; /* add some space between the checkbox and the label */
        }

        .table td, .table th {
            padding: .25rem;
            vertical-align: top;
            border-top: 1px solid #e3e6f0;
        }

        .select2-selection__rendered {
            line-height: 27px !important;
        }

        .data__search .content {
            border-left: 3px solid var(--logo-edu);
            padding-left: 7px;
        }

        .data__search .multiselect-filter {
            display: none;
        }

        .data__search .dropdown-menu.show {
            display: block;
            width: 100%;
            padding-top: 13px;
            border-radius: 0 0 4px 4px !important;
            margin-top: -2px;
        }

        .form-control:disabled, .form-control[readonly] {
            background-color: transparent;
            opacity: 1;
            border: none;
            color: #646464;
            font-weight: 300;
            padding-left: 0;
        }

        .fee__sum .form-control:disabled, .fee__sum .form-control[readonly] {
            background-color: transparent;
            opacity: 1;
            border: none;
            color: #000;
            font-weight: 700;
            padding-left: 0;
        }

        .fee__sum {
            background: #fffcf9;
            border: 1px solid orange;
            padding: 9px;
        }

        .item__fee__type {
            border-bottom: 1px solid #ddd;
            padding-bottom: .1rem;
            margin-bottom: .1rem;
            display: inline-block;
            font-size: .9rem;
        }

        .fee__sum label {
            margin-bottom: 0;
            color: #222222;
        }

        .fee__sum .fs__l {
            line-height: 1;
            padding: 4px 7px;
            margin-bottom: 10px;
            justify-content: space-between;
            align-items: center;
            background: #40a6dd21;
            border: 1px solid #40a6dd3d;
        }

        /*.data__search .table-bordered td, .data__search .table-bordered th {*/
        /*    border: 1px solid #fce5bf;*/
        /*}*/
    </style>

    <style>
        /*================
        Fee Collection Page
        =====================*/
        .custom-switch-inline {
            display: inline-block;
            margin-left: 10px; /* add some space between the label and the checkbox */
        }

        .custom-switch-inline .custom-control-label {
            margin-left: 5px; /* add some space between the checkbox and the label */
        }

        .table td, .table th {
            padding: .25rem;
            vertical-align: top;
            border-top: 1px solid #e3e6f0;
        }

        .select2-selection__rendered {
            line-height: 27px !important;
        }

        .fee__sum .form-control:disabled, .fee__sum .form-control[readonly] {
            background-color: transparent;
            opacity: 1;
            border: none;
            color: #000;
            font-weight: 700;
            padding-left: 0;
            font-size: 16px;
            text-align: right;
        }

        .fee__sum {
            background: transparent;
            border: 1px solid #d1d5dd;
            padding: 9px;
        }

        .fee__sum label {
            margin-bottom: 0;
            color: #222222;
        }

        .fee__sum .fs__l {
            background: #ecf1f9;
            line-height: 1;
            padding: 4px 7px;
            margin-bottom: 10px;
            justify-content: space-between;
            align-items: center;
        }

        .fee__sum .label__fine {
            display: flex;
            align-items: center;
            justify-content: space-between;
        }

        /*.data__search .table-bordered td, .data__search .table-bordered th {*/
        /*    border: 1px solid #fce5bf;*/
        /*}*/


        .fee__collection__body .card-body .table .thead-light th {
            font-weight: 500;
            font-size: 1rem;
            padding: .7rem 1.5rem;
            line-height: 1;
        }

        .fee__collection__body .card-body .table .thead-light th:last-child {
            text-align: right !important;
        }

        .fee__collection__body .custom-control-input:checked ~ .custom-control-label::before {
            color: #fff;
            border-color: #00b744;
            background-color: #00b744;
        }

        .fee__collection__body .custom-checkbox .custom-control-label::before {
            border-radius: 0px;
            top: 5px;
        }

        .fee__collection__body .table td, .table th {
            padding: .8rem 1.5rem;
            vertical-align: middle;
            border-top: 1px solid #e3e6f0;
        }

        .fee__collection__body table .tbl__footer {
            background: #25af2c24;
        }

        .fee__collection__body table td:first-child {
            text-align: left !important;
        }

        .fee__collection__body table td:last-child {
            text-align: right !important;
        }

        .fee__collection__body table .tbl__footer td {
            font-weight: bold;
            color: var(--black);
            text-align: center !important;
        }

        .fee__collection__body table .tbl__footer td:last-child {
            text-align: right !important;
        }
    </style>

    <div class="card data__search">
        <div class="card-body card__head">
            <form action="{{ route('collect_fee.create') }}" method="GET">
                <div class="row">
                    <div class="col-md-4 col-lg-4 col-xl-2 xxl-2 mb-3 col-6">
                        <div class="form-group mb-0">
                            @component('components.search_student', [
                                'student_name' => $student_name ?? '',
                                'student_id_no' => $student_id_no ?? '',
                                'required' => 'required',
                            ])
                            @endcomponent
                        </div>
                    </div>

                    <div class="col-md-4 col-lg-4 col-xl-2 xxl-2 mb-3 col-6">
                        <div class="form-group mb-0">
                            @php
                                $selectedYear = request()->year_id ?? $defaultYear;
                                $selectedMonth = request()->month ?? [date('n')] ;
                            @endphp
                            {{ generateDropdown($years, 'name="year_id" class="form-control form-control-sm" required', $selectedYear, 'Year' ) }}
                        </div>
                    </div>
                    <div class="col-md-4 col-lg-4 col-xl-2 xxl-2 mb-3 col-6">
                        <div class="form-group mb-0">
                            {{ multiSelectDropdown($months, 'name="month[]" class="form-control form-control-sm" id="multiselect"', $selectedMonth, 'Select months...' ) }}
                        </div>
                    </div>
                    <div class="col-lg-3">
                        <div class="form-group mb-0">
                            <button class="btn btn-sm btn-info">Search</button>
                        </div>
                    </div>
                    @isset($student_details)

                        <div class="col-md-12">
                            <div class="content mt-3">
                                <div class="title">
                                    Student Info:
                                </div>
                                <div class="body d-flex">
                                    <div class="name mr-3">
                                        <span><b>Name:</b> {{ ($student_details->first_name ?? '') . ' ' . ($student_details->last_name ?? '') }}</span>
                                    </div>
                                    <div class="class mr-3">
                                        <span><b>Class (Section): </b>
                                            {{ $student_details->studentClass->class_name ?? '' }}
                                            @if ($student_details?->section?->section_name)
                                                ({{ $student_details?->section?->section_name }})
                                            @endif
                                        </span>
                                    </div>
                                    <div class="roll mr-3">
                                        <span><b>Roll: </b> {{ $student_details->class_roll ?? '' }}</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    @endisset
                </div>
            </form>
        </div>
    </div>
    @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
    @if (isset($selectedFeeTypes) && empty($selectedFeeTypes))
        <div class="text-center">
            <svg viewBox="0 0 112 112" width="112" height="112" class="x14rh7hd x1lliihq x1tzjh5l x1k90msu x2h7rmj x1qfuztq"
                 style="--x-color: var(--primary-icon);">
                <defs>
                    <clipPath id="a">
                        <path fill="#a4a7ab" d="M94.38 98.59H21.51V11.18h44.55l28.32 23.45v63.96z"></path>
                    </clipPath>
                </defs>
                <path fill="#a4a7ab" d="M94.38 98.59H21.51V11.18h44.55l28.32 23.45v63.96z"></path>
                <g clip-path="url(#a)">
                    <path fill="#a4a7ab" d="M94.38 98.59H21.51V11.18h44.55l28.32 23.45v63.96z"></path>
                    <path fill="#87d534" d="M65.94 8.72h32.27v25.95H73a7 7 0 0 1-7-7V8.72h-.06z"></path>
                </g>
                <rect width="57.1" height="3.51" x="29.39" y="47.67" fill="#fff" rx="1.68"></rect>
                <rect width="57.1" height="3.51" x="29.39" y="58.2" fill="#fff" rx="1.68"></rect>
                <rect width="57.1" height="3.51" x="29.39" y="68.73" fill="#fff" rx="1.68"></rect>
            </svg>
            <div class="m-3" role="alert">
                <p class="text-muted">No Fees setup assigned yet for class "{{$student_details->studentClass->class_name}}"- {{$years[$year_id]}}</p>
                <a href="{{route('class_fees.create')}}" target="_blank" class="txt_underline">Setup Now</a>
            </div>
        </div>
    @endif

    @if (isset($selectedFeeTypes) && !empty($selectedFeeTypes))
        <div class="card mt-4 data__search fee__collection__body">
            <div class="card-body">
                <form action="{{ route('collect_fee.store') }}" method="POST">
                    @csrf
                    <div class="row">
                        <div class="col-md-8">
                            @isset($student_details)
                                <input type="hidden" name="student_id" value="{{ $student_details->id }}">
                                <input type="hidden" name="discount_type" value="{{ $discount?->discount_type }}">
                                <input type="hidden" name="discount" value="{{ $discount?->amount }}">
                                <input type="hidden" name="year_id" value="{{ $year_id ?? '' }}">
                                <input type="hidden" name="shift_id" value="{{ $student_details->shift_id }}">
                                <input type="hidden" name="student_class_id"
                                       value="{{ $student_details->student_class_id }}">
                                <input type="hidden" name="section_id" value="{{ $student_details->section_id }}">
                                <div class="table-responsive">
                                    <table class="table table-bordered" id="feeTypeTable">
                                        <thead class="thead-light">
                                        <tr>
                                            <th>Months</th>
                                            <th style="min-width: 250px">Fee Type</th>
                                            <th class="text-center">Status</th>
                                            <th>Fee (Tk.)</th>
                                            <th>Disc. (Tk.)</th>
                                            <th>Grand Total (Tk.)</th>
                                        </tr>
                                        </thead>
                                        <tbody>
                                        @if (!empty($selectedFeeTypes))
                                            @php
                                                $single_discount = 0;
                                                $allItemDiscount = 0;
                                                $active_late_fine_amount = 0;
                                                $transport_amount = 0;
                                                $hostel_amount = 0;
                                                $late_fine_ststus = get_setting_value(Settings::LATE_FINE_STATUS) ? get_setting_value(Settings::LATE_FINE_STATUS) : 0;
                                                $late_fine_start_day = get_setting_value(Settings::LATE_FINE_START_DAY) ? get_setting_value(Settings::LATE_FINE_START_DAY) : null;
                                                $late_fine_amount = get_setting_value(Settings::LATE_FINE_AMOUNT) ? get_setting_value(Settings::LATE_FINE_AMOUNT) : 0;
                                                
                                                // Transport fee check
                                                if (!empty($transportFeeType) && !empty($transport_fee)) {
                                                    $transport_amount = (int) ($transport_fee->monthly_cost ?? 0);
                                                }

                                                // Hostel fee check
                                                if (!empty($hostelFeeType) && !empty($hostel_fee)) {
                                                    $hostel_amount = (int) ($hostel_fee->cost ?? 0);
                                                }
                                            @endphp

                                            @foreach($selectedFeeTypes as $fee)

                                                @php
                                                    if(!empty($discount)){
                                                        // dd($fee['total_amount']);
                                                        $monthlyTotalFees = $fee['total_amount'];
                                                         // Transport fee check
                                                        if (!empty($transportFeeType) && !empty($transport_fee)) {
                                                            $monthlyTotalFees = $monthlyTotalFees + (int) ($transport_fee->monthly_cost ?? 0);
                                                        }

                                                        // Hostel fee check
                                                        if (!empty($hostelFeeType) && !empty($hostel_fee)) {
                                                            $monthlyTotalFees = $monthlyTotalFees + (int) ($hostel_fee->cost ?? 0);
                                                        }
                                                        
                                                        $single_discount = calculateDiscount($monthlyTotalFees, $discount->discount_type, $discount->amount);
                                                        $allItemDiscount += $single_discount;
                                                    }
                                                @endphp


                                                <tr class="subject-entry">
                                                    <td>{{ $fee['month_name'] ?? 'N/A' }}</td>
                                                    <td>
                                                        @foreach ($fee['fee_types'] as $fee_type)

                                                            @php
                                                                $uniqueKey = $fee_type['fee_type_id'] . '_' . $fee['month'];
                                                            @endphp

                                                            <span class="item__fee__type">{{ Str::title(str_replace('-', ' ', $fee_type['fee_type_name']))." ".$fee_type['fee_type_amount'] }} Tk.</span>
                                                            <br>

                                                            @if($fee['payment_status'] == 'Due')
                                                                <input type="hidden"
                                                                       class="custom-control-input fee-checkbox"
                                                                       id="feeCheck{{ $fee_type['fee_type_id'] }}"
                                                                       name="fee_type_id[]"
                                                                       value="{{ $fee_type['fee_type_id'] }}"
                                                                       data-month="{{ $fee['month'] }}"
                                                                       data-amount="{{ $fee_type['fee_type_amount'] }}">

                                                                <input type="hidden" name="amount[{{ $uniqueKey }}]"
                                                                       value="{{ $fee_type['fee_type_amount'] }}">
                                                                <input type="hidden" name="month[{{ $uniqueKey }}]"
                                                                       value="{{ $fee['month'] }}">
                                                            @endif
                                                        @endforeach

                                                        @if ($transport_fee && $transportFeeType)
                                                            <span class="item__fee__type">transport fee {{ (int) $transport_fee->monthly_cost }} Tk.</span>
                                                             @if($fee['payment_status'] == 'Due')
                                                                <input type="hidden"
                                                                       class="custom-control-input fee-checkbox"
                                                                       id="feeCheck{{ $transportFeeType->id }}"
                                                                       name="fee_type_id[]"
                                                                       value="{{ $transportFeeType->id }}"
                                                                       data-month="{{ $fee['month'] }}"
                                                                       data-amount="{{ (int) $transport_fee->monthly_cost }}">

                                                                <input type="hidden" name="amount[{{ (int) $transportFeeType->id }}_{{$fee['month']}}]"
                                                                       value="{{ (int) $transport_fee->monthly_cost }}">
                                                                <input type="hidden" name="month[{{ (int) $transportFeeType->id }}_{{$fee['month']}}]"
                                                                       value="{{ $fee['month'] }}">
                                                            @endif
                                                        <br>
                                                        @endif

                                                        @if ($hostel_fee && $hostelFeeType)
                                                            <span class="item__fee__type">Hostel fee {{ (int) $hostel_fee->cost }} Tk.</span>
                                                            @if($fee['payment_status'] == 'Due')
                                                                <input type="hidden"
                                                                       class="custom-control-input fee-checkbox"
                                                                       id="feeCheck{{ $hostelFeeType->id }}"
                                                                       name="fee_type_id[]"
                                                                       value="{{ $hostelFeeType->id }}"
                                                                       data-month="{{ $fee['month'] }}"
                                                                       data-amount="{{ (int) $hostel_fee->cost }}">

                                                                <input type="hidden" name="amount[{{ $hostelFeeType->id }}_{{$fee['month']}}]"
                                                                       value="{{ (int) $hostel_fee->cost }}">
                                                                <input type="hidden" name="month[{{ (int) $hostelFeeType->id }}_{{$fee['month']}}]"
                                                                       value="{{ $fee['month'] }}">
                                                            @endif
                                                        <br>
                                                        @endif
                                                        

                                                    </td>
                                                    <td class="text-center">
                                                        @if($fee['payment_status'] == 'Due')
                                                            {!! getStatusBadge(Status::UNPAID) !!}
                                                        @else
                                                            {!! getStatusBadge(Status::PAID) !!}
                                                        @endif
                                                    </td>
                                                    <td class="text-center">{{ $fee['total_amount'] + $transport_amount + $hostel_amount ?? '0.00' }}</td>
                                                    <td class="text-center">{{ $single_discount }}</td>
                                                    <td class="text-center">{{ $fee['total_amount'] + $transport_amount + $hostel_amount  -  $single_discount ?? 0  }}

                                                    </td>
                                                </tr>
                                            @endforeach
                                            <tr class="tbl__footer">
                                                <td colspan="3"><b> Grand Total </b></td>
                                                <td> {{ $grandTotal ?? '0.00'}} </td>
                                                <td> {{ $allItemDiscount ?? '0.00' }} </td>
                                                <td> {{ $grandTotal - $allItemDiscount ?? '0.00'}} </td>
                                            </tr>
                                        @endif
                                        </tbody>
                                    </table>
                                </div>
                            @endisset
                        </div>
                        <div class="col-md-4">
                            <div class="fee__sum">
                                <div class="total__fees fs__l d-flex">
                                    <label>Total Fees:</label>
                                    <div class="value">
                                        <input type="text"
                                               class="form-control form-control-sm"
                                               name="total_amount"
                                               value="{{ $totalDue ?? '0.00' }}" readonly>
                                    </div>
                                </div>
                                <div class="total__dis fs__l d-flex">
                                    <label>Total Discount:</label>
                                    <div class="value">
                                        <input type="text" class="form-control form-control-sm total_discount"
                                            id="total_discount" name="total_discount"
                                            value="{{ $totalDiscount ?? '0.00'}}" readonly>
                                    </div>
                                </div>
                                
                                @if ($late_fine_ststus == 1 && $late_fine_start_day <= date('j') && $late_fine_amount > 0)
                                    @php
                                        $active_late_fine_amount = $late_fine_amount;
                                    @endphp
                                    <div class="late__fine fs__l d-flex justify-content-between">
                                        <div class="label__fine">
                                            <label>Late Fine:</label>
                                        </div>
                                        <div class="value">
                                            <input type="text" class="form-control form-control-sm late_fine"
                                                   name="late_fine"
                                                   value="{{ $late_fine_amount }}" readonly>
                                        </div>
                                    </div>
                                @endif

                                @if(count($selectedMonth) == 1)
                                <div class="total__dis fs__l d-flex">
                                    <label>Special Discount:</label>
                                    <div class="value">
                                        <input type="number" class="form-control form-control-sm special_discount"
                                            name="special_discount" 
                                            min="0" max="{{$totalDue + $active_late_fine_amount - $totalDiscount}}">
                                    </div>
                                </div>
                                @endif

                                <input type="hidden" id="base_total"
                                    value="{{ $totalDue + $active_late_fine_amount - $totalDiscount }}">

                                <div class="grand__total fs__l d-flex">
                                    <label>Grand Total:</label>
                                    <div class="value">
                                        <input type="text" class="form-control form-control-sm grand_total"
                                               name="grand_total"
                                               value="{{ $totalDue + $active_late_fine_amount - $totalDiscount ?? '0.00' }}"
                                               readonly>
                                    </div>
                                </div>
                                <div class="note my-3">
                                    <label class="mb-1">Payment Method:</label>
                                    {{ generateDropdown($paymentMethods, 'name="payment_method" id="payment_method" class="form-control form-control-sm" required', old('payment_method', Accounting::CASH), '' ) }}
                                </div>
                                <div class="note">
                                    <label class="mb-1">Note (Optional):</label>
                                    <textarea class="form-control form-control-sm note" name="note" id="" cols="30"
                                              rows="2"
                                              placeholder="Write note or description if needed."></textarea>
                                </div>

                            </div>
                            <div class="flex justify-content-end mt-3">
                                {{-- <button type="submit" class="btn btn-primary mt-2" name="action" value="collect">Collect</button> --}}
                                <button type="submit" class="btn btn-submit mt-2" name="action" value="collect-print">
                                    Submit & Print
                                </button>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    @endif
@endsection

@section('scripts')
    <script>
        $(document).on('input', '.special_discount', function () {
            let existingDiscount = parseFloat($('#total_discount').val()) || 0;
            let baseTotal = parseFloat($('#base_total').val()) || 0;
            let discount  = parseFloat($(this).val()) || 0;

            if (discount > baseTotal) {
                discount = baseTotal;
                $(this).val(baseTotal);
            }
            console.log(discount)
            let discountTotal = discount;
            console.log(discountTotal)
            let grandTotal = baseTotal - discount;
            $('.total_discount').val(discountTotal);
            $('.grand_total').val(grandTotal);
        });

        document.addEventListener('DOMContentLoaded', function () {
            const monthCheckboxes = document.querySelectorAll('.month-checkbox');
            const feeCheckboxes = document.querySelectorAll('.fee-checkbox');
            const totalAmountInput = document.querySelector('.total_amount');
            const grandTotalInput = document.querySelector('.grand_total');

            function updateTotals() {
                let total = 0;

                document.querySelectorAll('.fee-checkbox:checked').forEach(cb => {
                    total += parseFloat(cb.dataset.amount);
                });

                totalAmountInput.value = total.toFixed(2);
                grandTotalInput.value = total.toFixed(2); // Assuming late fine is 0
            }

            monthCheckboxes.forEach(checkbox => {
                checkbox.addEventListener('change', function () {
                    const month = this.dataset.month;

                    document.querySelectorAll(`.fee-checkbox[data-month="${month}"]`).forEach(cb => {
                        cb.checked = this.checked;
                    });

                    updateTotals();
                });
            });

            // Recalculate on manual fee-type checkbox changes too
            feeCheckboxes.forEach(cb => {
                cb.addEventListener('change', updateTotals);
            });

            // Optional: recalculate on page load (if some already checked)
            updateTotals();
        });
    </script>



    <script>
        $(document).ready(function () {
            // Select All checkbox change event
            $('#selectAll').change(function () {
                $('.feeTypeCheckbox').prop('checked', this.checked);
            });

            $('#multiselect').multiselect({
                // Customization Options
                enableFiltering: true,           // Search/Filter option
                filterPlaceholder: 'Search...',  // Filter placeholder text
                maxHeight: 250,                  // Maximum dropdown height
                numberDisplayed: 3,              // Number of selected items to display
                disableIfEmpty: true,            // Disable if no options
                includeSelectAllOption: true,
                // Text Configurations
                nonSelectedText: 'Select Options',
                allSelectedText: 'All Selected',

                // Button Width
                buttonWidth: '100%',

                // Custom Styling
                buttonClass: 'btn btn-light',

                // Event Handlers
                onChange: function (option, checked) {
                    var selectedOptions = $('#multiselect').val();
                }
            });

            const currentMonth = parseInt("{{ date('m') }}");
            const lateFineAmount = parseFloat("{{ get_setting_value(Settings::LATE_FINE_AMOUNT) }}");
            const lastPayDay = parseFloat("{{ get_setting_value(Settings::LATE_FINE_START_DAY) }}");
            const currentDay = parseInt("{{ date('d') }}");

            let totalAmount = 0;
            let totalDiscount = 0;
            let grandTotal = 0;
            let lateFine = 0;

            // Function to determine if late fine should apply
            function shouldApplyLateFine() {
                let applyLateFine = false;
                $('.feeTypeCheckbox:checked').each(function () {
                    const month = parseInt($(this).closest('tr').find('.fee-month').val());
                    if (month < currentMonth || (month === currentMonth && lastPayDay < currentDay)) {
                        applyLateFine = true;
                    }
                });
                return applyLateFine;
            }

            // Update totals
            function updateTotals(amountChange, discountChange) {
                totalAmount += amountChange;
                totalDiscount += discountChange;
                grandTotal = (totalAmount + lateFine) - totalDiscount;
                $('.total_amount').val(totalAmount);
                $('.total_discount').val(totalDiscount);
                $('.late_fine').val(lateFine);
                $('.grand_total').val(grandTotal);
            }

            // Individual checkbox change event
            $('.feeTypeCheckbox').change(function () {
                const amount = parseFloat($(this).closest('tr').find('.amountInput').val());
                const discount = parseFloat($(this).closest('tr').find('.discount').val() || 0);

                if (this.checked) {
                    updateTotals(amount, discount);
                } else {
                    updateTotals(-amount, -discount);
                }

                lateFine = shouldApplyLateFine() && $('.customSwitch1').prop('checked') ? lateFineAmount : 0;
                updateTotals(0, 0); // Update grand total with late fine
            });

            $('.customSwitch1').change(function () {
                lateFine = this.checked && shouldApplyLateFine() ? lateFineAmount : 0;
                $('.late_fine').val(lateFine);
                grandTotal = (totalAmount + lateFine) - totalDiscount;
                $('.grand_total').val(grandTotal);
            });
        });
    </script>
@endsection

