<script type="text/Javascript">

// Save WhatsApp Settings
$("#whatsapp_settings_form").submit(function(e) {
    e.preventDefault();

    var api_key = $("#api_key").val();
    var sender_id = $("#sender_id").val();

    if (api_key == "" || sender_id == "") {
        swal({
            title: "Error",
            text: "API Key and Sender ID are required",
            icon: "error",
            buttons: false,
            timer: 2000
        });
        return false;
    }

    // Show processing
    $("#settings_form_container").hide();
    $("#settings_processing").show();

    var values = $("#whatsapp_settings_form").serialize();

    $.ajax({
        url: "save_whatsapp_settings.php",
        type: "post",
        data: values,
        success: function(response) {
            $("#settings_form_container").show();
            $("#settings_processing").hide();

            try {
                var result = jQuery.parseJSON(response);

                if (result['error'] == 1) {
                    swal({
                        title: "Error",
                        text: result['error_msg'],
                        icon: "error",
                        buttons: false,
                        timer: 2000
                    });
                } else {
                    swal({
                        title: "Success",
                        text: result['error_msg'],
                        icon: "success",
                        buttons: false,
                        timer: 2000
                    });

                    // Update hidden settings_id if new record was created
                    if (result['settings_id']) {
                        $("#settings_id").val(result['settings_id']);
                    }
                }
            } catch (e) {
                swal({
                    title: "Error",
                    text: "Invalid response from server",
                    icon: "error",
                    buttons: false,
                    timer: 2000
                });
                console.log("Parse error:", e);
            }
        },
        error: function(jqXHR, textStatus, errorThrown) {
            $("#settings_form_container").show();
            $("#settings_processing").hide();
            swal({
                title: "Error",
                text: "Server error. Please try again.",
                icon: "error",
                buttons: false,
                timer: 2000
            });
            console.log(textStatus, errorThrown);
        }
    });
});

// Test WhatsApp Connection
$("#test_btn").click(function() {
    var api_key = $("#api_key").val();
    var sender_id = $("#sender_id").val();

    if (api_key == "" || sender_id == "") {
        swal({
            title: "Error",
            text: "Please enter API Key and Sender ID first",
            icon: "error",
            buttons: false,
            timer: 2000
        });
        return false;
    }

    // Ask for test number
    swal({
        title: "Test WhatsApp Connection",
        text: "Enter a mobile number to send test message (with country code, e.g., 918007819235):",
        content: {
            element: "input",
            attributes: {
                placeholder: "918007819235",
                type: "text",
            },
        },
        buttons: {
            cancel: "Cancel",
            confirm: {
                text: "Send Test",
                closeModal: false,
            }
        },
    }).then((test_number) => {
        if (!test_number) {
            swal.close();
            return;
        }

        // Send test message
        $.ajax({
            url: "test_whatsapp.php",
            type: "post",
            data: {
                api_key: api_key,
                sender_id: sender_id,
                test_number: test_number
            },
            success: function(response) {
                try {
                    var result = jQuery.parseJSON(response);

                    if (result['error'] == 1) {
                        swal({
                            title: "Test Failed",
                            text: result['error_msg'],
                            icon: "error"
                        });
                    } else {
                        swal({
                            title: "Test Successful!",
                            text: result['error_msg'],
                            icon: "success"
                        });
                    }
                } catch (e) {
                    swal({
                        title: "Error",
                        text: "Invalid response from server",
                        icon: "error"
                    });
                }
            },
            error: function() {
                swal({
                    title: "Error",
                    text: "Server error. Please try again.",
                    icon: "error"
                });
            }
        });
    });
});
</script>
