$(document).ready(function () {

    /*
    |--------------------------------------------------------------------------
    | LOAD SUBJECTS
    |--------------------------------------------------------------------------
    */

    $('#loadSubjectsBtn').on('click', function () {

        const examTypeId = $('#exam_type_id').val();
        const classId    = $('#class_id').val();

        if (examTypeId === '') {

            toastr.error('Please select exam type!');
            return;
        }

        if (classId === '') {

            toastr.error('Please select class!');
            return;
        }

        $('#hidden_exam_type_id').val(examTypeId);
        $('#hidden_class_id').val(classId);

        $('#subjectsContainer').html(`

            <div class="text-center p-5">

                <div class="spinner-border text-primary"></div>

                <p class="mt-3 mb-0">

                    Loading subjects...

                </p>

            </div>

        `);

        $.ajax({

            url: 'ajax/exam_ajax.php',

            type: 'GET',

            dataType: 'json',

            data: {

                action: 'get_subjects',
                exam_type_id: examTypeId,
                class_id: classId

            },

            success: function (response) {

                if (!response.success) {

                    toastr.error(response.message);

                    return;
                }

                if (response.subjects.length === 0) {

                    $('#subjectsContainer').html(`

                        <div class="text-center p-5 text-muted">

                            <i class="fas fa-book fa-3x mb-3"></i>

                            <p class="mb-0">

                                No subjects found.

                            </p>

                        </div>

                    `);

                    return;
                }

                let html = `

                    <div class="table-responsive">

                        <table class="table table-bordered table-hover mb-0">

                            <thead class="thead-light">

                                <tr>

                                    <th width="70">
                                        #
                                    </th>

                                    <th>
                                        Subject
                                    </th>

                                    <th width="220">
                                        Exam Date
                                    </th>

                                    <th width="180">
                                        Max Marks
                                    </th>

                                    <th width="150">
                                        No Exam
                                    </th>

                                </tr>

                            </thead>

                            <tbody>

                `;

                response.subjects.forEach((subject, index) => {

                    html += `

                        <tr>

                            <td>

                                ${index + 1}

                            </td>

                            <td>

                                <strong>

                                    ${subject.name}

                                </strong>

                            </td>

                            <td>

                                <input
                                    type="date"
                                    name="date[${subject.id}]"
                                    class="form-control exam-date-input"
                                    value="${subject.date ?? ''}"
                                >

                            </td>

                            <td>

                                <input
                                    type="number"
                                    name="marks[${subject.id}]"
                                    class="form-control"
                                    min="0"
                                    max="1000"
                                    value="${subject.marks ?? 100}"
                                >

                            </td>

                            <td class="text-center">

                                <div class="custom-control custom-switch">

                                    <input
                                        type="checkbox"
                                        class="custom-control-input no-exam-checkbox"
                                        id="no_exam_${subject.id}"
                                        name="no_exam[${subject.id}]"
                                        value="1"
                                        ${subject.no_exam == 1 ? 'checked' : ''}
                                    >

                                    <label
                                        class="custom-control-label"
                                        for="no_exam_${subject.id}"
                                    ></label>

                                </div>

                            </td>

                        </tr>

                    `;
                });

                html += `

                            </tbody>

                        </table>

                    </div>

                `;

                $('#subjectsContainer').html(html);

                $('#saveScheduleBtn').prop('disabled', false);

                /*
                |--------------------------------------------------------------------------
                | DISABLE DATE IF NO EXAM
                |--------------------------------------------------------------------------
                */

                $('.no-exam-checkbox').each(function () {

                    if ($(this).is(':checked')) {

                        $(this)
                            .closest('tr')
                            .find('.exam-date-input')
                            .prop('disabled', true);

                    }

                });

            },

            error: function () {

                toastr.error('Something went wrong!');

            }

        });

    });

    /*
    |--------------------------------------------------------------------------
    | NO EXAM TOGGLE
    |--------------------------------------------------------------------------
    */

    $(document).on('change', '.no-exam-checkbox', function () {

        const row = $(this).closest('tr');

        const dateInput = row.find('.exam-date-input');

        if ($(this).is(':checked')) {

            dateInput.val('');

            dateInput.prop('disabled', true);

        } else {

            dateInput.prop('disabled', false);

        }

    });

    /*
    |--------------------------------------------------------------------------
    | FORM VALIDATION
    |--------------------------------------------------------------------------
    */

    $('#scheduleForm').on('submit', function (e) {

        let valid = true;

        $('.exam-date-input').each(function () {

            const row = $(this).closest('tr');

            const noExam = row.find('.no-exam-checkbox').is(':checked');

            if (!noExam && $(this).val() === '') {

                valid = false;
            }

        });

        if (!valid) {

            e.preventDefault();

            toastr.error(
                'Please fill all exam dates or mark No Exam!'
            );
        }

    });

});