(function($) { 'use strict'; // Dashboard module configuration let dashboardConfig = { ajaxurl: '', nonce: '', currentUserId: 0, layoutType: 'host' }; // Wait for dashboardVars to be available function initDashboardConfig() { if (window.dashboardVars) { dashboardConfig.ajaxurl = window.dashboardVars.ajaxurl; dashboardConfig.nonce = window.dashboardVars.nonce; dashboardConfig.currentUserId = window.dashboardVars.currentUserId; dashboardConfig.layoutType = window.dashboardVars.layoutType || 'host'; //console.log('Dashboard variables loaded via wp_localize_script'); } else { // Fallback to WordPress default ajaxurl dashboardConfig.ajaxurl = typeof ajaxurl !== 'undefined' ? ajaxurl : '/wp-admin/admin-ajax.php'; // Try to get nonce from inline script or meta tag let nonceElement = document.querySelector('meta[name="dashboard-nonce"]'); if (nonceElement) { dashboardConfig.nonce = nonceElement.getAttribute('content'); } // Get current user ID from body class let bodyClasses = document.body.className.split(' '); bodyClasses.forEach(className => { if (className.includes('user-id-')) { dashboardConfig.currentUserId = parseInt(className.replace('user-id-', '')); } }); //console.log('Dashboard variables loaded via fallbacks'); } // Debug log //if (console && typeof console.log === 'function') { //console.log('Dashboard config initialized:', { //ajaxurl: dashboardConfig.ajaxurl ? 'Set' : 'Not set', //nonce: dashboardConfig.nonce ? 'Set' : 'Not set', //currentUserId: dashboardConfig.currentUserId, //layoutType: dashboardConfig.layoutType //}); //} } let dashboardInitialized = false; let scrollDetectionInitialized = false; // Function to make real API call function makeApiCall(endpoint, cardType, fields, layoutType) { return new Promise(function(resolve, reject) { if (!dashboardConfig.ajaxurl) { initDashboardConfig(); } if (!dashboardConfig.ajaxurl) { //console.error('ERROR: ajaxurl is not defined!'); reject('ajaxurl is not defined'); return; } if (!endpoint || endpoint.trim() === '' || endpoint === 'mock') { $.ajax({ url: dashboardConfig.ajaxurl, type: 'POST', dataType: 'json', data: { action: 'dashboard_api_request', endpoint: endpoint, card_type: cardType, fields: fields, layout_type: layoutType || dashboardConfig.layoutType, nonce: dashboardConfig.nonce }, success: function(response) { if (response.success) { resolve(response.data); } else { reject(response.data || response.message || 'API request failed'); } }, error: function(xhr, status, error) { //console.error('AJAX error:', error); reject('AJAX error: ' + error); } }); } else { // External API call $.ajax({ url: endpoint, type: 'GET', dataType: 'json', data: { user_id: dashboardConfig.currentUserId || 0, fields: fields, layout_type: layoutType || dashboardConfig.layoutType }, success: function(data) { resolve(data); }, error: function(xhr, status, error) { //console.error('External API error:', error); reject('API error: ' + error); } }); } }); } // Function to fetch and display API data function fetchApiData(cardElement) { var apiConfig = cardElement.find('.api-config'); var apiLoading = cardElement.find('.api-loading'); var apiError = cardElement.find('.api-error'); var apiContent = cardElement.find('.api-content'); if(apiConfig.length) { var endpoint = apiConfig.data('endpoint'); var fields = apiConfig.data('fields'); var type = apiConfig.data('type'); var layoutType = ''; // Get layout type from wrapper class var wrapper = cardElement.closest('.dashboard-grid-wrapper'); if (wrapper.length) { layoutType = wrapper.attr('class')?.includes('rep') ? 'rep' : 'host'; } else { layoutType = dashboardConfig.layoutType || 'host'; } if(endpoint || true) { apiLoading.show(); apiError.hide(); apiContent.hide(); // Make API call makeApiCall(endpoint, type, fields, layoutType) .then(function(data) { // Display the data var html = processApiData(type, data, layoutType); apiLoading.hide(); apiContent.html(html).show(); // Update scroll detection updateScrollableCards(); }) .catch(function(error) { //console.error('API Error:', error); apiLoading.hide(); apiError.text('Error: ' + error).show(); // Fallback to mock data for testing var mockHtml = getMockData(type, layoutType); apiContent.html(mockHtml).show(); updateScrollableCards(); }); } else { apiLoading.hide(); apiError.text('No API endpoint configured').show(); } } } // TEST - Function to process real API data - https://jsonplaceholder.typicode.com/users function processApiData(type, data, layoutType) { switch(type) { case 'profile': if (Array.isArray(data)) { return processUsersArray(data, layoutType); } else { // original format return processSingleUser(data, layoutType); } case 'upcoming': if (Array.isArray(data)) { return processUpcomingArray(data, layoutType); } else { return processUpcomingSingle(data, layoutType); } case 'tools': var html = ''; if (data.badge_text && data.badge_text.trim()) { html += '' + data.badge_text + ''; } if (data.title && data.title.trim()) { html += '

' + data.title + '

'; } if (data.items && data.items.length > 0) { html += ''; } else { html += '

No resource items available.

'; } return html; case 'featured': var html = ''; if (data.badge_text && data.badge_text.trim()) { html += '' + data.badge_text + ''; } if (data.title && data.title.trim()) { html += '

' + data.title + '

'; } if (data.posts && data.posts.length > 0) { html += ''; // Close featured-posts } else { html += '

No featured posts available.

'; } return html; case 'incentive': var html = ''; if (data.title && data.title.trim()) { html += '

' + data.title + '

'; } if (data.items && data.items.length > 0) { html += '
'; data.items.forEach(function(item) { if (item && item.item_text && item.item_value) { html += '
'; html += '
' + item.item_text + '
'; html += '
' + item.item_value + '
'; html += '
'; } }); html += '
'; } return html; default: return '

API data for ' + type + ' card type.

'; } } // NEW TEST FUNCTION: Process array of users from JSONPlaceholder function processUsersArray(users, layoutType) { if (!Array.isArray(users) || users.length === 0) { return '

No user data available.

'; } var badgeClass = (layoutType === 'rep') ? 'profile-badge-rep' : 'profile-badge-host'; var badgeText = (layoutType === 'rep') ? 'Area Rep' : 'Host Family'; var html = '
'; html += '
'; // Show first user as main profile var mainUser = users[0]; // Left Column: User Image html += '
'; html += '
'; html += '' + getInitials(mainUser.name) + ''; html += '
'; html += '
'; // Right Column: User Info html += '
'; html += ''; html += badgeText + ' (API)'; html += ''; if (mainUser.name && mainUser.name.trim()) { html += '

' + mainUser.name + '

'; } if (mainUser.email && mainUser.email.trim()) { html += '
'; html += '
'; html += ''; html += ''; html += ''; html += '
'; html += ''; html += mainUser.email; html += ''; html += '
'; html += '
'; html += '
'; } html += '
'; // Close profile-info-column html += '
'; // Close profile-layout html += '
'; // Close profile-header // Separator Line html += '
'; // Showing total users html += '
'; html += '

Data from JSONPlaceholder API

'; html += '

Showing ' + users.length + ' users from external API:

'; html += '
'; // Show all users html += '
'; html += '
'; html += ''; html += ''; html += ''; html += '
'; html += 'All Users (' + users.length + ' total)'; html += '
'; html += '
'; // List each user users.forEach(function(user, index) { html += '
'; html += '
'; // User number and name html += ''; html += '' + (index + 1) + '. ' + user.name; html += ''; // User details html += '
'; html += '
Email: ' + user.email + '
'; if (user.phone) { html += '
Phone: ' + user.phone + '
'; } if (user.company && user.company.name) { html += '
Company: ' + user.company.name + '
'; } html += '
'; html += '
'; html += '
'; }); html += '
'; // Close contact-list return html; } // ORIGINAL FUNCTION: Process single user function processSingleUser(data, layoutType) { var html = '
'; html += '
'; // Left Column: User Image html += '
'; if (data.user_avatar && data.user_avatar.trim() !== '') { html += '
'; html += '' + (data.user_name || data.display_name || 'User') + ''; html += '
'; } else { html += '
'; html += '' + (data.initials || 'JD') + ''; html += '
'; } html += '
'; // Right Column: User Info html += '
'; html += ''; html += data.badge_text || 'Host Family'; html += ''; if (data.user_name && data.user_name.trim()) { html += '

' + data.user_name + '

'; } else if (data.display_name && data.display_name.trim()) { html += '

' + data.display_name + '

'; } if (data.user_email && data.user_email.trim()) { html += '
'; html += '
'; html += ''; html += ''; html += ''; html += ''; html += '
'; html += '
'; } html += '
'; // Close profile-info-column html += '
'; // Close profile-layout html += '
'; // Close profile-header // Separator Line html += '
'; // Description if (data.profile_description && data.profile_description.trim()) { html += '
'; html += '

' + data.profile_description + '

'; html += '
'; } // Contact Items if (data.contacts && data.contacts.length > 0) { html += '
'; data.contacts.forEach(function(contact) { if (contact && contact.value && contact.value.trim()) { html += '
'; if (contact.icon && contact.icon.trim()) { html += ''; html += ''; html += ''; } html += '
'; if (contact.label && contact.label.trim()) { html += '' + contact.label + ''; } if (contact.value && contact.value.trim()) { if (contact.is_phone || contact.type === 'phone') { html += '' + contact.value + ''; } else { html += '' + contact.value + ''; } } html += '
'; html += '
'; } }); html += '
'; } return html; } // NEW TEST FUNCTION: Process array for upcoming students function processUpcomingArray(users, layoutType) { if (!Array.isArray(users) || users.length === 0) { return '

No student data available.

'; } // Take first 5 users as "upcoming students" var upcomingUsers = users.slice(0, 5); var html = ''; html += 'Upcoming Students (API)'; html += '

' + upcomingUsers.length + ' Upcoming Students

'; html += '
'; html += '

Data loaded from JSONPlaceholder API. Showing ' + upcomingUsers.length + ' upcoming students:

'; // Use tools-list style for consistency html += ''; html += '
'; // Close card-description // Add a button to view all html += '
'; html += ''; html += 'View All API Users'; html += ''; html += '
'; return html; } // ORIGINAL FUNCTION: Process single upcoming data function processUpcomingSingle(data, layoutType) { var html = ''; if (data.badge_text && data.badge_text.trim()) { html += '' + data.badge_text + ''; } if (data.title && data.title.trim()) { html += '

' + data.title + '

'; } if (data.description && data.description.trim()) { html += '
'; html += '

' + data.description + '

'; if (data.students && data.students.length > 0) { html += ''; } html += '
'; } if (data.button_text && data.button_text.trim() && data.button_link && data.button_link.trim()) { html += '
'; html += ''; html += data.button_text; html += ''; html += '
'; } return html; } // Helper function to get initials from name function getInitials(name) { if (!name) return 'JD'; var parts = name.split(' '); if (parts.length >= 2) { return (parts[0].charAt(0) + parts[1].charAt(0)).toUpperCase(); } else if (parts.length === 1) { return (parts[0].charAt(0) + parts[0].charAt(1)).toUpperCase(); } return 'JD'; } // Function to generate mock data with function getMockData(type, layoutType) { // Same processApiData function with mock data var mockData = {}; var badgeClass = (layoutType === 'rep') ? 'profile-badge-rep' : 'profile-badge-host'; var badgeText = (layoutType === 'rep') ? 'Area Rep' : 'Host Family'; switch(type) { case 'profile': mockData = { badge_class: badgeClass, badge_text: badgeText, user_name: 'John Doe (API Mock)', display_name: 'John Doe', user_email: 'john.doe@example.com', initials: 'JD', profile_description: 'This is API mock profile data for testing purposes.', contacts: [ { label: 'Area Rep', value: 'rep@example.com', icon: 'dashicons-admin-users', type: 'email', is_phone: false }, { label: 'Emergency Hotline', value: '123-456-7890', icon: 'dashicons-phone', type: 'phone', is_phone: true } ] }; return processApiData('profile', mockData, layoutType); case 'upcoming': mockData = { badge_text: 'Upcoming', title: 'Upcoming Students (Mock)', description: 'Showing 3 upcoming students from mock API data.', button_text: 'View All Students', button_link: '#', students: [ {name: 'Maria Garcia', arrival: 'Aug 15'}, {name: 'Chen Wei', arrival: 'Sep 1'}, {name: 'Sarah Johnson', arrival: 'Sep 10'} ] }; return processApiData('upcoming', mockData, layoutType); case 'tools': mockData = { badge_text: 'Resources', title: 'Tools / Resources (Mock)', items: [ { title: 'Pre-Arrival Checklist', permalink: '#', bullet: true, arrow: true }, { title: 'Monthly Reports', permalink: '#', bullet: true, arrow: true }, { title: 'Resource Library', permalink: '#', bullet: true, arrow: true } ] }; return processApiData('tools', mockData, layoutType); case 'featured': mockData = { badge_text: 'Featured', title: 'Featured Insights (Mock)', posts: [ { title: 'ISE Student Wins Local Award', permalink: '#', category_name: 'Schools', featured_image: '' }, { title: 'Host Family Appreciation Month', permalink: '#', category_name: 'News', featured_image: '' } ] }; return processApiData('featured', mockData, layoutType); case 'incentive': mockData = { title: 'Incentive Numbers (Mock)', items: [ {item_text: 'Total Students Hosted', item_value: '18'}, {item_text: 'Months Active', item_value: '24'} ] }; return processApiData('incentive', mockData, layoutType); default: return '

Mock data for ' + type + ' card type.

'; } } // Function to check and update scrollable cards function updateScrollableCards() { if (!scrollDetectionInitialized) return; $('.scrollable-card').each(function() { const $card = $(this); let scrollableElement; // Find the scrollable element inside each card type if ($card.hasClass('card-type-profile')) { scrollableElement = $card.find('.profile-card-content'); } else if ($card.hasClass('card-type-upcoming')) { scrollableElement = $card.find('.upcoming-card-content'); } else if ($card.hasClass('card-type-featured')) { scrollableElement = $card.find('.featured-card-content'); } else if ($card.hasClass('card-type-incentive')) { scrollableElement = $card.find('.incentive-card-content'); } else if ($card.hasClass('tools-card')) { scrollableElement = $card.find('.tools-card-content'); } if (scrollableElement && scrollableElement.length > 0) { const isScrollable = scrollableElement[0].scrollHeight > scrollableElement[0].clientHeight; if (isScrollable) { $card.addClass('scroll-active'); } else { $card.removeClass('scroll-active'); } } }); } // Initialize scroll detection function initScrollDetection() { scrollDetectionInitialized = true; updateScrollableCards(); let resizeTimer; $(window).on('resize', function() { clearTimeout(resizeTimer); resizeTimer = setTimeout(function() { updateScrollableCards(); }, 250); }); // Update when content changes const observer = new MutationObserver(function() { clearTimeout(observer.timeout); observer.timeout = setTimeout(function() { updateScrollableCards(); }, 100); }); // Observe only the dashboard grid const dashboardGrid = document.querySelector('.dashboard-grid'); if (dashboardGrid) { observer.observe(dashboardGrid, { childList: true, subtree: true, attributes: false, characterData: false }); } } // Function to test API connection function testApiConnection(endpoint, cardType, layoutType) { return makeApiCall(endpoint, cardType, '', layoutType) .then(function(data) { return { success: true, data: data, message: 'API connection successful' }; }) .catch(function(error) { //console.error('API Test Failed:', error); return { success: false, error: error, message: 'API connection failed: ' + error }; }); } // Test AJAX connection directly function testAjaxConnection() { if (!dashboardConfig.ajaxurl) { initDashboardConfig(); } if (!dashboardConfig.ajaxurl) { return Promise.reject('Missing required variable ajaxurl for AJAX test'); } return $.ajax({ url: dashboardConfig.ajaxurl, type: 'POST', dataType: 'json', data: { action: 'dashboard_api_request', endpoint: 'test', card_type: 'profile', layout_type: 'host' } }).then(function(response) { return response; }).catch(function(xhr, status, error) { throw error; }); } // Initialize the dashboard module function initDashboardModule() { if (dashboardInitialized) { //console.log('Dashboard already initialized'); return; } dashboardInitialized = true; //console.log('Initializing dashboard module...'); // Initialize configuration initDashboardConfig(); initScrollDetection(); // Initialize API data fetching for all API cards $('.dashboard-card').each(function() { var $card = $(this); if($card.find('.api-config').length) { //console.log('Found API card:', $card[0]); fetchApiData($card); } }); } // Initialize when document is ready $(document).ready(function() { //console.log('Dashboard module loading...'); // Initialize immediately (no delay) initDashboardModule(); // Expose test function globally for console testing window.testDashboardApi = function(cardType) { var $card = $('.dashboard-card.card-type-' + cardType); var layoutType = dashboardConfig.layoutType; var wrapper = $('.dashboard-grid-wrapper'); if (wrapper.length) { layoutType = wrapper.attr('class')?.includes('rep') ? 'rep' : 'host'; } if ($card.length) { var $config = $card.find('.api-config'); var endpoint = $config.data('endpoint'); return testApiConnection(endpoint, cardType, layoutType); } else { //console.error('Card not found:', cardType); return Promise.reject('Card not found'); } }; // Expose AJAX test function window.testAjaxConnection = testAjaxConnection; }); // Initialize on window load $(window).on('load', function() { if (scrollDetectionInitialized) { updateScrollableCards(); } }); // Make functions available globally window.dashboardModule = { fetchApiData: fetchApiData, makeApiCall: makeApiCall, processApiData: processApiData, getMockData: getMockData, testApiConnection: testApiConnection, testAjaxConnection: testAjaxConnection, updateScrollableCards: updateScrollableCards, initScrollDetection: initScrollDetection, init: initDashboardModule, getConfig: function() { return dashboardConfig; } }; //console.log('Dashboard module loaded'); })(jQuery);