$(document).ready(function () {

    // MODAL OPEN
    $('#newRegistrationBtn').click(() => {
        $('#registrationModal').removeClass('hidden').addClass('flex');
    });

    $('#closeRegistrationModal').click(() => {
        $('#registrationModal').removeClass('flex').addClass('hidden');
    });

    // SEND OTP
    $('#sendOtpBtn').click(function () {

        $.post("/registrations/send-otp", {
            _token: csrf_token,
            phone: $('#phone').val()
        }, function (res) {

            $('#otpPreview')
                .removeClass('hidden')
                .text("OTP: " + res.otp);
        });

    });

    // VERIFY OTP
    $('#verifyOtpBtn').click(function () {

        $.post("/registrations/verify-otp", {
            _token: csrf_token,
            phone: $('#phone').val(),
            otp: $('#otp').val()
        }, function (res) {

            if (res.status === 'needs_registration') {
                $('#registrationModal').removeClass('flex').addClass('hidden');
                $('#registrationDetailsModal').removeClass('hidden').addClass('flex');
                return;
            }

            if (res.status === 'session_created') {
                location.reload();
                return;
            }

            if (res.status === 'blocked') {
                alert('Already played today');
            }

        });

    });

    // COMPLETE REGISTRATION
    $('#completeRegistrationBtn').click(function () {

        $.post("/registrations/store", {
            _token: csrf_token,
            phone: $('#phone').val(),
            name: $('#name').val(),
            email: $('#email').val()
        }, function (res) {

            if (res.status === 'session_created') {
                location.reload();
            }
        });

    });

});