Contact Us
If you have any questions about the products for sale, how to order, or an existing order please e-mail fargond@clothesmentorstores.com
If you have any questions about the products for sale, how to order, or an existing order please e-mail fargond@clothesmentorstores.com
(function() { if (window.driiveRewardsGlobalInitialized) return; window.driiveRewardsGlobalInitialized = true; console.log("[Driive Rewards] Script Initialized with Logout Fix"); // --- Global State --- const { proxyUrl, shopDomain } = window.driiveRewardsConfig || {}; let lastKnownCartTotal = -1; let isFetchInProgress = false; // --- Main Functions --- const fetchRewards = async () => { if (isFetchInProgress) return; isFetchInProgress = true; const customerPhone = window.driiveRewardsConfig.customerPhone; const cart = await getCart(); const cartTotal = parseFloat(cart.total_price / 100); if (!customerPhone) { updateAllUIs({ success: false, error: 'Log in to check for rewards. Login here.' }); isFetchInProgress = false; return; } try { const url = `${proxyUrl}?phone=${encodeURIComponent(customerPhone)}&shop=${encodeURIComponent(shopDomain)}&cart_total=${cartTotal}`; const response = await fetch(url); const result = await response.json(); updateAllUIs(result); } catch (error) { console.error("[Driive Rewards] Fetch error:", error); updateAllUIs({ success: false, error: "Error checking rewards." }); } finally { isFetchInProgress = false; } }; const redeemReward = async (event) => { const redeemBtn = event.currentTarget; const { rewardCode, rewardValue, g3mid } = redeemBtn.dataset; if (!rewardCode || !rewardValue || !g3mid) { alert('Please select a reward to redeem.'); return; } document.querySelectorAll('.driive-redeem-button').forEach(btn => btn.disabled = true); redeemBtn.textContent = "Redeeming..."; try { const response = await fetch(proxyUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ shop: shopDomain, amount: rewardValue, g3mid: g3mid, reward_code: rewardCode }) }); const data = await response.json(); if (response.ok && data.success && data.discount_code) { // --- EDIT 1: SAVE THE APPLIED REWARD CODE TO THE SESSION --- sessionStorage.setItem('driiveAppliedReward', data.discount_code); // ----------------------------------------------------------- window.location.href = `/checkout?discount=${data.discount_code}`; } else { // Re-enable button on failure redeemBtn.disabled = false; redeemBtn.textContent = "Redeem"; alert(`Failed to redeem: ${data.error || 'Unknown error'}`); } } catch (error) { console.error("[Driive Rewards] Redeem error:", error); redeemBtn.disabled = false; redeemBtn.textContent = "Redeem"; alert("Could not redeem reward due to a technical issue."); } }; const getCart = async () => { const res = await fetch('/cart.js'); return res.json(); }; const updateAllUIs = (result) => { const containers = document.querySelectorAll('.driive-rewards-container'); containers.forEach(container => { container.innerHTML = ''; if (!result) { container.innerHTML = `
Checking for rewards...
`; return; } if (!result.success) { container.innerHTML = `
${result.error}
`; return; } if (result.rewards && result.rewards.length > 0) { const firstReward = result.rewards[0]; const mainRewardContainer = document.createElement('div'); mainRewardContainer.className = 'driive-main-reward'; mainRewardContainer.style.padding = '10px'; mainRewardContainer.style.border = '1px solid #ddd'; mainRewardContainer.style.borderRadius = '5px'; const rewardValue = parseFloat(firstReward.value).toFixed(2); const expirationDate = new Date(firstReward.expirationdate).toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' }); mainRewardContainer.innerHTML = `
`; container.appendChild(mainRewardContainer); if (result.rewards.length > 1) { const dropdown = document.createElement('select'); dropdown.className = 'driive-rewards-dropdown'; dropdown.style.width = '100%'; dropdown.style.marginTop = '10px'; dropdown.style.padding = '8px'; const firstOption = document.createElement('option'); firstOption.value = firstReward.rewardcode; firstOption.textContent = `${firstReward.description} - $${parseFloat(firstReward.value).toFixed(2)}`; firstOption.dataset.rewardValue = firstReward.value; dropdown.appendChild(firstOption); result.rewards.slice(1).forEach(reward => { const option = document.createElement('option'); option.value = reward.rewardcode; option.textContent = `${reward.description} - $${parseFloat(reward.value).toFixed(2)}`; option.dataset.rewardValue = reward.value; dropdown.appendChild(option); }); container.appendChild(dropdown); } const redeemButton = document.createElement('button'); redeemButton.className = 'driive-redeem-button'; redeemButton.textContent = 'Redeem'; redeemButton.style.width = '100%'; redeemButton.style.marginTop = '10px'; redeemButton.style.padding = '12px'; redeemButton.style.backgroundColor = '#000000'; redeemButton.style.color = '#ffffff'; redeemButton.style.border = 'none'; redeemButton.style.borderRadius = '5px'; redeemButton.style.cursor = 'pointer'; redeemButton.style.fontSize = '16px'; container.appendChild(redeemButton); const updateButtonData = () => { let selectedReward; if (result.rewards.length > 1) { const dropdown = container.querySelector('.driive-rewards-dropdown'); const selectedCode = dropdown.value; selectedReward = result.rewards.find(r => r.rewardcode === selectedCode); } else { selectedReward = firstReward; } if (selectedReward) { redeemButton.dataset.rewardCode = selectedReward.rewardcode; redeemButton.dataset.rewardValue = selectedReward.value; redeemButton.dataset.g3mid = result.g3mid; } }; if (result.rewards.length > 1) { container.querySelector('.driive-rewards-dropdown').addEventListener('change', updateButtonData); } redeemButton.addEventListener('click', redeemReward); updateButtonData(); } else { container.innerHTML = `
No available rewards found for your account.
`;
}
if (result.point_balance !== null && result.points_needed_for_reward !== null) {
const pointsBalance = parseInt(result.point_balance, 10);
const pointsNeeded = parseInt(result.points_needed_for_reward, 10);
const pointsRemaining = pointsNeeded - pointsBalance;
const pointsContainer = document.createElement('div');
pointsContainer.className = 'driive-points-summary';
pointsContainer.style.marginTop = '20px';
pointsContainer.style.padding = '15px';
pointsContainer.style.border = '1px solid #ddd';
pointsContainer.style.borderRadius = '5px';
pointsContainer.style.textAlign = 'center';
let pointsMessage = `You have ${pointsBalance} points.`;
if (pointsRemaining > 0) {
pointsMessage += `
Only ${pointsRemaining} points until your next reward!`;
} else {
pointsMessage += `
You have enough points for a new reward!`;
}
pointsContainer.innerHTML = pointsMessage;
container.appendChild(pointsContainer);
}
});
};
// --- Initialization & Polling ---
const checkForUpdates = async () => {
try {
const cart = await getCart();
const newTotal = cart.total_price;
if (newTotal !== lastKnownCartTotal) {
lastKnownCartTotal = newTotal;
fetchRewards();
}
} catch(e) {
console.error("[Driive Rewards] Error checking for cart updates:", e);
}
};
checkForUpdates();
setInterval(checkForUpdates, 2500);
const initLogoutRewardClear = () => {
document.querySelectorAll('a[href="/account/logout"]').forEach(logoutLink => {
logoutLink.addEventListener('click', (event) => {
const appliedReward = sessionStorage.getItem('driiveAppliedReward');
if (!appliedReward) {
return;
}
event.preventDefault();
const logoutUrl = event.currentTarget.href;
const iframe = document.createElement('iframe');
iframe.style.display = 'none';
iframe.src = '/checkout?discount='; // The key step!
document.body.appendChild(iframe);
setTimeout(() => {
sessionStorage.removeItem('driiveAppliedReward');
document.body.removeChild(iframe);
fetch('/cart/clear.js', { method: 'POST' });
window.location.href = logoutUrl;
}, 500);
});
});
};
// Run the logout listener setup once the page is loaded.
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', initLogoutRewardClear);
} else {
initLogoutRewardClear();
}
// -----------------------------------------------------
})();