@push('js')
    <script>
        "use strict";
        $(document).on('click', '.generate-content', function(e) {
            e.preventDefault();

            let url = $(this).data('url');
            let targetId = $(this).data('id');
            let targetType = $(this).data('type');

            // Get the current title from the input field dynamically
            if (targetType == 'live_tv_description' || targetType == 'live_tv_meta_description') {
                var titleInput = $(this).closest('.crud-form').find('input[name="tv_name"]');
            } else {
                var titleInput = $(this).closest('.crud-form').find('input[name="title"]');
            }
            let targetTitle = titleInput.val(); // Get the current value

            // Store original button text
            const button = $(this);
            const originalText = button.find('span').html();
            if (!targetTitle) {
                toastr.error('{{ __('title_is_required') }}')
            } else {
                // Show loading text
                button.find('span').text('Loading...');
            }

            $.ajax({
                url: url,
                type: "GET",
                data: {
                    type: targetType,
                    title: targetTitle
                },
                success: function(response) {
                    //console.log(response);

                    let $target = $("#" + targetId);
                    if ($target.length === 0) return;

                    if (!targetTitle) {
                        $target.attr("placeholder", "{{ __('title_not_provided') }}");
                    } else {
                        // console.log(response.content);
                        if (response.content !== undefined) {
                            $target.val(response.content);
                        } else {
                            $target.val("{{ __('failed_to_load_content') }}");
                        }
                    }
                },
                error: function(xhr) {
                    let $target = $("#" + targetId);
                    if ($target.length === 0) return;

                    // Handle server errors
                    let msg = xhr.responseJSON.content;
                    if (xhr.responseJSON && xhr.responseJSON.content) {
                        msg = xhr.responseJSON.content;
                    }
                    $target.val(msg);
                },
                complete: function() {
                    // Restore original button text
                    button.find('span').html(originalText);
                }
            });
        });
    </script>
@endpush
<script>
    "use strict";

    // modal open with ajax and custom view
    function ajaxModal(size, url, title = null) {
        $.ajax({
            url: url,
            type: "GET",
            data: {
                size: size
            },
            success: function(result) {
                // Handle the response (result)
                $("#ajaxModal").modal("show");
                // modal size
                $("#modalSize").addClass(size);
                $("#modalTitle").text(title);
                // show the view
                $("#modalContent").html(result);
            }
        });
    }


    function ajaxLogin() {
        // Clear previous errors
        $("#login-email, #login-password").removeClass('border border-danger');
        $("#error-email, #error-password").html('');

        // Get the values of the email and password fields
        var email = $("#login-email").val();
        var password = $("#login-password").val();

        // Basic client-side check for empty fields
        if (!email || !password) {
            if (!email) {
                $("#login-email").addClass('border border-danger');
                $("#error-email").html('<span class="text-danger fs-14px">{{ __('email_is_required') }}</span>');
            }
            if (!password) {
                $("#login-password").addClass('border border-danger');
                $("#error-password").html('<span class="text-danger fs-14px">{{ __('password_is_required') }}</span>');
            }
            return;
        }

        var csrfToken = $('meta[name="csrf-token"]').attr('content');
        var formData = $("#loginForm").serialize();

        var showLoginFieldError = function(type, message) {
            var field = type === 'email' ? 'email' : 'password';
            $("#login-" + field).addClass('border border-danger');
            $("#error-" + field).html('<span class="text-danger fs-14px">' + message + '</span>');
        };

        var showLoginToast = function(msg) {
            if (typeof toastr !== "undefined") {
                toastr.error(msg);
            } else {
                alert(msg);
            }
        };

        $.ajax({
            url: $("#loginForm").attr('action'),
            type: "POST",
            dataType: "json",
            headers: {
                'X-CSRF-TOKEN': csrfToken,
                'Accept': 'application/json',
                'X-Requested-With': 'XMLHttpRequest'
            },
            data: formData,
            success: function(response) {
                if (response && response.success && response.redirect_url) {
                    window.location.href = response.redirect_url;
                    return;
                }

                if (response && response.errors) {
                    $.each(response.errors, function(field, messages) {
                        var inputField = $("#login-" + field);
                        var errorDiv = $("#error-" + field);
                        if (inputField.length && errorDiv.length) {
                            inputField.addClass('border border-danger');
                            errorDiv.html('<span class="text-danger fs-14px">' + (messages[0] || messages) + '</span>');
                        }
                    });
                    return;
                }

                if (response && response.message && response.type) {
                    showLoginFieldError(response.type, response.message);
                    return;
                }

                showLoginToast((response && response.message) || '{{ __("something_went_wrong_please_try_again!") }}');
            },
            error: function(xhr, textStatus) {
                if (textStatus === "parsererror") {
                    showLoginToast('{{ __("something_went_wrong_please_try_again!") }}');
                    return;
                }
                var json = xhr.responseJSON;
                if (xhr.status === 422 && json) {
                    if (json.errors) {
                        $.each(json.errors, function(field, messages) {
                            var inputField = $("#login-" + field);
                            var errorDiv = $("#error-" + field);
                            if (inputField.length && errorDiv.length) {
                                inputField.addClass('border border-danger');
                                errorDiv.html('<span class="text-danger fs-14px">' + (messages[0] || messages) + '</span>');
                            }
                        });
                        return;
                    }
                    if (json.message && json.type) {
                        showLoginFieldError(json.type, json.message);
                        return;
                    }
                }
                showLoginToast((json && (json.message || json.error)) || xhr.statusText || '{{ __("something_went_wrong_please_try_again!") }}');
            }
        });
    }


    function ajaxSignUp() {}
</script>
@if (get_config('one_signal_status'))
<script>
    var isCallback = {!! json_encode(request()->is(['auth.facebook.callback*','auth.google.callback*'])) !!};
    var appId = "{{ get_config('one_signal_id') }}";

    window.OneSignalDeferred = window.OneSignalDeferred || [];

    if (isCallback) {
        // Delay initialization only for callback URLs
        setTimeout(function() {
            OneSignalDeferred.push(async function(OneSignal) {
                await OneSignal.init({ appId: appId });
            });
        }, 1000); // adjust delay as needed
    } else {
        // Normal initialization for other pages
        OneSignalDeferred.push(async function(OneSignal) {
            await OneSignal.init({ appId: appId });
        });
    }
</script>
@endif
