'use client'; import { useState, useEffect } from 'react'; import { useRouter } from 'next/navigation'; import axios from 'axios'; export default function Turn14SettingsClient() { const router = useRouter(); const [ftpHost, setFtpHost] = useState('ftp.motorstateftp.com'); const [ftpUsername, setFtpUsername] = useState(''); const [ftpPassword, setFtpPassword] = useState(''); const [message, setMessage] = useState(''); const [loading, setLoading] = useState(false); const [statusLoaded, setStatusLoaded] = useState(false); const [showPassword, setShowPassword] = useState(false); const [connectionStatus, setConnectionStatus] = useState<'idle' | 'success' | 'error'>('idle'); const [userId, setUserId] = useState(null); const [payment, setPayment] = useState(null); useEffect(() => { // Check for user ID in cookies or localStorage // Note: Cookies cannot be directly accessed client-side; you may need to sync with the server const uid = localStorage.getItem('data4auto_uid'); if (uid) { setUserId(uid); } else { router.push('/login'); } }, [router]); useEffect(() => { const role = localStorage.getItem("user_role"); const sessionId = localStorage.getItem("payment_session"); // ✅ Admins and Partners can access directly (skip payment check) if (role === "admin" || role === "partner") { return; } // đŸšĢ If no payment session, redirect to pricing if (!sessionId) { router.push("/pricing"); return; } // ✅ Otherwise, check payment details const fetchPaymentDetails = async () => { try { const res: any = await axios.get( "https://ebay.backend.data4autos.com/api/payment/details", { params: { session_id: sessionId } } ); setPayment(res.data.payment); } catch (err) { console.error("Error fetching payment details:", err); } }; fetchPaymentDetails(); }, [router]); const read = async (r: Response) => r.headers.get('content-type')?.includes('application/json') ? r.json() : r.text(); // Load FTP Status on Mount useEffect(() => { if (!userId) return; console.log('Fetching existing FTP status...'); const fetchStatus = async () => { setLoading(true); try { const res = await fetch('https://ebay.backend.data4autos.com/api/motorstate/auth/motorstate/status', { // ^ make sure this path matches the Express route method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ userid: userId }), }); const data = await read(res); if (!res.ok) { throw new Error( (typeof data === 'object' && (data?.message || data?.error)) || `Status failed (${res.status})` ); } if (data?.hasCredentials) { setFtpHost(data.credentials.ftpHost || 'ftp.motorstateftp.com'); setFtpUsername(data.credentials.ftpUsername || ''); setFtpPassword(data.credentials.ftpPassword || ''); setMessage('✅ Existing FTP credentials loaded.'); setConnectionStatus('success'); } else { setMessage('â„šī¸ No credentials saved yet.'); setConnectionStatus('idle'); } } catch (e: any) { console.error('Error fetching FTP status:', e); setMessage(`❌ ${e?.message || 'Failed to fetch status.'}`); setConnectionStatus('error'); } finally { setLoading(false); setStatusLoaded(true); } }; fetchStatus(); }, [userId]); // Test and Save Credentials const handleTestAndSave = async () => { setMessage(''); if (!ftpUsername || !ftpPassword) { setMessage('❌ Please enter FTP Username and Password.'); setConnectionStatus('error'); return; } if (!userId) { setMessage('❌ User ID not found. Please log in again.'); setConnectionStatus('error'); return; } setLoading(true); try { setMessage('Testing FTP connection... Please wait.'); // Test the FTP connection const testRes = await fetch('https://motorstate.data4autos.com/api/tokens', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ clientName: "motorstate", host: ftpHost, user: ftpUsername, password: ftpPassword, }), }); const testData = await read(testRes); if (!testData.ok) { throw new Error(testData.message || 'FTP connection failed'); } // If test is successful, save the credentials setMessage('✅ FTP connection successful. Saving credentials...'); const saveRes = await fetch('https://ebay.backend.data4autos.com/api/motorstate/auth/motorstate/save', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ userid: userId, ftpHost, ftpUsername, ftpPassword, clientName : "motorstate", }), }); const saveData = await read(saveRes); if (!saveRes.ok) { console.error('Save request failed:', saveRes.status, saveData); throw new Error( (typeof saveData === 'object' && (saveData?.message || saveData?.error)) || `Save failed (${saveRes.status})` ); } setMessage('✅ Credentials tested and saved successfully.'); setConnectionStatus('success'); } catch (e: any) { console.error('Error in handleTestAndSave:', e); setMessage(`❌ ${e?.message || 'Failed to test or save credentials.'}`); setConnectionStatus('error'); } finally { setLoading(false); } }; const getStatusColor = () => { switch (connectionStatus) { case 'success': return 'bg-green-100 border-green-400 text-green-800'; case 'error': return 'bg-red-100 border-red-400 text-red-800'; default: return 'bg-blue-100 border-blue-400 text-blue-800'; } }; const getStatusIcon = () => { switch (connectionStatus) { case 'success': return ( ); case 'error': return ( ); default: return ( ); } }; return (
{/* Header Section */}

MotorState FTP Configuration

Manage your MotorState FTP credentials securely.

{/* Input Fields */}
setFtpHost(e.target.value)} className="block w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#00d1ff] focus:border-[#00d1ff] transition-all" placeholder="Enter your FTP Host (e.g., ftp.example.com)" />
setFtpUsername(e.target.value)} className="block w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#00d1ff] focus:border-[#00d1ff] transition-all" placeholder="Enter your FTP Username" />
setFtpPassword(e.target.value)} className="block w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-[#00d1ff] focus:border-[#00d1ff] transition-all pr-10" placeholder="Enter your FTP Password" />
{/* Test and Save Button */} {/* Status Message */} {statusLoaded && message && (
{getStatusIcon()}

{message}

)} {/* Tips Section */}

💡 Connection Tips

  • â€ĸ Ensure your FTP credentials are valid and active.
  • â€ĸ The default FTP host is ftp.motorstateftp.com.
  • â€ĸ Your credentials will be tested before saving.
); }