<?php
// modules/store/widgets/success_box.php
if (basename($_SERVER['PHP_SELF']) == 'success_box.php') { die('Access Denied'); }

// استخراج ID سرور برای استفاده در توابع دریافت کانفیگ
$targetServerId = 1;
if (!empty($purchasedConfigs)) {
    $sampleUser = $purchasedConfigs[0]['account_username'];
    $stmtSrv = $pdo->prepare("SELECT server_id FROM inventory WHERE account_username = ? LIMIT 1");
    $stmtSrv->execute([$sampleUser]);
    $targetServerId = $stmtSrv->fetchColumn() ?: 1;
}

// آماده‌سازی دیتای اکسپورت برای جاوااسکریپت
$exportData = [];
foreach($purchasedConfigs as $c) {
    $exportData[] = [
        'username' => $c['account_username'],
        'sub_link' => $c['config_link']
    ];
}
?>

<div class="bg-white dark:bg-slate-800 border-2 border-emerald-500 rounded-3xl overflow-hidden mb-12 shadow-2xl animate-pulse-once flex flex-col" id="successContainer">
    
    <div class="bg-emerald-50 dark:bg-emerald-900/30 p-6 border-b border-emerald-100 dark:border-emerald-800 flex flex-col sm:flex-row justify-between items-center gap-4">
        <div>
            <h2 class="text-xl font-black text-emerald-800 dark:text-emerald-400 mb-1">🎉 <?php echo count($purchasedConfigs); ?> اشتراک با موفقیت صادر شد</h2>
            <p class="text-sm text-emerald-700 dark:text-emerald-500 font-bold">رسید خرید و اطلاعات اتصال در زیر قابل مشاهده است.</p>
        </div>
        <div class="flex gap-2">
            <button onclick="downloadConfigsTxt(this)" class="bg-emerald-600 hover:bg-emerald-700 text-white font-bold py-2.5 px-4 rounded-xl shadow transition text-sm flex items-center gap-2">📄 TXT</button>
            <button onclick="downloadConfigsExcel(this)" class="bg-blue-600 hover:bg-blue-700 text-white font-bold py-2.5 px-4 rounded-xl shadow transition text-sm flex items-center gap-2">📊 Excel</button>
        </div>
    </div>

    <div class="p-6 overflow-x-auto border-b border-gray-100 dark:border-slate-700 bg-white dark:bg-slate-800">
        <table class="w-full text-sm text-left text-gray-600 dark:text-gray-300" dir="ltr">
            <thead class="bg-emerald-100 dark:bg-emerald-900/50 text-emerald-800 dark:text-emerald-400">
                <tr>
                    <th class="px-4 py-3 rounded-tl-xl font-bold">Username</th>
                    <th class="px-4 py-3 font-bold">Subscription Link (Click to Copy)</th>
                    <th class="px-4 py-3 text-center rounded-tr-xl font-bold">Actions</th>
                </tr>
            </thead>
            <tbody class="divide-y divide-emerald-50 dark:divide-emerald-900/20">
                <?php foreach($purchasedConfigs as $c): ?>
                <tr class="hover:bg-emerald-50 dark:hover:bg-slate-700 transition">
                    <td class="px-4 py-3 font-black text-gray-800 dark:text-gray-100"><?php echo htmlspecialchars($c['account_username']); ?></td>
                    <td class="px-4 py-3">
                        <div class="flex items-center gap-2 cursor-pointer group w-fit" onclick="copyTableLinkNative('<?php echo htmlspecialchars($c['config_link']); ?>', this)">
                            <span class="truncate max-w-[250px] md:max-w-[450px] inline-block font-mono text-xs text-blue-600 dark:text-blue-400"><?php echo htmlspecialchars($c['config_link']); ?></span>
                            <span class="copy-badge opacity-0 group-hover:opacity-100 transition text-emerald-600 dark:text-emerald-400 text-xs bg-emerald-100 dark:bg-emerald-900 px-2 py-1 rounded font-bold">Copy</span>
                        </div>
                    </td>
                    <td class="px-4 py-3">
                        <div class="flex items-center justify-center gap-2">
                           <button type="button" onclick="copyRowConfigs('<?php echo htmlspecialchars($c['config_link']); ?>', '<?php echo $targetServerId; ?>', this)" class="text-lg hover:scale-110 transition-transform bg-blue-50 text-blue-600 dark:bg-blue-900/30 dark:text-blue-400 p-1.5 rounded-lg border border-blue-100 dark:border-blue-800" title="کپی لینک ساب و تمام کانفیگ‌ها">📋</button>
                           <button type="button" onclick="if(typeof showQRModal === 'function') showQRModal('<?php echo htmlspecialchars($c['config_link']); ?>', '<?php echo htmlspecialchars($c['account_username']); ?>')" class="text-lg hover:scale-110 transition-transform bg-gray-100 dark:bg-slate-700 p-1.5 rounded-lg border border-gray-200 dark:border-slate-600" title="نمایش بارکد ساب">📱</button>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>

    <?php if(count($purchasedConfigs) == 1): 
        $singleUser = $purchasedConfigs[0]['account_username'];
    ?>
        <div class="bg-[#f8fafc] dark:bg-[#0f172a] relative min-h-[600px] p-6 md:p-10" id="live_sub_dashboard">
            <div id="sub_loading" class="absolute inset-0 bg-white/90 dark:bg-slate-900/90 z-30 flex flex-col items-center justify-center transition-opacity">
                <div class="animate-spin w-10 h-10 border-4 border-blue-600 border-t-transparent rounded-full mb-4"></div>
                <p class="font-bold text-gray-500 dark:text-gray-400 animate-pulse text-sm" id="sub_loading_text">در حال ارتباط با سرور اصلی...</p>
            </div>

            <div class="flex justify-between items-center mb-10">
                <div class="text-right">
                    <h3 class="text-3xl font-black text-gray-900 dark:text-white mb-2">داشبورد کاربری</h3>
                    <div class="flex items-center gap-3">
                        <span id="sub_online_status" class="text-emerald-500 text-xs font-bold flex items-center gap-1.5">آنلاین <span class="w-2 h-2 bg-emerald-500 rounded-full animate-pulse"></span></span>
                        <span class="text-gray-300 dark:text-slate-700">|</span>
                        <span id="sub_username_display" onclick="copyTextNative('<?php echo $singleUser; ?>', this)" class="text-gray-600 dark:text-slate-400 font-black cursor-pointer hover:text-blue-500 transition" dir="ltr">@<?php echo $singleUser; ?></span>
                    </div>
                </div>
            </div>

            <div class="grid grid-cols-1 lg:grid-cols-12 gap-6 mb-10">
                <div id="sub_status_card" class="lg:col-span-8 bg-[#eafbf1] dark:bg-[#064e3b]/50 border border-[#d1f4e0] dark:border-[#065f46] rounded-[2.5rem] p-8 flex flex-col justify-between min-h-[300px]">
                    <div class="flex justify-between items-start">
                        <div>
                            <h2 id="sub_status_text" class="text-5xl font-black text-[#10b981] mb-2">فعال</h2>
                            <span class="text-xs font-bold text-gray-400 dark:text-emerald-200/50 block pr-1">وضعیت اشتراک</span>
                        </div>
                        <div class="text-center">
                            <span class="block text-3xl mb-1 text-gray-400 font-light">∞</span>
                            <span class="font-black text-gray-800 dark:text-white">نامحدود</span>
                        </div>
                    </div>
                    <div class="flex justify-between items-end">
                        <div class="flex flex-col items-center">
                            <div class="sub-pie-wrap" id="sub_pie_chart">
                                <div class="sub-pie-inside" id="sub_percent_val">0%</div>
                            </div>
                            <span class="text-[10px] font-bold text-gray-400 mt-3">مصرف شده</span>
                        </div>
                        <div class="space-y-4 w-full max-w-[240px]">
                            <div class="flex justify-between text-sm font-bold"><span class="text-gray-400">مصرف شده:</span><span id="sub_used_val" class="dark:text-white" dir="ltr">0 MB</span></div>
                            <div class="flex justify-between text-sm font-bold"><span class="text-gray-400">حجم کل:</span><span id="sub_limit_val" class="dark:text-white" dir="ltr">0 GB</span></div>
                            <div class="flex justify-between text-sm font-black pt-2 border-t border-emerald-200 dark:border-emerald-800"><span class="text-gray-500">باقی‌مانده:</span><span id="sub_remain_val" class="text-[#10b981]" dir="ltr">0 MB</span></div>
                        </div>
                    </div>
                </div>

                <div class="lg:col-span-4 flex flex-col gap-4">
                    <div class="bg-white dark:bg-slate-800 rounded-3xl p-6 shadow-sm border border-gray-100 dark:border-slate-700 flex justify-between items-center flex-1">
                        <span class="text-xs font-bold text-gray-400">ترافیک کل</span>
                        <span id="sub_total_stat" class="text-2xl font-black font-mono dark:text-white" dir="ltr">0 MB</span>
                    </div>
                    <div class="bg-white dark:bg-slate-800 rounded-3xl p-6 shadow-sm border border-gray-100 dark:border-slate-700 flex justify-between items-center flex-1">
                        <span class="text-xs font-bold text-gray-400">تاریخ انقضا</span>
                        <span id="sub_expire_stat" class="text-xl font-black font-mono dark:text-white" dir="ltr">∞</span>
                    </div>
                    <div class="bg-white dark:bg-slate-800 rounded-3xl p-6 shadow-sm border border-gray-100 dark:border-slate-700 flex justify-between items-center flex-1">
                        <span class="text-xs font-bold text-gray-400">آخرین اتصال</span>
                        <span id="sub_last_stat" class="text-xs font-bold text-emerald-500" dir="ltr">--</span>
                    </div>
                </div>
            </div>

            <div class="grid grid-cols-1 lg:grid-cols-12 gap-8">
                <div class="lg:col-span-7">
                    <div class="flex justify-between items-center mb-6 px-1">
                        <h4 class="font-black text-gray-800 dark:text-white flex items-center gap-2">لینک‌های اتصال</h4>
                        <button onclick="copyAllSubConfigs(this)" class="bg-[#3b5998] text-white text-[10px] font-black px-4 py-2 rounded-xl shadow-lg hover:bg-blue-700 transition flex items-center justify-center gap-2 min-w-[140px]">کپی همه کانفیگ‌ها 📋</button>
                    </div>
                    <div id="sub_configs_container" class="space-y-3 max-h-[400px] overflow-y-auto custom-scrollbar pe-2"></div>
                </div>
                <div class="lg:col-span-5 bg-white dark:bg-slate-800 rounded-[2rem] p-6 shadow-sm border border-gray-100 dark:border-slate-700 flex flex-col">
                    <h4 class="font-black text-gray-800 dark:text-white text-sm mb-6">آمار مصرف</h4>
                    <div class="flex flex-wrap justify-end gap-1.5 mb-6" dir="ltr">
                        <?php foreach(['90d','30d','7d','24h','12h'] as $time): ?>
                            <button class="px-2.5 py-1 text-[9px] font-bold rounded-lg <?php echo $time=='12h'?'bg-blue-600 text-white':'bg-gray-100 text-gray-400'; ?>"><?php echo $time; ?></button>
                        <?php endforeach; ?>
                    </div>
                    <div class="flex-1 min-h-[250px]"><canvas id="subChartCanvas"></canvas></div>
                </div>
            </div>
        </div>

        <style>
            .sub-pie-wrap { width: 120px; height: 120px; background: #c6f6d5; border-radius: 50%; position: relative; transition: background 0.5s; }
            .sub-pie-inside { width: 96px; height: 96px; background: #eafbf1; border-radius: 50%; position: absolute; top: 12px; left: 12px; display: flex; align-items: center; justify-content: center; font-weight: 900; font-size: 1.5rem; color: #1f2937; }
            html.dark .sub-pie-wrap { background: #065f46; }
            html.dark .sub-pie-inside { background: #064e3b; color: #fff; }
        </style>

        <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <?php endif; ?>
</div>

<script>
    // موتور استخراج هوشمند JSON (Safe Fetcher)
    async function apiCall(action, params) {
        let url = `store.php?store_ajax=${action}`;
        for(let key in params) { url += `&${key}=${encodeURIComponent(params[key])}`; }
        
        const res = await fetch(url);
        const text = await res.text();
        
        try {
            return JSON.parse(text);
        } catch(e) {
            const match = text.match(/\{[\s\S]*\}|\[[\s\S]*\]/);
            if (match) {
                try { return JSON.parse(match[0]); } catch(err) {}
            }
            throw new Error("پاسخ سرور نامعتبر است.");
        }
    }

    const exportConfigsArr = <?php echo json_encode($exportData); ?>;
    const globalServerId = '<?php echo $targetServerId; ?>';

    window.downloadConfigsTxt = async function(btn) {
        let oldHtml = btn.innerHTML;
        btn.innerHTML = '<span class="animate-spin inline-block w-4 h-4 border-2 border-white border-t-transparent rounded-full"></span> دریافت...';
        btn.disabled = true;
        let txtContent = "";
        
        for (let item of exportConfigsArr) {
            txtContent += "========================================\n";
            txtContent += "Username: " + item.username + "\n";
            txtContent += "Sub Link: " + item.sub_link + "\n";
            txtContent += "Configs:\n";
            
            if (item.sub_link && item.sub_link !== 'null' && item.sub_link.trim() !== '') {
                try {
                    let links = await apiCall('get_sub_links', { sub_url: item.sub_link, server_id: globalServerId });
                    if(Array.isArray(links) && links.length > 0) txtContent += links.join("\n") + "\n";
                    else txtContent += "هیچ کانفیگی یافت نشد.\n";
                } catch(e) { txtContent += "خطا در دریافت کانفیگ‌ها.\n"; }
            } else { txtContent += "لینک اتصال موجود نیست.\n"; }
            txtContent += "\n";
        }
        
        let blob = new Blob([txtContent], { type: "text/plain;charset=utf-8" });
        let link = document.createElement("a");
        link.href = URL.createObjectURL(blob);
        link.download = "vpnet_configs_" + new Date().getTime() + ".txt";
        link.click();
        
        btn.innerHTML = '✔ دانلود شد';
        setTimeout(() => { btn.innerHTML = oldHtml; btn.disabled = false; }, 2000);
    };

    window.downloadConfigsExcel = async function(btn) {
        let oldHtml = btn.innerHTML;
        btn.innerHTML = '<span class="animate-spin inline-block w-4 h-4 border-2 border-white border-t-transparent rounded-full"></span> دریافت...';
        btn.disabled = true;
        let csvContent = "\uFEFFUsername,Sub Link,Configs\n"; 
        
        for (let item of exportConfigsArr) {
            let configsStr = "";
            if (item.sub_link && item.sub_link !== 'null' && item.sub_link.trim() !== '') {
                try {
                    let links = await apiCall('get_sub_links', { sub_url: item.sub_link, server_id: globalServerId });
                    if(Array.isArray(links) && links.length > 0) configsStr = links.join(" | "); 
                } catch(e) {}
            }
            let escapedLinks = configsStr.replace(/"/g, '""');
            csvContent += `"${item.username}","${item.sub_link}","${escapedLinks}"\n`;
        }
        
        let blob = new Blob([csvContent], { type: "text/csv;charset=utf-8" });
        let link = document.createElement("a");
        link.href = URL.createObjectURL(blob);
        link.download = "vpnet_configs_" + new Date().getTime() + ".csv";
        link.click();
        
        btn.innerHTML = '✔ دانلود شد';
        setTimeout(() => { btn.innerHTML = oldHtml; btn.disabled = false; }, 2000);
    };

    window.copyRowConfigs = async function(subUrl, serverId, btn) {
        if (!subUrl || subUrl === 'null' || subUrl.trim() === '') { alert('لینک ساب موجود نیست.'); return; }
        let originalHtml = btn.innerHTML;
        btn.innerHTML = '<span class="animate-spin inline-block w-4 h-4 border-2 border-blue-600 border-t-transparent rounded-full"></span>';
        btn.disabled = true;
        try {
            let links = await apiCall('get_sub_links', { sub_url: subUrl, server_id: serverId });
            let allText = "Sub Link: " + subUrl + '\n\n';
            if(Array.isArray(links) && links.length > 0) allText += links.join('\n');
            await navigator.clipboard.writeText(allText);
            btn.innerHTML = '<span class="text-emerald-500 text-sm">✔</span>';
        } catch (e) {
            btn.innerHTML = '<span class="text-rose-500 text-sm">❌</span>';
        }
        setTimeout(() => { btn.innerHTML = originalHtml; btn.disabled = false; }, 2000);
    };

    <?php if(count($purchasedConfigs) == 1): ?>
    (function() {
        const user = '<?php echo addslashes($singleUser); ?>';
        const srv = '<?php echo $targetServerId; ?>';
        let fullLinks = [];
        let loadedSubUrl = '';

        function formatSize(b) {
            if (!b || b <= 0) return '0 MB';
            const k = 1024, i = Math.floor(Math.log(b) / Math.log(k));
            return parseFloat((b / Math.pow(k, i)).toFixed(2)) + ' ' + ['B', 'KB', 'MB', 'GB', 'TB'][i];
        }

        async function initLiveDashboard() {
            try {
                // تاخیر کوتاه برای ثبت کامل در سرور اصلی
                await new Promise(resolve => setTimeout(resolve, 800));
                
                const data = await apiCall('get_user', { username: user, server_id: srv });
                
                if (data && data.error) {
                    throw new Error(data.error); // پرینت دقیق ارور cURL یا سرور
                }

                if (data && (data.code === 200 || data.data)) {
                    const u = data.data || data;
                    document.getElementById('sub_loading').style.opacity = '0';
                    setTimeout(() => document.getElementById('sub_loading')?.remove(), 500);

                    document.getElementById('sub_limit_val').innerText = u.data_limit > 0 ? formatSize(u.data_limit) : '∞';
                    document.getElementById('sub_used_val').innerText = formatSize(u.used_traffic);
                    document.getElementById('sub_total_stat').innerText = formatSize(u.used_traffic);
                    let remain = u.data_limit - u.used_traffic;
                    document.getElementById('sub_remain_val').innerText = u.data_limit > 0 ? formatSize(remain > 0 ? remain : 0) : 'نامحدود';
                    
                    let p = u.data_limit > 0 ? Math.round((u.used_traffic / u.data_limit) * 100) : 0;
                    document.getElementById('sub_percent_val').innerText = p + '%';
                    document.getElementById('sub_pie_chart').style.background = `conic-gradient(#10b981 ${p * 3.6}deg, transparent 0)`;

                    if(u.expire) {
                        let dt = new Date(u.expire).toLocaleDateString('fa-IR');
                        document.getElementById('sub_expire_stat').innerText = dt;
                        document.getElementById('sub_expire_stat').classList.replace('text-xl', 'text-sm');
                    }

                    if(u.subscription_url) {
                        loadedSubUrl = u.subscription_url;
                        try {
                            fullLinks = await apiCall('get_sub_links', { sub_url: u.subscription_url, server_id: srv });
                            renderConfigs(fullLinks, u.subscription_url);
                        } catch(linkErr) {
                            document.getElementById('sub_configs_container').innerHTML = '<div class="text-xs text-rose-500 font-bold p-3">خطا در پردازش لینک‌ها.</div>';
                        }
                    } else {
                        document.getElementById('sub_configs_container').innerHTML = '<div class="text-xs text-amber-500 font-bold p-3">بدون لینک اختصاصی.</div>';
                    }
                    if (typeof Chart !== 'undefined') { initChart(); }
                } else { 
                    throw new Error('ساختار دیتای دریافتی نامعتبر است.'); 
                }
            } catch(e) { 
                let errEl = document.getElementById('sub_loading_text');
                if(errEl) errEl.innerText = '❌ ' + e.message; 
            }
        }

        function renderConfigs(links, subUrl) {
            let html = '';
            if(subUrl) html += createRow('SUB', 'Subscription Link', subUrl, true);
            if(Array.isArray(links)) {
                links.forEach(l => {
                    let type = l.split('://')[0].toUpperCase();
                    let name = decodeURIComponent(l.split('#')[1] || 'Config');
                    html += createRow(type, name, l);
                });
            }
            document.getElementById('sub_configs_container').innerHTML = html;
        }

        function createRow(type, name, link) {
            return `
            <div class="bg-white dark:bg-slate-800 border border-gray-100 dark:border-slate-700 rounded-2xl p-4 flex justify-between items-center shadow-sm">
                <div class="flex items-center gap-3">
                    <span class="bg-[#336699] text-white text-[9px] font-black px-2 py-1 rounded uppercase">${type}</span>
                    <span class="text-[11px] font-bold text-gray-700 dark:text-gray-300 truncate max-w-[180px]" dir="ltr">${name}</span>
                </div>
                <div class="flex gap-1.5">
                    <button onclick="if(typeof showQRModal === 'function') showQRModal('${link}', '${name}')" class="w-8 h-8 flex items-center justify-center bg-gray-50 dark:bg-slate-700 rounded-xl text-gray-400 hover:text-blue-500 transition">📱</button>
                    <button onclick="copyTextNative('${link}', this)" class="w-8 h-8 flex items-center justify-center bg-gray-50 dark:bg-slate-700 rounded-xl text-gray-400 hover:text-blue-500 transition">📋</button>
                </div>
            </div>`;
        }

        function initChart() {
            const ctx = document.getElementById('subChartCanvas');
            if(!ctx) return;
            new Chart(ctx.getContext('2d'), {
                type: 'line', data: { labels: ['', '', '', '', '', '', 'Now'], datasets: [{ data: [0, 2, 5, 3, 8, 12, 10], borderColor: '#3b82f6', borderWidth: 3, pointRadius: 0, fill: true, backgroundColor: 'rgba(59, 130, 246, 0.05)', tension: 0.4 }] },
                options: { responsive: true, maintainAspectRatio: false, plugins: { legend: false }, scales: { y: { display: false }, x: { grid: { display: false }, ticks: { font: { size: 9 } } } } }
            });
        }

        window.copyAllSubConfigs = (btn) => {
            let allText = "";
            if(loadedSubUrl) allText += "Sub Link: " + loadedSubUrl + '\n\n';
            if(fullLinks.length) allText += fullLinks.join('\n');
            
            if(allText) { 
                navigator.clipboard.writeText(allText).then(() => {
                    let old = btn.innerHTML;
                    btn.innerHTML = 'کپی شد! ✔';
                    btn.classList.replace('bg-[#3b5998]', 'bg-emerald-600');
                    setTimeout(() => { btn.innerHTML = old; btn.classList.replace('bg-emerald-600', 'bg-[#3b5998]'); }, 2000);
                });
            } else {
                let old = btn.innerHTML; btn.innerHTML = 'خالی ❌';
                setTimeout(() => { btn.innerHTML = old; }, 2000);
            }
        };

        initLiveDashboard();
    })();
    <?php endif; ?>

    window.copyTextNative = function(t, btn) {
        navigator.clipboard.writeText(t).then(() => {
            let old = btn.innerHTML; btn.innerHTML = '<span class="text-emerald-500 text-[10px]">✔</span>';
            setTimeout(() => btn.innerHTML = old, 2000);
        });
    }

    window.copyTableLinkNative = function(t, el) {
        navigator.clipboard.writeText(t).then(() => {
            let b = el.querySelector('.copy-badge');
            if(b) { 
                b.innerText = 'کپی شد!'; b.classList.add('opacity-100', 'bg-emerald-500', 'text-white'); b.classList.remove('text-emerald-600', 'bg-emerald-100');
                setTimeout(() => { b.innerText = 'Copy'; b.classList.remove('opacity-100', 'bg-emerald-500', 'text-white'); b.classList.add('text-emerald-600', 'bg-emerald-100'); }, 2000); 
            }
        });
    }
</script>

<style>
    @keyframes pulse-once { 0% { transform: scale(0.98); opacity: 0.8; } 50% { transform: scale(1.02); opacity: 1; } 100% { transform: scale(1); opacity: 1; } }
    .animate-pulse-once { animation: pulse-once 0.5s ease-out; }
</style>