/**
* CV-Plus Things - Google Sign-In and AdSense Integration
* Complete JavaScript implementation for Google OAuth and AdSense
*
* This file handles:
* - Google Sign-In initialization and callback
* - Google AdSense loading and display
* - User authentication flow
* - Session management
*/
// ============================================================================
// GOOGLE SIGN-IN INTEGRATION
// ============================================================================
/**
* Initialize Google Sign-In
* This function should be called when the page loads
*/
function initializeGoogleSignIn() {
// Check if Google API is loaded
if (!window.google || !window.google.accounts) {
console.error('Google Sign-In library not loaded');
return;
}
// Get the Google Client ID from the page
const googleClientId = document.querySelector('[data-google-client-id]')?.dataset.googleClientId ||
cvPlusThingsData?.google_client_id ||
'YOUR_GOOGLE_CLIENT_ID.apps.googleusercontent.com';
// Initialize Google Sign-In
window.google.accounts.id.initialize({
client_id: googleClientId,
callback: handleGoogleSignInResponse,
auto_select: false,
itp_support: true,
});
// Render the Google Sign-In button in the modal
try {
window.google.accounts.id.renderButton(
document.getElementById('cv-plus-google-signin-button'),
{
type: 'standard',
size: 'large',
theme: 'outline',
text: 'signin_with',
shape: 'rectangular',
logo_alignment: 'left',
width: '300',
}
);
} catch (error) {
console.warn('Could not render Google Sign-In button:', error);
}
console.log('Google Sign-In initialized successfully');
}
/**
* Handle Google Sign-In Response
* Called when user successfully signs in with Google
*
* @param {Object} response - Google Sign-In response object
* @param {string} response.credential - JWT token from Google
*/
function handleGoogleSignInResponse(response) {
console.log('Google Sign-In Response received');
if (!response.credential) {
console.error('No credential received from Google Sign-In');
showNotification('Sign-In Error', 'Failed to receive credentials from Google', 'error');
return;
}
// Decode the JWT token (without verification - verification should happen on server)
const decodedToken = decodeJWT(response.credential);
console.log('Decoded Google token:', decodedToken);
// Store the token in session storage
sessionStorage.setItem('cv_plus_google_token', response.credential);
sessionStorage.setItem('cv_plus_user_email', decodedToken.email);
sessionStorage.setItem('cv_plus_user_name', decodedToken.name);
sessionStorage.setItem('cv_plus_user_picture', decodedToken.picture);
// Send token to backend for verification and user creation/update
sendTokenToBackend(response.credential, decodedToken);
// Update UI to show user is logged in
updateUIAfterSignIn(decodedToken);
// Close the sign-in modal
cvPlusThingsCloseModal('google-signin');
// Show success notification
showNotification('Success', `Welcome ${decodedToken.name}!`, 'success');
}
/**
* Decode JWT Token
* Decodes the JWT token to extract user information
* Note: This is client-side decoding only. Server should verify the signature.
*
* @param {string} token - JWT token from Google
* @returns {Object} Decoded token payload
*/
function decodeJWT(token) {
try {
const base64Url = token.split('.')[1];
const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
const jsonPayload = decodeURIComponent(
atob(base64)
.split('')
.map((c) => '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2))
.join('')
);
return JSON.parse(jsonPayload);
} catch (error) {
console.error('Error decoding JWT:', error);
return {};
}
}
/**
* Send Token to Backend
* Sends the Google token to the backend for verification and user creation
*
* @param {string} token - JWT token from Google
* @param {Object} decodedToken - Decoded token information
*/
function sendTokenToBackend(token, decodedToken) {
// Prepare the request data
const requestData = {
action: 'cv_plus_google_signin',
nonce: cvPlusThingsData?.nonce,
token: token,
email: decodedToken.email,
name: decodedToken.name,
picture: decodedToken.picture,
};
// Send AJAX request to backend
fetch(cvPlusThingsData?.ajax_url || '/wp-admin/admin-ajax.php', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams(requestData),
})
.then((response) => response.json())
.then((data) => {
if (data.success) {
console.log('User authenticated on backend:', data.data);
// Store user session ID if provided
if (data.data.session_id) {
sessionStorage.setItem('cv_plus_session_id', data.data.session_id);
}
if (data.data.user_id) {
sessionStorage.setItem('cv_plus_user_id', data.data.user_id);
}
} else {
console.error('Backend authentication failed:', data.data);
showNotification('Error', 'Failed to authenticate with server', 'error');
}
})
.catch((error) => {
console.error('Error sending token to backend:', error);
showNotification('Error', 'Network error during authentication', 'error');
});
}
/**
* Update UI After Sign-In
* Updates the UI to reflect that user is logged in
*
* @param {Object} userInfo - User information from Google token
*/
function updateUIAfterSignIn(userInfo) {
// Update navigation
const navAuth = document.querySelector('.nav-auth');
if (navAuth) {
navAuth.innerHTML = `
${userInfo.name}
`;
}
// Update dashboard button
const dashboardBtn = document.querySelector('[onclick*="dashboard"]');
if (dashboardBtn) {
dashboardBtn.style.display = 'inline-block';
}
// Show seller options
const becomeProviderBtn = document.querySelector('[onclick*="become-provider"]');
if (becomeProviderBtn) {
becomeProviderBtn.style.display = 'inline-block';
}
// Add CSS for user profile styling
addUserProfileStyles();
}
/**
* Handle Google Sign Out
* Logs out the user from Google and clears session
*/
function handleGoogleSignOut() {
// Sign out from Google
if (window.google && window.google.accounts) {
window.google.accounts.id.disableAutoSelect();
}
// Clear session storage
sessionStorage.removeItem('cv_plus_google_token');
sessionStorage.removeItem('cv_plus_user_email');
sessionStorage.removeItem('cv_plus_user_name');
sessionStorage.removeItem('cv_plus_user_picture');
sessionStorage.removeItem('cv_plus_session_id');
sessionStorage.removeItem('cv_plus_user_id');
// Send logout request to backend
fetch(cvPlusThingsData?.ajax_url || '/wp-admin/admin-ajax.php', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams({
action: 'cv_plus_google_logout',
nonce: cvPlusThingsData?.nonce,
}),
})
.then((response) => response.json())
.then((data) => {
console.log('Logout successful');
// Reload page to reset UI
location.reload();
})
.catch((error) => {
console.error('Error logging out:', error);
// Still reload page even if backend logout fails
location.reload();
});
}
/**
* Check if User is Logged In
* Checks if user has a valid session
*
* @returns {boolean} True if user is logged in
*/
function isUserLoggedIn() {
return !!sessionStorage.getItem('cv_plus_google_token') && !!sessionStorage.getItem('cv_plus_session_id');
}
/**
* Get Current User Info
* Returns the current logged-in user information
*
* @returns {Object} User information or null
*/
function getCurrentUserInfo() {
if (!isUserLoggedIn()) {
return null;
}
return {
email: sessionStorage.getItem('cv_plus_user_email'),
name: sessionStorage.getItem('cv_plus_user_name'),
picture: sessionStorage.getItem('cv_plus_user_picture'),
userId: sessionStorage.getItem('cv_plus_user_id'),
sessionId: sessionStorage.getItem('cv_plus_session_id'),
};
}
// ============================================================================
// GOOGLE ADSENSE INTEGRATION
// ============================================================================
/**
* Initialize Google AdSense
* Loads the AdSense script and initializes ad units
*/
function initializeGoogleAdSense() {
// Check if AdSense is enabled
if (!cvPlusThingsData?.adsense_enabled) {
console.log('Google AdSense is disabled');
return;
}
// Load AdSense script if not already loaded
if (!window.adsbygoogle) {
const script = document.createElement('script');
script.async = true;
script.src = 'https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-6943304898639392';
script.crossOrigin = 'anonymous';
script.onload = function () {
console.log('Google AdSense script loaded');
pushAdSenseAds();
};
script.onerror = function () {
console.error('Failed to load Google AdSense script');
};
document.head.appendChild(script);
} else {
// AdSense already loaded, push ads
pushAdSenseAds();
}
}
/**
* Push AdSense Ads
* Pushes all AdSense ad units to be displayed
*/
function pushAdSenseAds() {
if (window.adsbygoogle) {
try {
(adsbygoogle = window.adsbygoogle || []).push({});
console.log('AdSense ads pushed successfully');
} catch (error) {
console.error('Error pushing AdSense ads:', error);
}
}
}
/**
* Insert AdSense Ad Unit
* Dynamically inserts an AdSense ad unit at a specific location
*
* @param {string} elementId - ID of the element where ad should be inserted
* @param {string} adSlot - AdSense ad slot ID
* @param {string} format - Ad format (auto, horizontal, vertical, etc.)
*/
function insertAdSenseUnit(elementId, adSlot, format = 'auto') {
const element = document.getElementById(elementId);
if (!element) {
console.warn(`Element with ID ${elementId} not found`);
return;
}
const adUnit = document.createElement('ins');
adUnit.className = 'adsbygoogle';
adUnit.style.display = 'block';
adUnit.setAttribute('data-ad-client', 'ca-pub-6943304898639392');
adUnit.setAttribute('data-ad-slot', adSlot);
adUnit.setAttribute('data-ad-format', format);
adUnit.setAttribute('data-full-width-responsive', 'true');
element.appendChild(adUnit);
// Push the new ad
if (window.adsbygoogle) {
(adsbygoogle = window.adsbygoogle || []).push({});
}
}
/**
* Track AdSense Performance
* Tracks AdSense ad impressions and clicks
*
* @param {string} adSlot - Ad slot ID
* @param {string} eventType - Type of event (impression, click)
*/
function trackAdSensePerformance(adSlot, eventType) {
// Send tracking data to backend
const trackingData = {
action: 'cv_plus_track_adsense',
nonce: cvPlusThingsData?.nonce,
ad_slot: adSlot,
event_type: eventType,
timestamp: new Date().toISOString(),
};
fetch(cvPlusThingsData?.ajax_url || '/wp-admin/admin-ajax.php', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams(trackingData),
})
.then((response) => response.json())
.then((data) => {
console.log('AdSense event tracked:', data);
})
.catch((error) => {
console.error('Error tracking AdSense event:', error);
});
}
// ============================================================================
// UTILITY FUNCTIONS
// ============================================================================
/**
* Show Notification
* Displays a notification message to the user
*
* @param {string} title - Notification title
* @param {string} message - Notification message
* @param {string} type - Notification type (success, error, info, warning)
*/
function showNotification(title, message, type = 'info') {
// Create notification element
const notification = document.createElement('div');
notification.className = `cv-plus-notification cv-plus-notification-${type}`;
notification.innerHTML = `
${title}
${message}
`;
// Add to page
document.body.appendChild(notification);
// Auto-remove after 5 seconds
setTimeout(() => {
notification.remove();
}, 5000);
}
/**
* Add User Profile Styles
* Adds CSS styles for user profile display
*/
function addUserProfileStyles() {
const style = document.createElement('style');
style.textContent = `
.user-profile {
display: flex;
align-items: center;
gap: 1rem;
padding: 0.5rem 1rem;
background: #f0f0f0;
border-radius: 4px;
}
.user-avatar {
width: 40px;
height: 40px;
border-radius: 50%;
object-fit: cover;
}
.user-name {
font-weight: 600;
color: #333;
}
.logout-btn {
padding: 0.5rem 1rem;
background: #ef4444;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
font-weight: 600;
transition: background 0.3s;
}
.logout-btn:hover {
background: #dc2626;
}
.cv-plus-notification {
position: fixed;
top: 20px;
right: 20px;
background: white;
border-radius: 8px;
box-shadow: 0 4px 12px rgba(0,0,0,0.15);
padding: 1.5rem;
max-width: 400px;
z-index: 9999;
animation: slideIn 0.3s ease-out;
}
.cv-plus-notification-success {
border-left: 4px solid #10b981;
}
.cv-plus-notification-error {
border-left: 4px solid #ef4444;
}
.cv-plus-notification-info {
border-left: 4px solid #3b82f6;
}
.cv-plus-notification-warning {
border-left: 4px solid #f59e0b;
}
.notification-content h4 {
margin-bottom: 0.5rem;
color: #333;
}
.notification-content p {
color: #666;
font-size: 0.9rem;
}
.notification-close {
position: absolute;
top: 0.5rem;
right: 0.5rem;
background: none;
border: none;
font-size: 1.5rem;
cursor: pointer;
color: #999;
}
@keyframes slideIn {
from {
transform: translateX(400px);
opacity: 0;
}
to {
transform: translateX(0);
opacity: 1;
}
}
`;
document.head.appendChild(style);
}
// ============================================================================
// PAGE INITIALIZATION
// ============================================================================
/**
* Initialize on Page Load
* Initializes Google Sign-In and AdSense when page loads
*/
document.addEventListener('DOMContentLoaded', function () {
console.log('CV-Plus Things marketplace initializing...');
// Initialize Google Sign-In
initializeGoogleSignIn();
// Initialize Google AdSense
initializeGoogleAdSense();
// Check if user is already logged in
if (isUserLoggedIn()) {
const userInfo = getCurrentUserInfo();
updateUIAfterSignIn(userInfo);
}
console.log('CV-Plus Things marketplace initialized successfully');
});
// Handle page visibility changes (for session management)
document.addEventListener('visibilitychange', function () {
if (document.visibilityState === 'visible') {
// Page became visible - refresh user session if needed
if (isUserLoggedIn()) {
console.log('Page became visible, user session is active');
}
}
});
// Handle window unload (for cleanup)
window.addEventListener('beforeunload', function () {
// Optional: Send analytics or cleanup data
console.log('User leaving CV-Plus Things marketplace');
});