/** * icshd-api-connector.js * Handles all API interactions for the ICSHD API Connector WordPress plugin. * * This version includes additional console logs to debug the connection * issue directly within the WordPress environment. */ jQuery(document).ready(function($) { // Define your API base URL directly here. const BASE_API_URL = 'https://icshd-geniuses-backend-in.onrender.com/api/v1'; // *** رسالة تتبع جديدة للتأكد من أن السكربت يعمل *** console.log('ICSHD API Connector is initialized and running.'); console.log('Using API URL:', BASE_API_URL); // Get the home URL from the PHP-provided data (if available), fallback to current domain const HOME_URL = typeof icshdApiData !== 'undefined' ? icshdApiData.homeUrl : window.location.origin; // A simple function to display messages to the user function displayMessage(message, type = 'success') { const messageBox = $('.icshd-message'); if (messageBox.length === 0) { console.warn('Warning: .icshd-message element not found. Message:', message); return; } messageBox.text(message).removeClass('success error info').addClass(type).fadeIn(); // Clear message after 5 seconds setTimeout(() => messageBox.fadeOut(), 5000); } // Function to save the JWT token to local storage function saveToken(token) { localStorage.setItem('icshd_jwt_token', token); } // Function to get the JWT token from local storage function getToken() { return localStorage.getItem('icshd_jwt_token'); } // Function to remove the JWT token on logout function removeToken() { localStorage.removeItem('icshd_jwt_token'); } /** * Handles the login form submission. */ $('#icshd-login-form').on('submit', async function(e) { e.preventDefault(); const form = $(this); const username = form.find('#username').val(); // Can be username or email for login const password = form.find('#password').val(); if (!username || !password) { displayMessage('الرجاء إدخال اسم المستخدم/البريد الإلكتروني وكلمة المرور.', 'error'); return; } displayMessage('يتم تسجيل الدخول...', 'info'); // *** رسالة تتبع جديدة لإظهار بيانات الطلب *** console.log('Attempting login...'); console.log('Login API URL:', `${BASE_API_URL}/auth/login`); console.log('Login Payload:', { username, password }); try { const response = await fetch(`${BASE_API_URL}/auth/login`, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ username, password }) }); // *** رسالة تتبع جديدة لرد الخادم *** console.log('Received response from server:', response); // Always try to parse JSON, even if response.ok is false, // as backend might send error details in JSON const data = await response.json(); // *** رسالة تتبع جديدة لبيانات الرد *** console.log('Received data:', data); if (!response.ok) { // If the response is not OK (e.g., 400, 401, 500), throw an error with backend message throw new Error(data.message || 'فشل تسجيل الدخول. الرجاء التحقق من بياناتك.'); } // Success! Save the token and redirect. saveToken(data.token); displayMessage('تم تسجيل الدخول بنجاح! يتم التوجيه...', 'success'); // Redirect to the dashboard page or home page setTimeout(() => { window.location.href = HOME_URL + '/لوحة-تحكم-الإضافة/'; // Redirect to your actual dashboard/admin page }, 1000); } catch (error) { // Check for specific "Failed to fetch" error if (error.message === 'Failed to fetch') { displayMessage('فشل الاتصال بالخادم. يرجى التحقق من اتصالك بالإنترنت أو الاتصال بالدعم.', 'error'); } else { displayMessage(error.message, 'error'); } console.error('Login error:', error); } }); /** * Handles the registration form submission. */ $('#icshd-register-form').on('submit', async function(e) { e.preventDefault(); const form = $(this); const username = form.find('#reg-username').val(); const email = form.find('#reg-email').val(); const password = form.find('#reg-password').val(); const firstName = form.find('#reg-firstName').val(); const lastName = form.find('#reg-lastName').val(); // Check for all required fields based on your backend if (!username || !email || !password || !firstName || !lastName) { displayMessage('الرجاء إدخال جميع الحقول المطلوبة.', 'error'); return; } displayMessage('يتم التسجيل...', 'info'); // *** رسالة تتبع جديدة لإظهار بيانات الطلب *** console.log('Attempting registration...'); console.log('Registration API URL:', `${BASE_API_URL}/auth/register`); console.log('Registration Payload:', { username, email, password, firstName, lastName }); try { const response = await fetch(`${BASE_API_URL}/auth/register`, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ username, email, password, firstName, lastName }) }); // *** رسالة تتبع جديدة لرد الخادم *** console.log('Received response from server:', response); // Always try to parse JSON, even if response.ok is false const data = await response.json(); // *** رسالة تتبع جديدة لبيانات الرد *** console.log('Received data:', data); if (!response.ok) { // Throw an error with backend message throw new Error(data.message || 'فشل التسجيل. الرجاء المحاولة مرة أخرى.'); } // Success! Save the token (optional for registration, but good for immediate login) saveToken(data.token); displayMessage('تم التسجيل بنجاح! يتم التوجيه لتسجيل الدخول...', 'success'); // Redirect to the login page after successful registration const loginPage = HOME_URL + '/تسجيل-الدخول/'; // Construct full URL for login page setTimeout(() => { window.location.href = loginPage; }, 1000); } catch (error) { // Check for specific "Failed to fetch" error if (error.message === 'Failed to fetch') { displayMessage('فشل الاتصال بالخادم. يرجى التحقق من اتصالك بالإنترنت أو الاتصال بالدعم.', 'error'); } else { displayMessage(error.message, 'error'); } console.error('Registration error:', error); } }); // Handle logout functionality // This will now listen to a specific button with id 'icshd-logout-button' $('#icshd-logout-button').on('click', function(e) { e.preventDefault(); removeToken(); displayMessage('تم تسجيل الخروج بنجاح!', 'success'); setTimeout(() => { window.location.href = HOME_URL; // Redirect to home page after logout }, 500); // Redirect faster after logout }); // Show/hide logout button based on token presence const token = getToken(); if (token) { $('#icshd-logout-button').show(); // Show the button if token exists // Optionally hide login/register forms if user is logged in $('.icshd-form-container').each(function() { if ($(this).find('#icshd-login-form').length || $(this).find('#icshd-register-form').length) { $(this).hide(); } }); } else { $('#icshd-logout-button').hide(); // Hide the button if no token } });