$(document).ready(function () {

    // When Darja changes, fetch its subjects
    $('#darja').on('change', function () {
        const darjaSn = $(this).val();
        if (!darjaSn) return;

        $('#subjectsListContainer').html('<div class="text-center p-3"><div class="spinner-border text-primary spinner-border-sm"></div></div>');

        // Fetch subjects for this darja
        // We'll use a simplified version of the current logic but with better UI
        $.post('?cmd=deleteSubject', { darjaSn: darjaSn }, function (html) {
            // Extract the table body from the returned HTML since it's a full page reload currently
            // Ideally we'd have a separate API for fetching subjects, but for now we'll adapt to existing pattern
            // or just trigger a page reload which is safer given the current index.php architecture
            window.location.href = '?cmd=deleteSubject&darjaSn=' + darjaSn;
        });
    });

    // Delete Subject handling
    $(document).on('click', '.btn-delete-subject', function () {
        const sno = $(this).data('id');
        const subjectName = $(this).data('name');
        const row = $(this).closest('tr');

        Swal.fire({
            title: 'توجہ فرمائیں',
            text: `کیا آپ واقعی مضمون "${subjectName}" کو حذف کرنا چاہتے ہیں؟`,
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#d33',
            cancelButtonColor: '#3085d6',
            confirmButtonText: 'جی ہاں، حذف کریں',
            cancelButtonText: 'کینسل'
        }).then((result) => {
            if (result.isConfirmed) {
                const $btn = $(this);
                const originalContent = $btn.html();

                $btn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm"></span>');

                $.ajax({
                    url: 'APIs/deleteSubject.php',
                    method: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify({ sno: sno }),
                    dataType: 'json',
                    success: function (response) {
                        if (response.success) {
                            Swal.fire({
                                title: 'کامیابی',
                                text: response.message,
                                icon: 'success',
                                timer: 2000,
                                showConfirmButton: false
                            });
                            row.fadeOut(500, function () {
                                $(this).remove();
                                if ($('#subjectsTable tbody tr').length === 0) {
                                    $('#subjectsTable').after('<div class="alert alert-info text-center m-3">اس درجہ میں کوئی مضمون باقی نہیں ہے</div>');
                                    $('#subjectsTable').remove();
                                }
                            });
                        } else {
                            Swal.fire('غلطی', response.message, 'error');
                            $btn.prop('disabled', false).html(originalContent);
                        }
                    },
                    error: function () {
                        Swal.fire('خرابی', 'سرور سے رابطہ کرنے میں ناکامی آئی', 'error');
                        $btn.prop('disabled', false).html(originalContent);
                    }
                });
            }
        });
    });

});
