function editUsername() {
    swal({
        title: "Edit Username!",
        text: "Do you want to edit this username?",
        icon: "info",
        buttons: {
            cancel: "Cancel",
            confirm: "Yes"
        }
    })
    .then((willConfirm) => {
        if (willConfirm) {
            swal({
                title: "Enter New Username!",
                content: {
                    element: "input",
                    attributes: {
                        placeholder: "Type the new username",
                        type: "text",
                    },
                },
                buttons: {
                    cancel: "Cancel",
                    confirm: "Update"
                },
            })
            .then((value) => {
                if (value && value.trim().length > 0) {
                    const username = document.getElementById('username');
                    username.readOnly = false;
                    username.value = value.trim();
                    username.readOnly = true;
                } else {
                    swal("No changes made. Username cannot be empty.", {
                        icon: "warning",
                    });
                }
            });
        }
    });
}

function editKeyType() {
    const select = document.getElementById('type');
    const currentValue = select.value;

    select.innerHTML = '';

    const jsonOption = document.createElement('option');
    jsonOption.value = 'json';
    jsonOption.textContent = 'JSON';
    select.appendChild(jsonOption);

    const pdfOption = document.createElement('option');
    pdfOption.value = 'pdf';
    pdfOption.textContent = 'PDF';
    select.appendChild(pdfOption);

    if (currentValue === 'json' || currentValue === 'pdf') {
        select.value = currentValue;
    }

    select.disabled = false;

    setTimeout(() => {
        select.disabled = true;
    }, 5000);
}


function editKeyStatus() {
    const select = document.getElementById('status');
    const currentValue = select.value;
    select.innerHTML = '';

    const onOption = document.createElement('option');
    onOption.value = 'on';
    onOption.textContent = 'ON';

    const offOption = document.createElement('option');
    offOption.value = 'off';
    offOption.textContent = 'OFF';

    select.appendChild(onOption);
    select.appendChild(offOption);

    if (currentValue === 'on' || currentValue === 'off') {
        select.value = currentValue;
    }

    select.disabled = false;

    setTimeout(() => {
        select.disabled = true;
    }, 5000);
}


function editExpDate() {
    swal({
        title: "Edit Expiry Date",
        text: "Do you want to increase the expiry date?",
        icon: "info",
        buttons: {
            cancel: "Cancel",
            confirm: "Yes"
        }
    })
    .then((willConfirm) => {
        if (willConfirm) {
            swal({
                title: "Enter New Expiry Date!",
                content: {
                    element: "input",
                    attributes: {
                        placeholder: "Enter new expiry date",
                        type: "datetime-local",
                    },
                },
                buttons: {
                    cancel: "Cancel",
                    confirm: "Update"
                },
            })
            .then((value) => {
                if (value && value.trim().length > 0) {
                    const inputDate = new Date(value.trim());
                    const formattedDate = formatDate(inputDate);

                    const expDate = document.getElementById('expdate');
                    expDate.readOnly = false;
                    expDate.value = formattedDate;
                    expDate.readOnly = true;
                } else {
                    swal("No changes made. Expiry date cannot be empty.", {
                        icon: "warning",
                    });
                }
            });
        }
    });
}

function formatDate(date) {
    const pad = (n) => (n < 10 ? '0' + n : n);
    return date.getFullYear() + '-' +
           pad(date.getMonth() + 1) + '-' +
           pad(date.getDate()) + ' ' +
           pad(date.getHours()) + ':' +
           pad(date.getMinutes()) + ':' +
           pad(date.getSeconds());
}


function editLimit() {
    swal({
        title: "Edit Key Limit",
        text: "Do you want to increase the key limit?",
        icon: "info",
        buttons: {
            cancel: "Cancel",
            confirm: "Yes"
        }
    })
    .then((willConfirm) => {
        if (willConfirm) {
            swal({
                title: "Enter New Key Limit",
                text: "Enter a numeric value or choose 'UNLIMITED'.",
                content: {
                    element: "input",
                    attributes: {
                        placeholder: "Enter new key limit",
                        type: "number",
                        min: "1",
                        max: "99999999"
                    },
                },
                buttons: {
                    UNLIMITED: "UNLIMITED",
                    confirm: "Update"
                },
            })
            .then((value) => {
                const limit = document.getElementById('limit');

                if (value === "UNLIMITED") {
                    limit.readOnly = false;
                    limit.value = value.toUpperCase();
                    limit.readOnly = true;
                } else if (value && value.trim().length > 0) {
                    limit.readOnly = false;
                    limit.value = value.trim();
                    limit.readOnly = true;
                } else {
                    swal("No changes made. Please enter a valid value.", {
                        icon: "warning",
                    });
                }
            })
            .catch((error) => {
                console.error("Error: ", error);
                swal("An error occurred while updating the key limit.", {
                    icon: "error",
                });
            });
        }
    });
}


function balance() {
    swal("Attention!", "You don't need to edit the balance. To increase the balance, simply edit the limit. The balance will update automatically.", "info");
}

function key() {
    swal("Attention!", "You can't edit api key! its a primary details of user.", "info");
}

function creDate() {
    swal("Attention!", "You can't edit api key create date!", "info");
}

function used() {
    swal("Attention!", "You can't edit users used record!", "info");
}



// UPDATE & DELETE BUTTON //#

//Delete button
document.getElementById('dltKeyBtn').addEventListener('click', function() {
    const apiKey = document.getElementById('apikey').value;
    if (apiKey) {
        swal({
            title: "Are you sure?",
            text: "You won't be able to recover this API key!",
            icon: "warning",
            buttons: {
                cancel: "Cancel",
                confirm: "Delete"
            },
            dangerMode: true,
        })
        .then((willDelete) => {
            if (willDelete) {
                // Send DELETE request to PHP
                fetch('delete-key.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        apiKey: apiKey
                    })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        swal("Poof! The key has been deleted!", {
                            icon: "success",
                        });
                        document.getElementById('userDetailsModal').style.display = 'none';
                        window.location.reload(true);
                    } else {
                        swal("Something went wrong. Please try again.", {
                            icon: "error",
                        });
                    }
                })
                .catch((error) => {
                    console.error("Error:", error);
                    swal("An error occurred while deleting the key.", {
                        icon: "error",
                    });
                });
            }
        });
    }
});


//UPDATE button

document.getElementById('updtKeyBtn').addEventListener('click', function () {
    const apiKey = document.getElementById('apikey').value.trim();
    const username = document.getElementById('username').value.trim();
    const keyType = document.getElementById('type').value.trim();
    const keyStatus = document.getElementById('status').value.trim();
    const expDate = document.getElementById('expdate').value.trim();
    const limit = document.getElementById('limit').value.trim();

    if (!apiKey || !username || !keyType || !keyStatus || !expDate || !limit) {
        swal("Warning!", "Please fill in all the fields before updating.", {
            icon: "warning",
        });
        return;
    }

    const data = {
        apiKey,
        username,
        type: keyType,
        status: keyStatus,
        expDate,
        limit
    };

    fetch('update-key.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(data),
    })
        .then(response => {
            if (response.ok) {
                return response.json();
            }
            return Promise.reject(`HTTP error! status: ${response.status}`);
        })
        .then(data => {
            if (data.success) {
                swal("Success!", "API key details have been updated.", {
                    icon: "success",
                }).then(() => {
                    const modal = document.getElementById('userDetailsModal');
                    if (modal) {
                        modal.style.display = 'none';
                    }
                    window.location.reload(true);
                });
            } else {
                swal("Error!", data.message || "There was an issue updating the key. Please try again.", {
                    icon: "error",
                });
            }
        })
        .catch(error => {
            swal("Error!", "An unexpected error occurred while updating the key.", {
                icon: "error",
                text: error,
            });
        });
});