/* 
 * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
 * Click nbfs://nbhost/SystemFileSystem/Templates/Other/javascript.js to edit this template
 */


$ = jQuery;
$(document).ready(function () {
    $(".bank_save").click(function () {
        var enable_bank = $("#enable_bank").is(":checked");
        var stripe_publishable_key = $("#stripe_publishable_key").val();
        var method_id = $("#method_id").val();
        var nonce = dspp_nonces.add_payment_methode;
        var ajaxUrl = dspp_nonces.ajax_url;
        if (method_id === "") {
            method_id = 0;
        }
        if (stripe_publishable_key === "") {
            alert("Bank details are required.");
        } else {
            $('#dspp-bank_save').prop('disabled', true);
            $('#fullpage-loader').show();
            $.ajax({
                url: ajaxUrl,
                type: "POST",
                data: {
                    action: "dspp_add_payment_methode", // Corrected action hook
                    nonce: nonce,
                    enable: enable_bank,
                    user_plublish: stripe_publishable_key,
                    methode: "Bank",
                    method_id: method_id
                },
                success: function (response) {
                    $('#dspp-bank_save').prop('disabled', false);
                    $('#fullpage-loader').hide();
                    if (response.success) {
                        $(".success").text(response.data);
                    } else {
                        $(".success").text(response.data);
                    }
                    location.reload();
                }
            });
        }
    });
    $(".stripe_save").click(function () {
        var enable_stripe = $("#enable_stripe").is(":checked");
        var stripe_publishable_key = $("#stripe_publishable_key").val();
        var stripe_secret_key = $("#stripe_secret_key").val();
        var method_id = $("#method_id").val();
        var nonce = dspp_nonces.add_payment_methode;
        var ajaxUrl = dspp_nonces.ajax_url;
        if (stripe_publishable_key === "" || stripe_secret_key === "") {
            alert("Publishable key and secret are required fields.");
        } else {
            $('#dspp-stripe_save').prop('disabled', true);
            $('#fullpage-loader').show();
            $.ajax({
                url: ajaxUrl,
                type: "POST",
                data: {
                    action: "dspp_add_payment_methode", // Corrected action hook
                    nonce: nonce,
                    enable: enable_stripe,
                    user_plublish: stripe_publishable_key,
                    secret_key: stripe_secret_key,
                    methode: "Strip",
                    method_id: method_id
                },
                success: function (response) {
                    $('#dspp-stripe_save').prop('disabled', false);
                    $('#fullpage-loader').hide();
                    if (response.success) {
                        $(".success").text(response.data);
                    } else {
                        $(".success").text(response.data);
                    }
                    location.reload();
                }
            });
        }
    });
    $(".paypal_save").click(function () {
        $(".paypal_save").prop("disabled");
        var enable_paypal = $("#enable_paypal").is(":checked");
        var stripe_publishable_key = $("#stripe_publishable_key").val();
        var stripe_secret_key = $("#stripe_secret_key").val();
        var method_id = $("#method_id").val();
        var nonce = dspp_nonces.add_payment_methode;
        var ajaxUrl = dspp_nonces.ajax_url;
        if (stripe_publishable_key === "" || stripe_secret_key === "") {
            alert("User ID and Secret are required fields.");
        } else {
            $('#dspp-paypal_save').prop('disabled', true);
            $('#fullpage-loader').show();
            $.ajax({
                url: ajaxUrl,
                type: "POST",
                data: {
                    action: "dspp_add_payment_methode", // Corrected action hook
                    nonce: nonce,
                    enable: enable_paypal,
                    user_plublish: stripe_publishable_key,
                    secret_key: stripe_secret_key,
                    methode: "Paypal",
                    method_id: method_id
                },
                success: function (response) {
                    $('#dspp-paypal_save').prop('disabled', false);
                    $('#fullpage-loader').hide();
                    if (response.success) {
                        $(".success").text(response.data);
                    } else {
                        $(".success").text(response.data);
                    }
                    location.reload();
                }
            });
        }
    });
    $('.delete-status').on('click', function (e) {
        e.preventDefault();
        var statusId = $(this).data('status-id');
        var nonce = dspp_nonces.delete_status_action;
        var ajaxUrl = dspp_nonces.ajax_url;
        console.log(statusId);
        // Show confirmation dialog
        if (confirm('Are you sure you want to delete this status?')) {
            // AJAX request to delete the status
            $.ajax({
                url: ajaxUrl,
                type: 'POST',
                data: {
                    action: 'dspp_delete_status_action',
                    nonce: nonce,
                    status_id: statusId
                },
                success: function (response) {
                    if (response.success) {
                        location.reload();
                    } else {
                        alert('Failed to delete status. Please try again.');
                    }
                },
                error: function () {
                    alert('Error during the AJAX request.');
                }
            });
        }
    });
    $('.edit-email-template').on('click', function (e) {
        e.preventDefault();
        var email_template_id = $(this).data('email-template-id');
        var nonce = dspp_nonces.get_email_temp_details_action;
        var ajaxUrl = dspp_nonces.ajax_url;
        // AJAX request to retrieve status details
        $.ajax({
            url: ajaxUrl,
            type: 'POST',
            data: {
                action: 'dspp_get_email_temp_details_action',
                nonce: nonce,
                status_id: email_template_id
            },
            success: function (response) {
                if (response.success) {
                    // Populate the edit form with retrieved data
                    $('#email_temp_subject').val(response.data.subject);
                    $('#email_temp_message').html(response.data.body);
                    $('#email_temp_id').val(email_template_id);
                    $('#edit-email-template-modal').show();
                } else {
                    alert('Failed to retrieve template details. Please try again.');
                }
            },
            error: function () {
                alert('Error during the AJAX request.');
            }
        });
    });
    $('.reset-email-template').on('click', function (e) {
        e.preventDefault();
        var nonce = dspp_nonces.reset_email_template_action;
        var ajaxUrl = dspp_nonces.ajax_url;
        var statusId = $(this).data('email-template-id');
        // Show confirmation dialog
        console.log(statusId);
        if (confirm('Are you sure you want to reset this template?')) {
            // AJAX request to delete the status
            $.ajax({
                url: ajaxUrl,
                type: 'POST',
                data: {
                    action: 'dspp_reset_email_template_action',
                    nonce: nonce,
                    status_id: statusId
                },
                success: function (response) {
                    if (response.success) {
                        location.reload();
                    } else {
                        alert('Failed to reset template. Please try again.');
                    }
                },
                error: function () {
                    alert('Error during the AJAX request.');
                }
            });
        }
    });
    $('.delete-email-template').on('click', function (e) {
        e.preventDefault();
        var nonce = dspp_nonces.delete_email_template_action;
        var ajaxUrl = dspp_nonces.ajax_url;
        var statusId = $(this).data('email-template-id');
        // Show confirmation dialog
        if (confirm('Are you sure you want to delete this status?')) {
            // AJAX request to delete the status
            $.ajax({
                url: ajaxUrl,
                type: 'POST',
                data: {
                    action: 'dspp_delete_email_template_action',
                    nonce: nonce,
                    status_id: statusId
                },
                success: function (response) {
                    if (response.success) {
                        location.reload();
                    } else {
                        alert('Failed to delete status. Please try again.');
                    }
                },
                error: function () {
                    alert('Error during the AJAX request.');
                }
            });
        }
    });
    $('#edit-email-temp-form').on('submit', function (e) {
        e.preventDefault();
        var nonce = dspp_nonces.update_email_temp_action;
        var ajaxUrl = dspp_nonces.ajax_url;
        // AJAX request to update status details
        $.ajax({
            url: ajaxUrl,
            type: 'POST',
            data: {
                action: 'dspp_update_email_temp_action',
                nonce: nonce,
                email_temp_id: $('#email_temp_id').val(),
                email_temp_subject: $('#email_temp_subject').val(),
                email_temp_message: $('#email_temp_message').html()
            },
            success: function (response) {
                if (response.success) {
                    $('#edit-email-template-modal').hide();
                    location.reload();
                } else {
                    alert('Failed to update status. Please try again.');
                }
            },
            error: function () {
                alert('Error during the AJAX request.');
            }
        });
    });
    $('.edit-status').on('click', function (e) {
        e.preventDefault();
        var statusId = $(this).data('status-id');
        var nonce = dspp_nonces.get_status_details_action;
        var ajaxUrl = dspp_nonces.ajax_url;
        // AJAX request to retrieve status details
        $.ajax({
            url: ajaxUrl,
            type: 'POST',
            data: {
                action: 'dspp_get_status_details_action',
                nonce: nonce,
                status_id: statusId
            },
            success: function (response) {
                if (response.success) {
                    // Populate the edit form with retrieved data
                    $('#edit-status-name').val(response.data.status_name);
                    $('#edit-status-description').val(response.data.status_description);
                    $('#edit-status-id').val(statusId);
                    $('#edit-status-modal').show();
                } else {
                    alert('Failed to retrieve status details. Please try again.');
                }
            },
            error: function () {
                alert('Error during the AJAX request.');
            }
        });
    });

    $('#edit-status-form').on('submit', function (e) {
        e.preventDefault();
        var nonce = dspp_nonces.edit_status_action;
        var ajaxUrl = dspp_nonces.ajax_url;
        // AJAX request to update status details
        $.ajax({
            url: ajaxUrl,
            type: 'POST',
            data: {
                action: 'dspp_edit_status_action',
                nonce: nonce,
                status_id: $('#edit-status-id').val(),
                status_name: $('#edit-status-name').val(),
                status_description: $('#edit-status-description').val(),
            },
            success: function (response) {
                if (response.success) {
                    // Close the modal or perform any other actions
                    $('#edit-status-modal').hide();
                    location.reload();
                } else {
                    alert('Failed to update status. Please try again.');
                }
            },
            error: function () {
                alert('Error during the AJAX request.');
            }
        });
    });
    $('#update-order-status-admin').on('submit', function (e) {
        e.preventDefault();

        var formData = $(this).serialize();
        var nonce = dspp_nonces.update_order_status_admin;
        var ajaxUrl = dspp_nonces.ajax_url;

        // Disable button & show loader
        $('#update-order-status-btn').prop('disabled', true);
        $('#fullpage-loader').show();

        $.ajax({
            type: 'POST',
            url: ajaxUrl,
            data: {
                action: 'dspp_update_order_status_admin',
                nonce: nonce,
                formData: formData
            },
            success: function (response) {
                let message;
                if (response.success) {
                    message = '<p class="sucess-message alert alert-success">' + response.data + '</p>';
                } else {
                    message = '<p class="error-message alert alert-danger">' + response.data + '</p>';
                }

                $("#message-box").html(message).fadeIn(1000).delay(2000).fadeOut(1000);

                // Enable button & hide loader
                $('#update-order-status-btn').prop('disabled', false);
                $('#fullpage-loader').hide();
            },
            error: function () {
                $("#message-box").html('<p class="error-message alert alert-danger">Something went wrong!</p>').fadeIn(1000).delay(2000).fadeOut(1000);

                // Enable button & hide loader even on failure
                $('#update-order-status-btn').prop('disabled', false);
                $('#fullpage-loader').hide();
            }
        });
    });
    $('#update-invoice-status-admin').on('submit', function (e) {
        e.preventDefault();
        var formData = $(this).serialize();
        var nonce = dspp_nonces.update_invoice_status_admin;
        var ajaxUrl = dspp_nonces.ajax_url;
        $('#update-invoice-status-btn').prop('disabled', true);
        $('#fullpage-loader').show();
        $.ajax({
            type: 'POST',
            url: ajaxUrl,
            data: {
                action: 'dspp_update_invoice_status_admin',
                nonce: nonce,
                formData: formData
            },
            success: function (response) {
                $('#update-invoice-status-btn').prop('disabled', false);
                $('#fullpage-loader').hide();
                if (response.success) {
                    var message = '<p class="sucess-message alert alert-success">' + response.data + '</p>';
                    $("#message-box").html(message);
                    $('#message-box').fadeIn(2000);
                    $('#message-box').delay(2000).fadeOut(2000);
                } else {
                    var message = '<p class="error-message alert alert-danger">' + response.data + '</p>';
                    $("#message-box").html(message);
                    $('#message-box').fadeIn(2000);
                    $('#message-box').delay(2000).fadeOut(2000);
                }
            }
        });
    });
    $('.delete-invoice-status').on('click', function (e) {
        e.preventDefault();
        var nonce = dspp_nonces.delete_invoice_status_action;
        var ajaxUrl = dspp_nonces.ajax_url;
        var statusId = $(this).data('status-id');
        // Show confirmation dialog
        if (confirm('Are you sure you want to delete this status?')) {
            // AJAX request to delete the status
            $.ajax({
                url: ajaxUrl,
                type: 'POST',
                data: {
                    action: 'dspp_delete_invoice_status_action',
                    nonce: nonce,
                    status_id: statusId
                },
                success: function (response) {
                    if (response.success) {
                        location.reload();
                    } else {
                        alert('Failed to delete status. Please try again.');
                    }
                },
                error: function () {
                    alert('Error during the AJAX request.');
                }
            });
        }
    });
    $('.edit-invoice-status').on('click', function (e) {
        e.preventDefault();
        var nonce = dspp_nonces.get_invoice_status_details_action;
        var ajaxUrl = dspp_nonces.ajax_url;
        var statusId = $(this).data('status-id');
        console.log(nonce);
        // AJAX request to retrieve status details
        $.ajax({
            url: ajaxUrl,
            type: 'POST',
            data: {
                action: 'dspp_get_invoice_status_details_action',
                nonce: nonce,
                status_id: statusId
            },
            success: function (response) {
                if (response.success) {
                    // Populate the edit form with retrieved data
                    $('#edit-status-name').val(response.data.status_name);
                    $('#edit-status-description').val(response.data.status_description);
                    $('#edit-status-id').val(statusId);

                    // Show the edit form
                    $('#edit-status-modal').show();
                } else {
                    alert('Failed to retrieve status details. Please try again.');
                }
            },
            error: function () {
                alert('Error during the AJAX request.');
            }
        });
    });
    $('#edit-invoice-status-form').on('submit', function (e) {
        e.preventDefault();
        var nonce = dspp_nonces.edit_invoice_status_action;
        var ajaxUrl = dspp_nonces.ajax_url;
        // AJAX request to update status details
        $.ajax({
            url: ajaxUrl,
            type: 'POST',
            data: {
                action: 'dspp_edit_invoice_status_action',
                nonce: nonce,
                status_id: $('#edit-status-id').val(),
                status_name: $('#edit-status-name').val(),
                status_description: $('#edit-status-description').val(),
            },
            success: function (response) {
                if (response.success) {
                    // Close the modal or perform any other actions
                    $('#edit-status-modal').hide();
                    location.reload();
                } else {
                    alert('Failed to update status. Please try again.');
                }
            },
            error: function () {
                alert('Error during the AJAX request.');
            }
        });
    });
    $('.add_new_invoice_form').on('submit', function (e) {
        e.preventDefault(); // Prevent default form submission

        var nonce = dspp_nonces.add_new_invoice;
        var ajaxUrl = dspp_nonces.ajax_url;
        var items = {}; // Initialize items object
        var user_id = $('.add-new-invoice-users-list').val(); // Get user ID from dropdown

        // Iterate over each invoice row to collect data
        $('#invoice-table tbody tr').each(function (index) {
            var post_id = $(this).find('.add-new-invoice-services-list').val(); // Get post ID of selected service
            var selectedService = $(this).find('.add-new-invoice-services-list option:selected').text(); // Get selected service text
            var itemName = $(this).find('input[name="item_name"]').val(); // Get custom item name
            var price = $(this).find('input[name="price"]').val(); // Get item price
            var quantity = $(this).find('input[name="item_quantity"]').val(); // Get item quantity

            // Check if either service or custom item is provided
            if (!post_id && !itemName) {
                alert("Please provide an item name or select a service.");
                return false;
            }

            // Determine the item key (use item name if custom, otherwise use the service name)
            var itemKey = itemName ? itemName : selectedService;

            // Add item to items object
            items['item_' + index] = {
                'site': itemKey,
                'price': price,
                'quantity': quantity,
                'user_id': user_id || null, // Save user_id or null if not selected
                'post_id': post_id || null // Save post_id if service is selected
            };
        });

        // Check if items object is empty
        if ($.isEmptyObject(items)) {
            alert('Please add at least one item.');
            return;
        }
        $('#add-invoice-btn').prop('disabled', true);
        $('#fullpage-loader').show();
        // Send AJAX request
        $.ajax({
            url: ajaxUrl,
            method: 'POST',
            data: {
                action: 'dspp_handle_invoice_submission',
                user_id: user_id,
                items: JSON.stringify(items), // Convert items object to JSON
                nonce: nonce
            },
            success: function (response) {
                $('#add-invoice-btn').prop('disabled', false);
                $('#fullpage-loader').hide();
                if (response.success) {
                    var redirectUrl = '?page=spp_invoices';
                    window.location.href = redirectUrl;
                } else {
                    console.log(response);
                }
            },
            error: function () {
                $('#add-invoice-btn').prop('disabled', false);
                $('#fullpage-loader').hide();
                alert('An error occurred. Please try again.');
            }
        });
    });
    $('#dspp_admin_email_settings_form').on('submit', function (e) {
        e.preventDefault(); // Prevent the form from submitting normally
        var nonce = dspp_nonces.save_email_general_settings;
        var ajaxUrl = dspp_nonces.ajax_url;
        // Collect the form data
        var formData = {
            action: 'dspp_save_admin_email_settings',
            nonce: nonce,
            from_name: $('#sender-name').val(),
            from_email: $('#from-email').val()
        };
        $('#dspp-save-email-settings').prop('disabled', true);
        $('#fullpage-loader').show();
        $.ajax({
            url: ajaxUrl,
            method: 'POST',
            data: formData,
            success: function (response) {
                $('#dspp-save-email-settings').prop('disabled', false);
                $('#fullpage-loader').hide();
                if (response.success) {
                    alert('Email settings saved successfully!');
                } else {
                    alert('Error: ' + response.data);
                }
            },
            error: function () {
                $('#dspp-save-email-settings').prop('disabled', false);
                $('#fullpage-loader').hide();
                alert('An error occurred. Please try again.');
            }
        });
    });
});
