jQuery(document).ready(function($) {
    var verifiedWhatsapp = '';
    var verifiedToken = '';

    // Get nonces from data attributes
    var $form = $('.hk-appointment-form');
    var ajaxurl = $form.data('ajaxurl');
    var otpNonce = $form.data('otp-nonce');
    var appointmentNonce = $form.data('appointment-nonce');

    // Fallback to hkAjax if available
    if (typeof hkAjax !== 'undefined') {
        ajaxurl = ajaxurl || hkAjax.ajaxurl;
        otpNonce = otpNonce || hkAjax.otp_nonce;
        appointmentNonce = appointmentNonce || hkAjax.appointment_nonce;
    }

    // Modal close button
    $('.hk-apt-modal-close').on('click', function() {
        $('#hk-apt-otp-modal').hide();
    });

    // Close modal when clicking outside
    $(window).on('click', function(e) {
        if ($(e.target).is('#hk-apt-otp-modal')) {
            $('#hk-apt-otp-modal').hide();
        }
    });

    // Send OTP
    $('#hk-apt-send-otp').on('click', function() {
        var whatsapp = $('#hk-apt-whatsapp').val().trim();
        if (!whatsapp) {
            alert('Masukkan nomor WhatsApp');
            return;
        }

        var btn = $(this);
        btn.prop('disabled', true).text('Mengirim...');

        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'hk_send_otp',
                nonce: otpNonce,
                whatsapp: whatsapp
            },
            success: function(response) {
                btn.prop('disabled', false).text('Kirim OTP');
                if (response.success) {
                    $('#hk-apt-otp-modal').show();
                    $('#hk-apt-otp-code').focus();
                } else {
                    alert(response.data.message || 'Gagal mengirim OTP');
                }
            },
            error: function() {
                alert('Terjadi kesalahan');
                btn.prop('disabled', false).text('Kirim OTP');
            }
        });
    });

    // Verify OTP
    $('#hk-apt-verify-otp').on('click', function() {
        var whatsapp = $('#hk-apt-whatsapp').val().trim();
        var otp = $('#hk-apt-otp-code').val().trim();

        if (!otp) {
            alert('Masukkan kode OTP');
            return;
        }

        var btn = $(this);
        btn.prop('disabled', true).text('Memverifikasi...');

        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'hk_verify_otp',
                nonce: otpNonce,
                whatsapp: whatsapp,
                otp: otp
            },
            success: function(response) {
                if (response.success) {
                    verifiedWhatsapp = whatsapp;
                    verifiedToken = response.data.token;
                    $('#hk-apt-verified-token').val(verifiedToken);
                    $('#hk-apt-verified-whatsapp').val(verifiedWhatsapp);
                    $('#hk-apt-otp-modal').hide();
                    $('#hk-apt-otp-section').hide();
                    $('#hk-appointment-form-main').show();
                } else {
                    alert(response.data.message || 'OTP tidak valid');
                    btn.prop('disabled', false).text('Verifikasi OTP');
                }
            },
            error: function() {
                alert('Terjadi kesalahan');
                btn.prop('disabled', false).text('Verifikasi OTP');
            }
        });
    });

    // Submit Appointment
    $('#hk-appointment-form-main').on('submit', function(e) {
        e.preventDefault();

        if (!appointmentNonce) {
            alert('Error: Nonce tidak ditemukan. Silakan refresh halaman.');
            return;
        }

        var formData = $(this).serializeArray();
        formData.push({ name: 'action', value: 'hk_submit_appointment' });
        formData.push({ name: 'nonce', value: appointmentNonce });
        formData.push({ name: 'whatsapp', value: verifiedWhatsapp });
        formData.push({ name: 'token', value: verifiedToken });

        var btn = $(this).find('button[type="submit"]');
        btn.prop('disabled', true).text('Mengirim...');

        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: formData,
            success: function(response) {
                if (response.success) {
                    $('#hk-appointment-form-main').hide();
                    $('#hk-apt-success-message').show();
                } else {
                    alert(response.data.message || 'Gagal membuat janji temu');
                    btn.prop('disabled', false).text('Buat Janji Temu');
                }
            },
            error: function() {
                alert('Terjadi kesalahan');
                btn.prop('disabled', false).text('Buat Janji Temu');
            }
        });
    });
});
