(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 += '
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 += 'No featured posts available.
'; } return html; case 'incentive': var html = ''; if (data.title && data.title.trim()) { html += '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 = 'Data from JSONPlaceholder API
'; html += 'Showing ' + users.length + ' users from external API:
'; html += '' + data.profile_description + '
'; html += 'No student data available.
'; } // Take first 5 users as "upcoming students" var upcomingUsers = users.slice(0, 5); var html = ''; html += 'Upcoming Students (API)'; html += 'Data loaded from JSONPlaceholder API. Showing ' + upcomingUsers.length + ' upcoming students:
'; // Use tools-list style for consistency html += '' + data.description + '
'; if (data.students && data.students.length > 0) { html += '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);