<?php
// modules/view_config.php
require_once '../config/db.php';
// نکته: در این صفحه تابع checkLogin() قرار داده نشده تا مشتری نهایی بتواند لینک را ببیند.

$invId = isset($_GET['inv_id']) ? (int)$_GET['inv_id'] : 0;

// دریافت لینک ساب از دیتابیس
$stmt = $pdo->prepare("SELECT * FROM inventory WHERE id = ? AND status = 'sold'");
$stmt->execute([$invId]);
$config = $stmt->fetch();

if (!$config) {
    die("
    <div style='font-family: tahoma; text-align: center; margin-top: 100px; direction: rtl;'>
        <h2 style='color: #dc2626;'>خطا: اشتراک یافت نشد!</h2>
        <p>این اشتراک وجود ندارد یا هنوز فروخته نشده است.</p>
    </div>");
}

$subUrl = $config['config_link'];
$accountName = $config['account_username'];

// ==========================================
// تابع استخراج لایو اطلاعات از لینک ساب
// ==========================================
function fetchSubData($url) {
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HEADER, true); // دریافت هدرها الزامی است
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    $response = curl_exec($ch);
    $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
    $header = substr($response, 0, $header_size);
    $body = substr($response, $header_size);
    curl_close($ch);

    // ۱. پردازش هدرها برای حجم و زمان
    $upload = 0; $download = 0; $total = 0; $expire = 0;
    if (preg_match('/subscription-userinfo:\s*(.+)/i', $header, $matches)) {
        $info = $matches[1];
        if (preg_match('/upload=(\d+)/i', $info, $m)) $upload = (int)$m[1];
        if (preg_match('/download=(\d+)/i', $info, $m)) $download = (int)$m[1];
        if (preg_match('/total=(\d+)/i', $info, $m)) $total = (int)$m[1];
        if (preg_match('/expire=(\d+)/i', $info, $m)) $expire = (int)$m[1];
    }

    // ۲. پردازش بادی برای استخراج کانفیگ‌ها
    $configsList = [];
    $decodedBody = base64_decode(trim($body));
    if ($decodedBody) {
        $lines = explode("\n", $decodedBody);
        foreach ($lines as $line) {
            $line = trim($line);
            if (empty($line)) continue;
            
            // استخراج نام کانفیگ (بعد از کاراکتر #)
            $name = "کانفیگ اتصال";
            $hashPos = strpos($line, '#');
            if ($hashPos !== false) {
                $name = urldecode(substr($line, $hashPos + 1));
            }
            $configsList[] = ['link' => $line, 'name' => $name];
        }
    }

    return [
        'upload' => $upload, 
        'download' => $download, 
        'total' => $total, 
        'expire' => $expire, 
        'configs' => $configsList
    ];
}

$subData = fetchSubData($subUrl);

// محاسبات
$usedBytes = $subData['upload'] + $subData['download'];
$totalBytes = $subData['total'];
$expireTime = $subData['expire'];

// توابع تبدیل واحد
function formatBytes($bytes) {
    if ($bytes == 0) return "0 B";
    $k = 1024;
    $sizes = ["B", "KB", "MB", "GB", "TB"];
    $i = floor(log($bytes) / log($k));
    return round($bytes / pow($k, $i), 2) . " " . $sizes[$i];
}

$usedFormatted = formatBytes($usedBytes);
$totalFormatted = $totalBytes > 0 ? formatBytes($totalBytes) : "نامحدود";
$percentUsage = $totalBytes > 0 ? min(round(($usedBytes / $totalBytes) * 100), 100) : 0;

$isExpired = false;
$daysLeft = 0;
if ($expireTime > 0) {
    $now = time();
    if ($now > $expireTime) {
        $isExpired = true;
    } else {
        $daysLeft = ceil(($expireTime - $now) / 86400);
    }
}
$expireDateString = $expireTime > 0 ? date('Y-m-d', $expireTime) : "نامحدود";

?>
<!DOCTYPE html>
<html lang="fa" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>وضعیت اشتراک: <?php echo htmlspecialchars($accountName); ?></title>
    <script src="/vpnet-panel/assets/js/tailwindcss.js"></script>
    <link href="/vpnet-panel/assets/css/Vazirmatn-font-face.css" rel="stylesheet">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js"></script>
    <style>
        body { font-family: 'Vazirmatn', sans-serif; background-color: #f3f4f6; }
        .glass-card { background: rgba(255, 255, 255, 0.9); backdrop-filter: blur(10px); }
        .hide-scroll::-webkit-scrollbar { display: none; }
    </style>
</head>
<body class="text-gray-800 pb-12">

    <!-- هدر صفحه -->
    <div class="bg-blue-600 text-white pt-8 pb-16 px-4 text-center rounded-b-[3rem] shadow-md relative overflow-hidden">
        <div class="absolute opacity-10 text-9xl -top-10 -right-10">🛡️</div>
        <div class="relative z-10">
            <h1 class="text-2xl font-black mb-2">اطلاعات اشتراک (ساب)</h1>
            <p class="font-mono bg-blue-800/50 inline-block px-4 py-1.5 rounded-full text-sm font-bold shadow-inner" dir="ltr"><?php echo htmlspecialchars($accountName); ?></p>
        </div>
    </div>

    <div class="max-w-3xl mx-auto px-4 -mt-10 relative z-20 space-y-6">

        <!-- کارت کپی لینک اصلی -->
        <div class="glass-card rounded-3xl p-6 shadow-sm border border-gray-100 text-center flex flex-col items-center">
            <div class="w-12 h-12 bg-blue-100 text-blue-600 rounded-full flex items-center justify-center text-xl mb-3">🔗</div>
            <h2 class="font-bold text-gray-700 mb-2">لینک ساب (Subscription Link)</h2>
            <p class="text-xs text-gray-500 mb-4">این لینک را کپی کرده و در نرم‌افزار خود وارد کنید (Import).</p>
            <button onclick="copyToClipboard('<?php echo htmlspecialchars($subUrl); ?>', this)" class="w-full bg-blue-600 hover:bg-blue-700 text-white font-bold py-3.5 rounded-xl transition shadow-md flex justify-center items-center gap-2">
                <span>📋</span> کپی لینک ساب
            </button>
        </div>

        <!-- کارت‌های آمار مصرف -->
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            <!-- حجم -->
            <div class="glass-card rounded-3xl p-6 shadow-sm border border-gray-100 relative overflow-hidden">
                <div class="flex justify-between items-center mb-4">
                    <h3 class="font-bold text-gray-700 flex items-center gap-2"><span class="w-2 h-2 rounded-full bg-purple-500"></span> ترافیک مصرفی</h3>
                    <span class="text-xs font-black bg-gray-100 px-2 py-1 rounded-md text-gray-600"><?php echo $percentUsage; ?>%</span>
                </div>
                
                <div class="w-full bg-gray-100 rounded-full h-3.5 mb-4 shadow-inner overflow-hidden">
                    <div class="bg-gradient-to-r from-purple-500 to-indigo-600 h-3.5 rounded-full transition-all duration-1000" style="width: <?php echo $percentUsage; ?>%"></div>
                </div>
                
                <div class="flex justify-between text-sm">
                    <div><span class="text-gray-400 text-xs block">مصرف شده</span><strong class="text-gray-800" dir="ltr"><?php echo $usedFormatted; ?></strong></div>
                    <div class="text-left"><span class="text-gray-400 text-xs block">حد کل</span><strong class="text-gray-800" dir="ltr"><?php echo $totalFormatted; ?></strong></div>
                </div>
            </div>

            <!-- زمان -->
            <div class="glass-card rounded-3xl p-6 shadow-sm border border-gray-100 relative overflow-hidden">
                <div class="flex justify-between items-center mb-4">
                    <h3 class="font-bold text-gray-700 flex items-center gap-2">
                        <span class="w-2 h-2 rounded-full <?php echo $isExpired ? 'bg-red-500' : 'bg-emerald-500'; ?>"></span> 
                        وضعیت اعتبار
                    </h3>
                    <span class="text-xs font-black <?php echo $isExpired ? 'bg-red-50 text-red-600' : 'bg-emerald-50 text-emerald-600'; ?> px-2 py-1 rounded-md">
                        <?php echo $isExpired ? 'منقضی شده' : 'فعال'; ?>
                    </span>
                </div>
                
                <div class="text-center py-2">
                    <?php if($expireTime > 0): ?>
                        <p class="text-3xl font-black <?php echo $isExpired ? 'text-red-500' : 'text-emerald-500'; ?>" dir="ltr">
                            <?php echo $isExpired ? 'Expired' : $daysLeft . ' <span class="text-sm">Days Left</span>'; ?>
                        </p>
                        <p class="text-xs text-gray-400 mt-2" dir="ltr">Exp: <?php echo $expireDateString; ?></p>
                    <?php else: ?>
                        <p class="text-3xl font-black text-emerald-500">نامحدود</p>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- لیست کانفیگ‌های تکی -->
        <div class="glass-card rounded-3xl p-6 shadow-sm border border-gray-100">
            <h2 class="font-bold text-gray-800 mb-4 flex items-center gap-2">
                <span class="text-xl">⚙️</span> لیست کانفیگ‌ها به صورت تکی
            </h2>
            <?php if(empty($subData['configs'])): ?>
                <div class="bg-amber-50 text-amber-600 p-4 rounded-xl text-sm font-bold text-center border border-amber-200">کانفیگی در این ساب یافت نشد.</div>
            <?php else: ?>
                <div class="space-y-3 max-h-80 overflow-y-auto hide-scroll pr-1">
                    <?php foreach($subData['configs'] as $idx => $cfg): ?>
                        <div class="bg-gray-50 border border-gray-200 p-4 rounded-2xl flex items-center justify-between hover:bg-blue-50 transition group">
                            <div class="overflow-hidden mr-3">
                                <p class="text-sm font-bold text-gray-700 truncate"><?php echo htmlspecialchars($cfg['name']); ?></p>
                                <p class="text-[10px] text-gray-400 font-mono truncate mt-1" dir="ltr"><?php echo substr(htmlspecialchars($cfg['link']), 0, 30); ?>...</p>
                            </div>
                            <div class="flex gap-2 shrink-0">
                                <button onclick="openQR('<?php echo htmlspecialchars($cfg['link']); ?>')" class="w-9 h-9 bg-white border border-gray-200 text-gray-600 rounded-xl flex items-center justify-center hover:text-blue-600 hover:border-blue-300 shadow-sm transition" title="بارکد (QR)">
                                    📱
                                </button>
                                <button onclick="copyToClipboard('<?php echo htmlspecialchars($cfg['link']); ?>', this, true)" class="w-9 h-9 bg-white border border-gray-200 text-gray-600 rounded-xl flex items-center justify-center hover:text-blue-600 hover:border-blue-300 shadow-sm transition" title="کپی کانفیگ">
                                    📋
                                </button>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </div>

        <!-- نرم‌افزارهای پیشنهادی -->
        <div class="glass-card rounded-3xl p-6 shadow-sm border border-gray-100">
            <h2 class="font-bold text-gray-800 mb-4 flex items-center gap-2"><span class="text-xl">📱</span> نرم‌افزارهای پیشنهادی اتصال</h2>
            <div class="grid grid-cols-2 sm:grid-cols-4 gap-4">
                <a href="https://play.google.com/store/apps/details?id=com.v2ray.ang" target="_blank" class="block bg-gray-50 border border-gray-200 p-4 rounded-2xl text-center hover:bg-gray-100 transition">
                    <div class="text-2xl mb-2">🤖</div>
                    <div class="text-xs font-bold text-gray-700">v2rayNG</div>
                    <div class="text-[10px] text-gray-400">اندروید</div>
                </a>
                <a href="https://apps.apple.com/us/app/v2box-v2ray-client/id6446814690" target="_blank" class="block bg-gray-50 border border-gray-200 p-4 rounded-2xl text-center hover:bg-gray-100 transition">
                    <div class="text-2xl mb-2">🍏</div>
                    <div class="text-xs font-bold text-gray-700">V2Box</div>
                    <div class="text-[10px] text-gray-400">آیفون (iOS)</div>
                </a>
                <a href="https://apps.apple.com/us/app/streisand/id6450534064" target="_blank" class="block bg-gray-50 border border-gray-200 p-4 rounded-2xl text-center hover:bg-gray-100 transition">
                    <div class="text-2xl mb-2">🍎</div>
                    <div class="text-xs font-bold text-gray-700">Streisand</div>
                    <div class="text-[10px] text-gray-400">آیفون (iOS)</div>
                </a>
                <a href="https://github.com/hiddify/hiddify-next/releases" target="_blank" class="block bg-gray-50 border border-gray-200 p-4 rounded-2xl text-center hover:bg-gray-100 transition">
                    <div class="text-2xl mb-2">💻</div>
                    <div class="text-xs font-bold text-gray-700">Hiddify</div>
                    <div class="text-[10px] text-gray-400">ویندوز / مک</div>
                </a>
            </div>
        </div>
        
    </div>

    <!-- Modal بارکد -->
    <div id="qrModal" class="fixed inset-0 bg-black/60 backdrop-blur-sm hidden items-center justify-center z-50 transition-opacity opacity-0">
        <div class="bg-white p-6 rounded-3xl shadow-xl max-w-sm w-full mx-4 transform scale-95 transition-transform" id="qrModalContent">
            <div class="flex justify-between items-center mb-4">
                <h3 class="font-bold text-gray-800">اسکن بارکد (QR)</h3>
                <button onclick="closeQR()" class="text-gray-400 hover:text-red-500 text-xl leading-none">&times;</button>
            </div>
            <div id="qrcode" class="flex justify-center bg-white p-4 rounded-xl border border-gray-100"></div>
            <button onclick="closeQR()" class="w-full mt-6 bg-gray-100 text-gray-700 font-bold py-2.5 rounded-xl hover:bg-gray-200 transition">بستن</button>
        </div>
    </div>

    <script>
        // کپی در کلیپ‌بورد
        function copyToClipboard(text, btn, isIcon = false) {
            navigator.clipboard.writeText(text).then(() => {
                const originalHTML = btn.innerHTML;
                if(isIcon) {
                    btn.innerHTML = '✅';
                    btn.classList.add('bg-green-50', 'text-green-600', 'border-green-300');
                } else {
                    btn.innerHTML = '✅ کپی شد!';
                    btn.classList.add('bg-green-500', 'text-white');
                    btn.classList.remove('bg-blue-600');
                }
                
                setTimeout(() => {
                    btn.innerHTML = originalHTML;
                    if(isIcon) {
                        btn.classList.remove('bg-green-50', 'text-green-600', 'border-green-300');
                    } else {
                        btn.classList.add('bg-blue-600');
                        btn.classList.remove('bg-green-500', 'text-white');
                    }
                }, 2000);
            });
        }

        // نمایش مدال QR Code
        const qrModal = document.getElementById('qrModal');
        const qrModalContent = document.getElementById('qrModalContent');
        const qrcodeDiv = document.getElementById('qrcode');
        let qrInstance = null;

        function openQR(link) {
            // پاک کردن بارکد قبلی
            qrcodeDiv.innerHTML = '';
            
            // ساخت بارکد جدید
            qrInstance = new QRCode(qrcodeDiv, {
                text: link,
                width: 200,
                height: 200,
                colorDark : "#1f2937",
                colorLight : "#ffffff",
                correctLevel : QRCode.CorrectLevel.L
            });

            // نمایش با انیمیشن
            qrModal.classList.remove('hidden');
            qrModal.classList.add('flex');
            // تاخیر کوچک برای اعمال ترانزیشن
            setTimeout(() => {
                qrModal.classList.remove('opacity-0');
                qrModalContent.classList.remove('scale-95');
            }, 10);
        }

        function closeQR() {
            qrModal.classList.add('opacity-0');
            qrModalContent.classList.add('scale-95');
            setTimeout(() => {
                qrModal.classList.add('hidden');
                qrModal.classList.remove('flex');
            }, 300); // همگام با زمان ترانزیشن
        }

        // بستن مودال با کلیک بیرون از آن
        qrModal.addEventListener('click', function(e) {
            if (e.target === qrModal) closeQR();
        });
    </script>
</body>
</html>