/** * Skin Analysis Interactive - JavaScript * منطق التفاعل والتنقل بين الشاشات */ // =================================== // State Management // =================================== const AnalysisState = { currentScreen: 1, sessionToken: ANALYSIS_TOKEN, sessionId: null, detectedConcerns: [], selectedSymptoms: [], analysisResult: null, selectedDate: null, selectedClinic: null }; // =================================== // Initialize // =================================== document.addEventListener('DOMContentLoaded', function() { console.log('🚀 Skin Analysis Interactive Started'); // Start new session startAnalysisSession(); // Setup navigation setupNavigation(); // Hide loading screen after 2 seconds setTimeout(() => { document.getElementById('loadingScreen').classList.add('hidden'); }, 2000); }); // =================================== // Session Management // =================================== async function startAnalysisSession() { try { const response = await fetch('../api/skin-analysis-start.php', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ token: AnalysisState.sessionToken }) }); const data = await response.json(); if (data.success) { AnalysisState.sessionId = data.session_id; console.log('✅ Session started:', AnalysisState.sessionId); // Start detection simulation setTimeout(() => { simulateDetection(); }, 3000); } else { console.error('❌ Failed to start session:', data.message); } } catch (error) { console.error('❌ Error starting session:', error); } } // =================================== // Screen 1: Detection Simulation // =================================== async function simulateDetection() { try { const response = await fetch('../api/skin-analysis-detect.php', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ session_id: AnalysisState.sessionId }) }); const data = await response.json(); if (data.success) { AnalysisState.detectedConcerns = data.concerns; displayDetectionResults(data.concerns); } else { console.error('❌ Detection failed:', data.message); } } catch (error) { console.error('❌ Error in detection:', error); } } function displayDetectionResults(concerns) { const titleEl = document.getElementById('detectionTitle'); const subtitleEl = document.getElementById('detectionSubtitle'); const nextBtn = document.getElementById('nextBtn1'); const detectionPoints = document.getElementById('detectionPoints'); if (concerns.length === 0) { titleEl.textContent = 'لم يتم اكتشاف أي مشاكل'; subtitleEl.textContent = 'بشرتك تبدو رائعة!'; } else { const primaryConcern = concerns[0]; const count = primaryConcern.count; const type = getConcernNameAr(primaryConcern.type); titleEl.textContent = `تم اكتشاف ${count} ${type}`; subtitleEl.textContent = 'هذا يتطلب المراقبة'; // Add detection points to SVG concerns.forEach((concern, index) => { const circle = document.createElementNS('http://www.w3.org/2000/svg', 'circle'); circle.setAttribute('cx', concern.position_x * 3); circle.setAttribute('cy', concern.position_y * 4); circle.setAttribute('r', '15'); circle.setAttribute('fill', 'rgba(239, 68, 68, 0.3)'); circle.setAttribute('stroke', '#ef4444'); circle.setAttribute('stroke-width', '2'); circle.classList.add('detection-point'); circle.style.animationDelay = `${index * 0.2}s`; detectionPoints.appendChild(circle); }); } // Enable next button nextBtn.disabled = false; } function getConcernNameAr(type) { const names = { 'moles': 'شامة', 'acne': 'حب شباب', 'dark_spots': 'بقعة داكنة', 'redness': 'احمرار', 'fine_lines': 'خط رفيع', 'wrinkles': 'تجعد', 'pores': 'مسام', 'dryness': 'جفاف', 'oiliness': 'دهون' }; return names[type] || type; } // =================================== // Screen 2: Symptoms Selection // =================================== async function loadSymptoms() { if (AnalysisState.detectedConcerns.length === 0) { // Skip to results if no concerns goToScreen(3); return; } try { const primaryConcern = AnalysisState.detectedConcerns[0]; const response = await fetch(`../api/skin-analysis-symptoms.php?concern_type=${primaryConcern.type}`); const data = await response.json(); if (data.success) { displaySymptoms(data.symptoms); } else { console.error('❌ Failed to load symptoms:', data.message); } } catch (error) { console.error('❌ Error loading symptoms:', error); } } function displaySymptoms(symptoms) { const grid = document.getElementById('symptomsGrid'); grid.innerHTML = ''; symptoms.forEach(symptom => { const card = document.createElement('div'); card.className = 'symptom-card'; card.dataset.symptomId = symptom.id; card.innerHTML = `
${symptom.name_ar}
`; card.addEventListener('click', () => toggleSymptom(card, symptom.id)); grid.appendChild(card); }); } function toggleSymptom(card, symptomId) { card.classList.toggle('selected'); const index = AnalysisState.selectedSymptoms.indexOf(symptomId); if (index > -1) { AnalysisState.selectedSymptoms.splice(index, 1); } else { AnalysisState.selectedSymptoms.push(symptomId); } console.log('Selected symptoms:', AnalysisState.selectedSymptoms); } async function saveSymptoms() { if (AnalysisState.selectedSymptoms.length === 0) { return true; } try { const response = await fetch('../api/skin-analysis-symptoms.php', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ session_id: AnalysisState.sessionId, concern_id: AnalysisState.detectedConcerns[0].id, symptoms: AnalysisState.selectedSymptoms }) }); const data = await response.json(); return data.success; } catch (error) { console.error('❌ Error saving symptoms:', error); return false; } } // =================================== // Screen 3: Results & Recommendations // =================================== async function loadResults() { try { const response = await fetch('../api/skin-analysis-results.php', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ session_id: AnalysisState.sessionId }) }); const data = await response.json(); if (data.success) { AnalysisState.analysisResult = data.result; displayResults(data.result); loadDates(); loadClinics(data.clinics); } else { console.error('❌ Failed to load results:', data.message); } } catch (error) { console.error('❌ Error loading results:', error); } } function displayResults(result) { const scoreNumber = document.getElementById('scoreNumber'); const scoreLabel1 = document.getElementById('scoreLabel1'); const scoreLabel2 = document.getElementById('scoreLabel2'); // Animate score animateScore(0, result.severity_percentage, 2000, scoreNumber); // Set labels based on concern type if (result.primary_concern === 'oiliness') { scoreLabel1.textContent = 'دهنية'; scoreLabel2.textContent = 'جافة'; } else if (result.primary_concern === 'dryness') { scoreLabel1.textContent = 'جافة'; scoreLabel2.textContent = 'دهنية'; } else { scoreLabel1.textContent = 'مشاكل'; scoreLabel2.textContent = 'صحية'; } } function animateScore(start, end, duration, element) { const startTime = performance.now(); function update(currentTime) { const elapsed = currentTime - startTime; const progress = Math.min(elapsed / duration, 1); const current = Math.floor(start + (end - start) * progress); element.textContent = current; if (progress < 1) { requestAnimationFrame(update); } } requestAnimationFrame(update); } function loadDates() { const dateButtons = document.getElementById('dateButtons'); dateButtons.innerHTML = ''; const today = new Date(); for (let i = 0; i < 7; i++) { const date = new Date(today); date.setDate(today.getDate() + i); const btn = document.createElement('button'); btn.className = 'date-btn'; btn.textContent = formatDate(date); btn.dataset.date = date.toISOString().split('T')[0]; if (i === 0) { btn.classList.add('selected'); AnalysisState.selectedDate = btn.dataset.date; } btn.addEventListener('click', () => selectDate(btn)); dateButtons.appendChild(btn); } } function formatDate(date) { const days = ['الأحد', 'الإثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت']; const day = days[date.getDay()]; const dateNum = date.getDate(); return `${day} ${dateNum}`; } function selectDate(btn) { document.querySelectorAll('.date-btn').forEach(b => b.classList.remove('selected')); btn.classList.add('selected'); AnalysisState.selectedDate = btn.dataset.date; } function loadClinics(clinics) { const clinicsList = document.getElementById('clinicsList'); clinicsList.innerHTML = ''; clinics.forEach(clinic => { const card = document.createElement('div'); card.className = 'clinic-card'; card.innerHTML = ` ${clinic.name}
${clinic.name}
${clinic.rating || '4.5'}
${clinic.distance || '2 كم'}
`; clinicsList.appendChild(card); }); } function bookClinic(clinicId) { // Redirect to booking page with analysis data window.location.href = `consultation-booking.php?clinic_id=${clinicId}&session_id=${AnalysisState.sessionId}&date=${AnalysisState.selectedDate}`; } // =================================== // Navigation // =================================== function setupNavigation() { // Screen 1 document.getElementById('nextBtn1').addEventListener('click', async () => { await goToScreen(2); loadSymptoms(); }); // Screen 2 document.getElementById('backBtn2').addEventListener('click', () => { goToScreen(1); }); document.getElementById('nextBtn2').addEventListener('click', async () => { await saveSymptoms(); await goToScreen(3); loadResults(); }); document.getElementById('skipBtn2').addEventListener('click', async () => { await goToScreen(3); loadResults(); }); // Screen 3 document.getElementById('backBtn3').addEventListener('click', () => { goToScreen(2); }); document.getElementById('finishBtn').addEventListener('click', () => { finishAnalysis(); }); } async function goToScreen(screenNumber) { const currentScreen = document.querySelector('.screen.active'); const nextScreen = document.getElementById(`screen${screenNumber}`); if (!nextScreen) return; // Determine direction const direction = screenNumber > AnalysisState.currentScreen ? 'left' : 'right'; // Exit current screen currentScreen.classList.remove('active'); currentScreen.classList.add(`exit-${direction}`); // Enter next screen setTimeout(() => { currentScreen.classList.remove(`exit-${direction}`); nextScreen.classList.add('active'); AnalysisState.currentScreen = screenNumber; // Scroll to top window.scrollTo(0, 0); }, 100); } function finishAnalysis() { // Show success message or redirect alert('شكراً لاستخدام تحليل البشرة التفاعلي! 🎉'); // Optionally redirect to home or results page // window.location.href = 'index.php'; } // =================================== // Utility Functions // =================================== function showLoading() { document.getElementById('loadingScreen').classList.remove('hidden'); } function hideLoading() { document.getElementById('loadingScreen').classList.add('hidden'); } // Export for global access window.bookClinic = bookClinic;