/**
 * Stremio Services JavaScript
 * 
 * Handles client-side functionality for the Stremio services management.
 * 
 * @package Cockpit
 * @subpackage Stremio
 * @author Ian O'Neill
 * @version See version.json
 */

/**
 * Gets the CSRF token from the page
 * @returns {string} The CSRF token value
 */
function getCsrfToken() {
    return $('input[name="csrf_token"]').val();
}

// Form submission handlers
$(function () {
    // Initialize toasts with auto-hide
    $('.toast').each(function() {
        var toast = new bootstrap.Toast(this);
        toast.show();
    });
    
    // Initialize datepicker with consistent formatting
    $('#expiration').datepicker({
        autoclose: true,
        format: 'yyyy-mm-dd',
        todayHighlight: true,
        orientation: 'bottom auto',
        clearBtn: true
    });

    // Service form submission
    $("#post_service").on("submit", function (e) {
        e.preventDefault();
        var formData = new FormData(this);
        formData.append('post_service', '1');
        formData.append('csrf_token', getCsrfToken());

        const submitBtn = $(this).find('button[type="submit"]');
        const originalText = submitBtn.text();
        submitBtn.prop('disabled', true).text('Saving...');

        $.ajax({
            type: "POST",
            url: "./includes/post_stremio_services.php",
            data: formData,
            processData: false,
            contentType: false,
            success: function () {
                location.reload();
            },
            error: function (xhr, status, error) {
                console.error("Error submitting service:", error);
                submitBtn.prop('disabled', false).text(originalText);
            }
        });
    });

    // Client form submission
    $("#post_client").on("submit", function (e) {
        e.preventDefault();
        var formData = new FormData(this);
        formData.append('post_client', '1');
        formData.append('csrf_token', getCsrfToken());

        const submitBtn = $(this).find('button[type="submit"]');
        const originalText = submitBtn.text();
        submitBtn.prop('disabled', true).text('Saving...');

        $.ajax({
            type: "POST",
            url: "./includes/post_stremio_services.php",
            data: formData,
            processData: false,
            contentType: false,
            success: function () {
                location.reload();
            },
            error: function (xhr, status, error) {
                console.error("Error submitting client:", error);
                submitBtn.prop('disabled', false).text(originalText);
            }
        });
    });

    // Clear cache form submission
    $("#post_clearcache").on("submit", function (e) {
        e.preventDefault();
        var formData = new FormData(this);
        formData.append('post_clearcache', '1');
        formData.append('csrf_token', getCsrfToken());

        $.ajax({
            type: "POST",
            url: "./includes/post_stremio_services.php",
            data: formData,
            processData: false,
            contentType: false,
            success: function () {
                location.reload();
            },
            error: function (xhr, status, error) {
                console.error("Error clearing cache:", error);
            }
        });
    });

    // Generate random username button
    $('#generateUsernameBtn').on('click', function(e) {
        e.preventDefault();
        e.stopPropagation();
        const randomUsername = generateRandomString(8);
        $('#username').val(randomUsername);
    });

    // Generate random password button
    $('#generatePasswordBtn').on('click', function(e) {
        e.preventDefault();
        e.stopPropagation();
        const randomPassword = generateRandomString(8);
        $('#password').val(randomPassword);
    });

    // Copy credentials button
    $('#copyCredentialsBtn').on('click', function(e) {
        e.preventDefault();
        e.stopPropagation();
        const username = $('#username').val();
        const password = $('#password').val();
        
        if (username && password) {
            copyClientCredentials(username, password);
        } else {
            showToast('Warning', 'Please enter both username and password first', 'warning');
        }
    });
});

/**
 * Deletes a service after confirmation
 * @param {number} id The ID of the service to delete
 */
function deleteService(id) {
    if (confirm("Are you sure you want to delete this service?")) {
        $.ajax({
            type: "POST",
            url: "./includes/post_stremio_services.php",
            data: {
                delete_service: 1,
                id: id,
                csrf_token: getCsrfToken()
            },
            success: function () {
                location.reload();
            },
            error: function (xhr, status, error) {
                console.error("Error deleting service:", error);
            }
        });
    }
}

/**
 * Deletes a client after confirmation
 * @param {number} id The ID of the client to delete
 */
function deleteClient(id) {
    if (confirm("Are you sure you want to delete this client?")) {
        $.ajax({
            type: "POST",
            url: "./includes/post_stremio_services.php",
            data: {
                delete_client: 1,
                id: id,
                csrf_token: getCsrfToken()
            },
            success: function () {
                location.reload();
            },
            error: function (xhr, status, error) {
                console.error("Error deleting client:", error);
            }
        });
    }
}

/**
 * Bans a client after confirmation
 * @param {number} id The ID of the client to ban
 */
function banClient(id) {
    if (confirm("Are you sure you want to ban this client?")) {
        $.ajax({
            type: "POST",
            url: "./includes/post_stremio_services.php",
            data: {
                ban_client: 1,
                id: id,
                csrf_token: getCsrfToken()
            },
            success: function () {
                location.reload();
            },
            error: function (xhr, status, error) {
                console.error("Error banning client:", error);
            }
        });
    }
}

/**
 * Unbans a client after confirmation
 * @param {number} id The ID of the client to unban
 */
function unbanClient(id) {
    if (confirm("Are you sure you want to unban this client?")) {
        $.ajax({
            type: "POST",
            url: "./includes/post_stremio_services.php",
            data: {
                unban_client: 1,
                id: id,
                csrf_token: getCsrfToken()
            },
            success: function () {
                location.reload();
            },
            error: function (xhr, status, error) {
                console.error("Error unbanning client:", error);
            }
        });
    }
}

/**
 * Populates the service form with existing service data for editing
 * @param {string} name The name of the service
 * @param {string} url The URL of the service
 * @param {number} id The ID of the service
 */
function editService(name, url, id) {
    $("#name").val(name);
    $("#url").val(url);
    $("#name").focus();

    //update button text
    $("#post_service button[type='submit']").text("Update Service");

    // Scroll to the form
    $('html, body').animate({
        scrollTop: $("#post_service").offset().top - 100
    }, 500);
}

/**
 * Populates the client form with existing client data for editing
 * @param {string} username The username of the client
 * @param {string} password The password of the client
 * @param {string} expirey The expiration date of the client
 * @param {number} id The ID of the client
 */
function editClient(username, password, expirey, id) {
    $("#username").val(username);
    $("#password").val(password);
    $("#expiration").val(expirey);
    $("#username").focus();

    // Update button text
    $("#post_client button[type='submit']").text("Update Client");

    // Scroll to the form
    $('html, body').animate({
        scrollTop: $("#post_client").offset().top - 100
    }, 500);
}

/**
 * Generate a random alphanumeric string
 * @param {number} length - Length of the string to generate
 * @returns {string} Random string
 */
function generateRandomString(length = 8) {
    const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    let result = '';
    for (let i = 0; i < length; i++) {
        result += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    return result;
}

/**
 * Copy text to clipboard
 * @param {string} text - Text to copy
 */
function copyToClipboard(text) {
    if (navigator.clipboard && navigator.clipboard.writeText) {
        navigator.clipboard.writeText(text).then(() => {
            showToast('Success', 'Copied to clipboard!', 'success');
        }).catch(err => {
            console.error('Failed to copy: ', err);
            fallbackCopyToClipboard(text);
        });
    } else {
        fallbackCopyToClipboard(text);
    }
}

/**
 * Fallback copy method for older browsers
 * @param {string} text - Text to copy
 */
function fallbackCopyToClipboard(text) {
    const textArea = document.createElement('textarea');
    textArea.value = text;
    textArea.style.position = 'fixed';
    textArea.style.left = '-999999px';
    document.body.appendChild(textArea);
    textArea.select();
    try {
        document.execCommand('copy');
        showToast('Success', 'Copied to clipboard!', 'success');
    } catch (err) {
        console.error('Fallback copy failed: ', err);
        showToast('Error', 'Failed to copy', 'danger');
    }
    document.body.removeChild(textArea);
}

/**
 * Show toast notification
 * @param {string} title - Toast title
 * @param {string} message - Toast message
 * @param {string} type - Toast type (success, danger, warning, info)
 */
function showToast(title, message, type = 'info') {
    const container = document.querySelector('.toasts-container');
    if (!container) return;

    const iconMap = {
        success: 'fa-check-circle text-theme',
        danger: 'fa-exclamation-circle text-danger',
        warning: 'fa-exclamation-triangle text-warning',
        info: 'fa-info-circle text-info'
    };

    const toastHtml = `
        <div class="toast fade show mb-3" role="alert" aria-live="assertive" aria-atomic="true" data-bs-autohide="true" data-bs-delay="3000">
            <div class="toast-header">
                <i class="fas ${iconMap[type] || iconMap.info} me-2"></i>
                <strong class="me-auto">${title}</strong>
                <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
            </div>
            <div class="toast-body">
                ${message}
            </div>
        </div>
    `;

    container.insertAdjacentHTML('beforeend', toastHtml);

    // Auto-remove toast after delay
    setTimeout(() => {
        const toasts = container.querySelectorAll('.toast');
        if (toasts.length > 0) {
            toasts[0].remove();
        }
    }, 3500);
}

/**
 * Copy client credentials in formatted text
 * @param {string} username - Client username
 * @param {string} password - Client password
 */
function copyClientCredentials(username, password) {
    const text = `Username: ${username}\nPassword: ${password}`;
    copyToClipboard(text);
}