
/*******************************************************************************************/
/* scripts-admin.js */

document.addEventListener('DOMContentLoaded', () => {
    const hamburger = document.getElementById('hamburger-menu');
    const menu = document.getElementById('menu');
    const myAccount = document.getElementById('my-account');
    const myAccountMenu = document.getElementById('my-account-menu');
    const toggleSidebar = document.getElementById('toggle-sidebar');
    const sidebar = document.getElementById('sidebar');
    const content = document.querySelector('.mainContentSection');
    const themeToggle = document.getElementById('theme-toggle');
    const html = document.documentElement;
    
    function setCookie(name, value, days) {
        let expires = "";
        if (days) {
            const date = new Date();
            date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
            expires = "; expires=" + date.toUTCString();
        }
        document.cookie = name + "=" + (value || "") + expires + "; path=/";
    }

    function getCookie(name) {
        const nameEQ = name + "=";
        const ca = document.cookie.split(';');
        for(let i = 0; i < ca.length; i++) {
            let c = ca[i];
            while (c.charAt(0) === ' ') c = c.substring(1, c.length);
            if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
        }
        return null;
    }
	
	function toggleMenu(menuElement) {
        if (menuElement) {
            menuElement.style.display = menuElement.style.display === 'block' ? 'none' : 'block';
        }
    }

    hamburger.addEventListener('click', (e) => {
        e.stopPropagation();
        hamburger.classList.toggle('change');
        toggleMenu(menu);
        if (myAccountMenu) myAccountMenu.style.display = 'none';
    });

    myAccount.addEventListener('click', (e) => {
        e.stopPropagation();
        toggleMenu(myAccountMenu);
        if (menu) menu.style.display = 'none';
    });
	
	

	// Sidebar toggle
	toggleSidebar.addEventListener('click', () => {
		sidebar.classList.toggle('collapsed');
		content.classList.toggle('sidebar-collapsed');
		document.body.classList.toggle('sidebar-collapsed');
		setCookie('sidebar', sidebar.classList.contains('collapsed') ? 'collapsed' : 'expanded', 30);
	});

	// Theme toggle
	themeToggle.addEventListener('click', () => {
		html.classList.toggle('light-theme');
		const icon = themeToggle.querySelector('i');
		const text = themeToggle.querySelector('span');
		
		if (html.classList.contains('light-theme')) {
			icon.classList.replace('fa-moon', 'fa-sun');
			text.textContent = 'Theme: Light';
			setCookie('theme', 'light', 30);
		} else {
			icon.classList.replace('fa-sun', 'fa-moon');
			text.textContent = 'Theme: Dark';
			setCookie('theme', 'dark', 30);
		}
	});
	
    // Close menus when clicking outside
    document.addEventListener('click', (event) => {
        if (!hamburger.contains(event.target) && !menu.contains(event.target)) {
            menu.style.display = 'none';
            hamburger.classList.remove('change');
        }
        if (!myAccount.contains(event.target) && !myAccountMenu.contains(event.target)) {
            myAccountMenu.style.display = 'none';
        }
    });

	/* save cookies for user toggles */
	const savedTheme = getCookie('theme');
	if (savedTheme === 'light') {
		html.classList.add('light-theme');
		themeToggle.querySelector('i').classList.replace('fa-moon', 'fa-sun');
		themeToggle.querySelector('span').textContent = 'Dark Mode';
	}

	const savedSidebar = getCookie('sidebar');
	if (savedSidebar === 'collapsed') {
		sidebar.classList.add('collapsed');
		content.classList.add('sidebar-collapsed');
		document.body.classList.add('sidebar-collapsed');
	}

	/* profile picture change */
    const modal = document.getElementById('profilePictureModal');
    const changeProfilePictureTriggers = document.querySelectorAll('.change-profile-picture, #changeProfilePicture');
    const closeButton = modal.querySelector('.close');
    const form = document.getElementById('profilePictureForm');
    const uploadStatus = document.getElementById('uploadStatus');
    const removeProfilePictureButton = document.getElementById('removeProfilePicture');

    changeProfilePictureTriggers.forEach(trigger => {
        trigger.addEventListener('click', openModal);
    });

    closeButton.addEventListener('click', closeModal);

    window.addEventListener('click', function(event) {
        if (event.target == modal) {
            closeModal();
        }
    });

/* profile admin */
$(document).ready(function() {
    $('#profilePictureForm').on('submit', function(e) {
        e.preventDefault();
        var formData = new FormData(this);
        
        $.ajax({
            url: '/admin/inc/upload_profile_picture_admin.php',
            type: 'POST',
            data: formData,
            contentType: false,
            processData: false,
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    $('.profile-picture-container').html('<img src="' + response.newImageUrl + '" alt="Profile Picture" class="profile-picture">');
                    $('#removeProfilePicture').show();
                    $('#uploadStatus').text(response.message);
                    $('#profilePictureModal').hide();
                } else {
                    $('#uploadStatus').text(response.message);
                }
            },
            error: function(xhr, status, error) {
                console.error('Upload error:', status, error);
                $('#uploadStatus').text('An error occurred. Please try again.');
            }
        });
    });
});

	// Function to remove the profile picture
	function removeProfilePicture(event) {
		event.preventDefault();
		event.stopPropagation();  // Add this line to stop event propagation
		
		if (confirm('Are you sure you want to remove your profile picture?')) {
			fetch('/includes/remove_profile_picture.php', {
				method: 'POST',
				headers: {
					'Content-Type': 'application/json',
				},
			})
			.then(response => {
				if (!response.ok) {
					throw new Error('Network response was not ok');
				}
				return response.json();
			})
			.then(data => {
				if (data.success) {
					alert(data.message);
					location.reload();
				} else {
					alert('Error: ' + data.message);
				}
			})
			.catch(error => {
				// console.error('Error:', error);
				// alert('An error occurred. Please try again.');
			});
		}
	}


	function updateProfilePicture(newImageUrl) {
		const profilePictureContainers = document.querySelectorAll('.profile-picture-container, .user-settings img');
		profilePictureContainers.forEach(container => {
			if (container.tagName.toLowerCase() === 'img') {
				container.src = newImageUrl;
			} else {
				container.innerHTML = `<img src="${newImageUrl}" alt="Profile Picture" class="profile-picture">`;
			}
		});

		// Toggle visibility of remove button
		if (removeProfilePictureButton) {
			removeProfilePictureButton.style.display = newImageUrl ? 'block' : 'none';
		}
	}
	
    function openModal() {
        modal.style.display = 'block';
    }

    function closeModal() {
		modal.style.display = 'none';
		form.reset();
		if (uploadStatus) {
			uploadStatus.textContent = '';
		}
	}
	
	if (removeProfilePictureButton) {
        removeProfilePictureButton.addEventListener('click', removeProfilePicture);
    }

	// debugging cookies
	// console.log('Settings Page Loaded');
	// console.log('Saved Sidebar State:', getCookie('sidebar'));
	// console.log('Saved Theme State:', getCookie('theme'));
	// console.log('Saved Layout State:', savedLayout);
	
});

// Ensure this event listener is added after the DOM is fully loaded
document.addEventListener('DOMContentLoaded', function() {
    const removeButton = document.getElementById('removeProfilePicture');
    if (removeButton) {
        removeButton.addEventListener('click', removeProfilePicture);
    }
});

// confirm delete (from header)
function confirmDeleteGeneric() { 
	var retval=confirm("You are about to delete this group\nall the members of this group\nand all the cases of the users.\n\nAre You Sure?");
	return retval;
}
function sort() {
	return false;
}

/***************************************************************************************************/

/* fix the second div to the top as scroll down */
window.addEventListener('scroll', function() {
    const scrollingDiv = document.getElementById('menu-wrap');
    const originalOffset = 65; // Original offset from the top
    const scrollPosition = window.scrollY;

    // Check if the scroll position has reached the original offset
    if (scrollPosition >= originalOffset) {
        scrollingDiv.style.position = 'fixed';
        scrollingDiv.style.top = '0'; // Fix to the top
    } else {
        scrollingDiv.style.position = 'relative';
        scrollingDiv.style.top = ''; // Reset top position
    }
});

// for date formatting
function formatDate(dateString) {
	const options = { year: 'numeric', month: 'long', day: 'numeric' };
	return new Date(dateString).toLocaleDateString('en-US', options);
}


/* make sure all modals can close */
$(document).ready(function() {
    var modal = document.getElementById("editGroupModal");
    var span = document.getElementsByClassName("close")[0];
    var isSuper = $('body').hasClass('super-admin');

    span.onclick = function() {
        modal.style.display = "none";
    }

    $('.close').on('click', function() {
        modal.style.display = "none";
    });

    window.onclick = function(event) {
        if (event.target == modal) {
            modal.style.display = "none";
        }
    }

});

// Close modal when clicking outside
window.onclick = function(event) {
    if (event.target.classList.contains('modal')) {
        event.target.style.display = 'none';
    }
}

$(document).on('click', function(event) {
    if ($(event.target).hasClass('modal')) {
        $('.modal').hide();
    }
});

// Close button functionality
document.querySelectorAll('.close').forEach(function(closeButton) {
    closeButton.onclick = function() {
        this.closest('.modal').style.display = 'none';
    }
});

// toggle visibility
$(document).ready(function() {
    // Toggle switch handler
	$('#showHiddenToggle').on('change', function() {
        const currentUrl = new URL(window.location.href);
        currentUrl.searchParams.set('show_hidden', this.checked ? '1' : '0');
        window.location.href = currentUrl.toString();
    });

    // Handle visibility toggle buttons
    $('.visibility-toggle-btn').on('click', function(e) {
        e.preventDefault();
        const btn = $(this);
        const id = btn.data('id');
        const type = btn.data('type');
        const currentStatus = btn.data('status');
        const newStatus = currentStatus === 'visible' ? 'hidden' : 'visible';

        console.log('Button clicked');
        console.log('ID:', id);
        console.log('Type:', type);
        console.log('Current Status:', currentStatus);
        console.log('New Status:', newStatus);
		
        // Set URL based on type
        let url;
        switch(type) {
            case 'user':
                url = 'users.php';
                break;
            case 'group':
                url = 'groups.php';
                break;
            case 'case':
                url = 'cases.php';
                break;
            default:
                // console.error('Invalid type:', type);
                // alert('Error: Invalid type specified');
                return;
        }

        $.ajax({
            url: url,
            method: 'POST',
            data: {
                action: 'toggle_visibility',
                id: id,
                type: type,
                status: newStatus
            },
            success: function(response) {
                let data = response;
                if (typeof response === 'string') {
                    try {
                        data = JSON.parse(response);
                    } catch (e) {
                        // console.error('Failed to parse response:', e);
                        // alert('Error updating visibility: Invalid server response');
                        return;
                    }
                }
                
                if (data.success) {
                    btn.text(newStatus === 'visible' ? 'Hide' : 'Show');
                    btn.data('status', newStatus);
                    location.reload();
                } else {
                    // alert('Error updating visibility: ' + (data.error || 'Unknown error'));
                }
            },
            error: function(xhr, status, error) {
                // console.error('AJAX error:', status, error, xhr.responseText);
                // alert('Error updating visibility: Server error occurred');
            }
        });
    });
});

/* email text overflow functions */

document.querySelectorAll('.inner-text').forEach(element => {
    element.setAttribute('data-text', element.textContent);
    
    if (element.scrollWidth > element.offsetWidth) {
        element.classList.add('overflow');
    } else {
        element.classList.remove('overflow');
    }
});

window.addEventListener('resize', () => {
    document.querySelectorAll('.inner-text').forEach(element => {
        if (element.scrollWidth > element.offsetWidth) {
            element.classList.add('overflow');
        } else {
            element.classList.remove('overflow');
        }
    });
});

// copy email icons

document.querySelectorAll('.copy-icon').forEach(icon => {
    icon.addEventListener('click', function() {
        let email;
        
        // For the main menu version
        if (this.closest('.just-info')) {
            email = this.previousElementSibling.querySelector('.inner-text').textContent;
        }
        // For the menu-items-left version
        else if (this.closest('.menu-items-left-email')) {
            email = this.previousElementSibling.querySelector('.inner-text').textContent;
        }
        
        if (email) {
            navigator.clipboard.writeText(email.trim()).then(() => {
                // Visual feedback
                this.classList.remove('fa-copy');
                this.classList.add('fa-check');
                
                setTimeout(() => {
                    this.classList.remove('fa-check');
                    this.classList.add('fa-copy');
                }, 1000);
            });
        }
    });
});

/* hide copy icon when no overflow */

document.addEventListener('DOMContentLoaded', () => {
	document.querySelectorAll('.copy-icon').forEach(icon => {
		if (icon.closest('.menu-items-left-email')) {
			const textEl = icon.previousElementSibling.querySelector('.inner-text');
			if (textEl.scrollWidth <= textEl.offsetWidth) {
				icon.style.display = 'none';
			} else {
				icon.style.display = 'inline-block';
			}
		}
	});
});
window.addEventListener('load', () => {
    document.querySelectorAll('.copy-icon').forEach(icon => {
        const textEl = icon.previousElementSibling.querySelector('.inner-text');
        if (textEl.scrollWidth <= textEl.offsetWidth) {
            icon.style.display = 'none';
        } else {
            icon.style.removeProperty('display');
        }
    });
});

async function getAdminContent() {
    try {
        const response = await fetch('../app/modal_data/modal-content.json');
        const data = await response.json();
        return data;
    } catch (error) {
        console.error('Failed to load modal content:', error);
        return {
            proModal: {
                statusText: {
                    "Pro": "Pro Active",
                    "Renew": "Pro Active, Expiring Soon", 
                    "Expired": "Pro Expired",
                    "Upgrade": "Upgrade to Pro",
                    "Super": "You Are Super Admin",
                    "No": "Upgrade to Pro"
                }
            },
            adminProModal: {
                features: {
                    "Pro": ["Advanced analytics", "Custom branding", "API access", "Priority phone support"],
                    "Renew": ["Advanced analytics", "Custom branding", "API access", "Priority phone support", "Renew now to keep Pro benefits"],
                    "Expired": ["Basic features only", "Upgrade to regain Pro features", "Limited analytics"],
                    "Upgrade": ["Unlock advanced analytics", "Enable custom branding", "Get API access", "Receive priority support"],
                    "Super": ["You are the super admin and already have unlimited everything!"]
                }
            },
            licenseModal: {
                features: {
                    "Active": ["Full access to all basic features", "Priority email support", "Regular updates"],
                    "Renew": ["Full access to all basic features", "Priority email support", "Regular updates", "Renew now to avoid service interruption"],
                    "Expired": ["Group editing is disabled", "Users can be viewed but not edited", "No access to saved cases", "Data may be deleted after 30 days", "Cases in the app cannot be run until license is active"],
                    "Inactive": ["Group editing is disabled", "Users can be viewed but not edited", "No access to saved cases", "Data may be deleted after 30 days", "Cases in the app cannot be run until license is active"],
                    "Super": ["You are Sasdsadsadasds to all features!"]
                }
            }
        };
    }
}

async function showLicenseModal(status, expirationDate) {
    console.log('License Modal Called:', {status, expirationDate});
    const content = await getAdminContent();
    const modal = document.getElementById('licenseModal');
    const statusEl = document.getElementById('licenseStatus');
    const expirationEl = document.getElementById('licenseExpiration');
    const featuresEl = document.getElementById('licenseFeatures');
    const actionEl = document.getElementById('licenseAction');

    const statusIcons = {
        'Active': '<i class="fas fa-check-circle"></i>',
        'Renew': '<i class="fas fa-exclamation-circle"></i>',
        'Expired': '<i class="fas fa-times-circle"></i>',
        'Inactive': '<i class="fas fa-ban"></i>',
        'Super': '<i class="fas fa-crown"></i>'
    };

    const statusText = {
        'Active': 'Active Subscription',
        'Renew': 'Active, Expiring Soon',
        'Expired': 'Expired',
        'Inactive': 'Inactive License',
        'Super': 'You Are Super Admin' 
    };

    const actionText = {
        'Active': 'Extend Subscription',
        'Renew': 'Renew Subscription',
        'Expired': 'Renew Subscription',
        'Inactive': 'Reactivate Subscription',
        'Super': 'Already Super Admin!'
    };

    statusEl.innerHTML = `${statusIcons[status]} ${statusText[status]}`;
    statusEl.className = 'status-button ' + status.toLowerCase();
    expirationEl.textContent = 'Expiration Date: ' + expirationDate;
    featuresEl.innerHTML = content.licenseModal.features[status].map(feature => `<li>${feature}</li>`).join('');

    actionEl.textContent = actionText[status];
    actionEl.href = licenseUrls[status];
    actionEl.target = '_blank';

    modal.style.display = 'block';
}

async function showProModal(status, expirationDate) {
    console.log('Pro Modal Called:', {status, expirationDate});
    const content = await getAdminContent();
    const modal = document.getElementById('proStatusModal');
    const statusEl = document.getElementById('proStatus');
    const expirationEl = document.getElementById('proExpiration');
    const featuresEl = document.getElementById('proFeatures');
    const actionEl = document.getElementById('proAction');
    
    const statusIcons = {
        'Pro': '<i class="fas fa-check-circle"></i>',
        'Renew': '<i class="fas fa-exclamation-circle"></i>',
        'Expired': '<i class="fas fa-times-circle"></i>',
        'Upgrade': '<i class="fas fa-rocket"></i>',
        'Super': '<i class="fas fa-crown"></i>'
    };

    statusEl.innerHTML = `${statusIcons[status]} ${content.proModal.statusText[status]}`;
    statusEl.className = 'status-button ' + status.toLowerCase();

    if (status === 'Upgrade' || status === 'Super' || expirationDate === 'Never') {
        expirationEl.style.display = 'none';
    } else {
        expirationEl.style.display = 'block';
        expirationEl.textContent = 'Expiration Date: ' + expirationDate;
    }

    featuresEl.innerHTML = content.adminProModal.features[status].map(feature => `<li>${feature}</li>`).join('');

    const buttonText = {
        'Pro': 'Pro Active',
        'Renew': 'Renew Pro',
        'Expired': 'Renew Pro',
        'Upgrade': 'Get Pro',
        'Super': 'Pro Active'
    };

    actionEl.textContent = buttonText[status];
    actionEl.href = proStatusUrls[status];
    actionEl.target = '_blank';

    modal.style.display = 'block';
}

const statusButtonText = {
    license: {
        'Active': 'Active',
        'Renew': 'Renew',
        'Expired': 'Expired',
        'Inactive': 'Inactive'
    },
    pro: {
        'Pro': 'Pro',
        'Renew': 'Renew Pro',
        'Expired': 'Expired Pro',
        'Upgrade': 'Get Pro'
    }
};

const licenseUrls = {
    'Active': mainUrl + '/upgrade',
    'Renew': mainUrl + '/upgrade',
    'Expired': mainUrl + '/upgrade',
    'Inactive': mainUrl + '/upgrade',
    'Super': '#'
};

const proStatusUrls = {
    'Pro': mainUrl + '/pro-upgrade',
    'Renew': mainUrl + '/pro-upgrade',
    'Expired': mainUrl + '/pro-upgrade',
    'Upgrade': mainUrl + '/pro-upgrade',
    'Super': '#'
};