<?php
// modules/store/widgets/product_grid.php
// جلوگیری از دسترسی مستقیم به فایل
if (basename($_SERVER['PHP_SELF']) == 'product_grid.php') {
    die('Access Denied');
}
?>

<div class="bg-white dark:bg-slate-800 rounded-[2rem] p-8 md:p-10 mb-10 flex flex-col md:flex-row justify-between items-center shadow-sm border border-gray-100 dark:border-slate-700 relative overflow-hidden">
    <div class="absolute -left-10 -top-10 opacity-[0.03] dark:opacity-[0.05] text-9xl pointer-events-none">🛒</div>
    
    <div class="relative z-10 text-center md:text-right mb-6 md:mb-0">
        <h1 class="text-3xl font-black text-gray-900 dark:text-white mb-2 tracking-tight">فروشگاه اشتراک VPNet</h1>
        <p class="text-gray-500 dark:text-gray-400 text-sm font-bold flex items-center justify-center md:justify-start gap-2">
            موجودی کیف پول شما: 
            <span class="text-emerald-600 dark:text-emerald-400 text-lg font-black font-mono tracking-tighter" dir="ltr">
                <?php echo number_format($walletBalance); ?> <span class="text-[10px] font-normal">T</span>
            </span>
        </p>
    </div>
    
    <a href="../wallet.php" class="relative z-10 bg-blue-600 hover:bg-blue-700 text-white font-black px-8 py-3.5 rounded-2xl shadow-lg shadow-blue-600/30 transition-all hover:scale-105 flex items-center gap-2">
        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6"></path></svg>
        شارژ حساب
    </a>
</div>

<div class="flex items-center gap-3 mb-8 px-2">
    <span class="w-8 h-8 bg-gray-100 dark:bg-slate-800 rounded-xl flex items-center justify-center text-xl shadow-sm">📦</span>
    <h2 class="text-xl font-black text-gray-800 dark:text-white">قفسه محصولات به تفکیک طرح</h2>
</div>

<?php if(empty($groupedProducts)): ?>
    <div class="bg-white dark:bg-slate-800 rounded-[2rem] shadow-sm border border-gray-100 dark:border-slate-700 p-16 text-center flex flex-col items-center justify-center">
        <div class="text-7xl mb-6 opacity-20 grayscale">🛒</div>
        <h3 class="text-xl font-black text-gray-600 dark:text-gray-300 mb-2">قفسه فروشگاه خالی است!</h3>
        <p class="text-sm text-gray-400">در حال حاضر هیچ طرحی برای فروش موجود نیست.</p>
    </div>
<?php else: foreach($groupedProducts as $planName => $group): 
    $hex = $group['color'] ?: '#3b82f6';
?>
    <div class="mb-12 bg-white dark:bg-slate-800 rounded-[2rem] shadow-sm border border-gray-100 dark:border-slate-700 overflow-hidden relative transition-colors">
        
        <div class="px-8 py-5 flex flex-col sm:flex-row sm:items-center justify-between gap-4 border-b border-gray-50 dark:border-slate-700/50" style="background-color: <?php echo $hex; ?>08; border-right: 6px solid <?php echo $hex; ?>">
            <div class="flex items-center gap-3">
                <span class="w-3 h-3 rounded-full shadow-sm animate-pulse" style="background-color: <?php echo $hex; ?>"></span>
                <h3 class="text-2xl font-black tracking-tight" style="color: <?php echo $hex; ?>"><?php echo htmlspecialchars($planName); ?></h3>
            </div>
            
            <?php if($group['has_timer'] && !empty($group['timer_end'])): ?>
                <div class="flex items-center gap-2 bg-rose-50 dark:bg-rose-900/20 text-rose-600 dark:text-rose-400 px-4 py-2 rounded-xl border border-rose-100 dark:border-rose-800/50 shadow-sm">
                    <svg class="w-5 h-5 animate-pulse" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>
                    <span class="text-xs font-bold hidden md:inline">مهلت جشنواره:</span>
                    <span class="store-plan-timer font-mono text-sm font-black tracking-wider" data-target="<?php echo date('Y-m-d\TH:i:s', strtotime($group['timer_end'])); ?>">--:--:--</span>
                </div>
            <?php endif; ?>
        </div>
        
        <div class="p-6 md:p-8 grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            <?php foreach($group['items'] as $p): 
                $volume = (float)$p['volume'];
                $volumeUnit = $p['volume_unit'] ?? 'GB';
                $availableCount = (int)$p['available_count'];
                
                $isZeroStock = ($availableCount === 0);
                $isLowStock = ($availableCount > 0 && $availableCount <= 5);
                
                $boxBorderColor = $hex . '30'; // شفافیت کمتر برای ظاهر مدرن‌تر
                $boxBgClass = "bg-white dark:bg-slate-800";
                $stockBadgeClass = "bg-gray-100 dark:bg-slate-700 text-gray-600 dark:text-gray-400";
                
                if ($isZeroStock) {
                    $boxBorderColor = "#fca5a5"; 
                    $boxBgClass = "bg-rose-50/50 dark:bg-rose-900/10 grayscale-[40%]";
                    $stockBadgeClass = "bg-rose-100 dark:bg-rose-900/50 text-rose-700 dark:text-rose-400 font-black";
                } elseif ($isLowStock) {
                    $boxBorderColor = "#fcd34d"; 
                    $boxBgClass = "bg-amber-50/30 dark:bg-amber-900/10";
                    $stockBadgeClass = "bg-amber-100 dark:bg-amber-900/50 text-amber-700 dark:text-amber-400 font-black animate-pulse";
                }

                $volumeForPrice = ($volumeUnit === 'MB') ? ($volume / 1024) : $volume;
                $basePrice = $volumeForPrice * (int)$p['cost_price'];
                $discount = ($basePrice * (int)$p['discount_percent']) / 100;
                $finalPrice = $basePrice - $discount;
                $retailTotal = $volumeForPrice * (int)$p['retail_price'];
                $cardId = md5($planName . $volume . $volumeUnit);
            ?>
                <div class="rounded-3xl p-6 relative hover:shadow-xl transition-all duration-300 flex flex-col justify-between border <?php echo $boxBgClass; ?> hover:-translate-y-1" style="border-color: <?php echo $boxBorderColor; ?>;">
                    
                    <?php if($discount > 0): ?>
                        <div class="absolute -top-3 -right-3 text-white text-xs font-black px-4 py-1.5 rounded-2xl shadow-lg transform rotate-3 z-10" style="background-color: <?php echo $hex; ?>">
                            <?php echo $p['discount_percent']; ?>٪ تخفیف
                        </div>
                    <?php endif; ?>

                    <div>
                        <div class="flex justify-between items-center mb-6 border-b border-gray-100 dark:border-slate-700 pb-5">
                            <div class="text-3xl font-black text-gray-900 dark:text-white tracking-tighter" dir="ltr">
                                <?php echo $volume; ?> <span class="text-sm font-bold text-gray-400"><?php echo $volumeUnit; ?></span>
                            </div>
                            <div class="text-[10px] font-bold px-3 py-1.5 rounded-xl <?php echo $stockBadgeClass; ?>">
                                <?php 
                                    if($isZeroStock) echo "❌ ناموجود";
                                    elseif($isLowStock) echo "⚠️ رو به اتمام: " . $availableCount;
                                    else echo "موجودی: " . $availableCount;
                                ?>
                            </div>
                        </div>

                        <div class="space-y-4 mb-6">
                            <div class="flex justify-between items-center text-sm bg-gray-50 dark:bg-slate-700/50 p-3 rounded-xl">
                                <span class="text-gray-500 dark:text-gray-400 font-bold text-xs">ارزش فروش:</span>
                                <span class="font-mono font-bold text-gray-700 dark:text-gray-300" dir="ltr"><?php echo number_format($retailTotal); ?> <span class="text-[10px]">T</span></span>
                            </div>
                            
                            <div class="flex justify-between items-center">
                                <span class="text-gray-700 dark:text-gray-300 font-black text-xs">مبلغ پرداختی شما:</span>
                                <div class="text-left flex flex-col items-end" dir="ltr">
                                    <?php if($discount > 0): ?>
                                        <span class="line-through text-gray-400 text-[10px] decoration-rose-500 decoration-2 mb-0.5"><?php echo number_format($basePrice); ?></span>
                                    <?php endif; ?>
                                    <span class="font-mono text-blue-600 dark:text-blue-400 text-xl font-black tracking-tight" id="base-price-<?php echo $cardId; ?>" data-price="<?php echo $finalPrice; ?>">
                                        <?php echo number_format($finalPrice); ?> <span class="text-xs font-normal">T</span>
                                    </span>
                                </div>
                            </div>
                        </div>
                    </div>

                    <?php if($isZeroStock): ?>
                        <div class="mt-auto">
                            <?php if($isAdmin): ?>
                                <a href="../inventory/inventory.php" class="block w-full text-center bg-rose-50 text-rose-600 font-bold py-3.5 rounded-xl border border-rose-100 transition hover:bg-rose-100 text-sm">شارژ موجودی (انبار)</a>
                            <?php else: ?>
                                <button type="button" disabled class="w-full bg-gray-100 dark:bg-slate-700 text-gray-400 dark:text-gray-500 font-bold py-3.5 rounded-xl cursor-not-allowed text-sm">موجودی به اتمام رسید</button>
                            <?php endif; ?>
                        </div>
                    <?php else: ?>
                        <form method="POST" class="mt-auto" onsubmit="return confirm('آیا از خرید مطمئن هستید؟ مبلغ مستقیماً از کیف پول شما کسر خواهد شد.');">
                            <input type="hidden" name="action" value="buy_config">
                            <input type="hidden" name="plan_name" value="<?php echo htmlspecialchars($planName); ?>">
                            <input type="hidden" name="volume" value="<?php echo $volume; ?>">
                            <input type="hidden" name="volume_unit" value="<?php echo $volumeUnit; ?>">
                            
                            <div class="flex justify-between items-center bg-gray-50 dark:bg-slate-700/50 rounded-xl p-2 mb-4 border border-gray-100 dark:border-slate-600/50">
                                <span class="text-xs font-black text-gray-600 dark:text-gray-300 ml-2">تعداد خرید:</span>
                                <div class="flex items-center gap-1.5" dir="ltr">
                                    <button type="button" class="w-8 h-8 rounded-lg bg-white dark:bg-slate-600 shadow-sm flex items-center justify-center hover:bg-gray-100 dark:hover:bg-slate-500 text-gray-800 dark:text-white transition font-bold" onclick="updateGroupQty('<?php echo $cardId; ?>', -1, <?php echo $availableCount; ?>)">-</button>
                                    <input type="number" name="quantity" id="qty-<?php echo $cardId; ?>" value="1" min="1" max="<?php echo $availableCount; ?>" readonly class="w-10 text-center font-black text-sm bg-transparent border-none outline-none dark:text-white">
                                    <button type="button" class="w-8 h-8 rounded-lg bg-white dark:bg-slate-600 shadow-sm flex items-center justify-center hover:bg-gray-100 dark:hover:bg-slate-500 text-gray-800 dark:text-white transition font-bold" onclick="updateGroupQty('<?php echo $cardId; ?>', 1, <?php echo $availableCount; ?>)">+</button>
                                </div>
                            </div>
                            
                            <div class="flex justify-between items-center text-sm font-black text-gray-800 dark:text-white mb-4 px-1">
                                <span>جمع کل:</span>
                                <span class="font-mono text-emerald-600 dark:text-emerald-400 text-xl tracking-tight" id="total-price-<?php echo $cardId; ?>" dir="ltr"><?php echo number_format($finalPrice); ?> <span class="text-xs">T</span></span>
                            </div>

                            <button type="button" onclick="toggleAdvancedSettings('<?php echo $cardId; ?>')" class="w-full text-[11px] font-bold text-gray-500 hover:text-blue-600 dark:text-gray-400 dark:hover:text-blue-400 mb-3 flex items-center justify-center gap-1.5 transition bg-gray-50 dark:bg-slate-700/30 py-2 rounded-lg">
                                تنظیمات ثبت مشتری <span id="icon-<?php echo $cardId; ?>">🔽</span>
                            </button>

                            <div id="settings-<?php echo $cardId; ?>" class="hidden bg-gray-50 dark:bg-slate-700/50 p-4 rounded-xl border border-gray-100 dark:border-slate-600/50 mb-5 space-y-4">
                                <div>
                                    <label class="block text-[10px] font-black text-gray-500 dark:text-gray-400 mb-1.5">نام مشتری (اختیاری)</label>
                                    <input type="text" name="customer_name" list="customerNamesList" placeholder="جستجو یا تایپ نام..." class="w-full border border-gray-200 dark:border-slate-600 bg-white dark:bg-slate-800 p-2.5 rounded-lg text-xs font-bold outline-none focus:border-blue-500 dark:focus:border-blue-400 transition dark:text-white shadow-sm">
                                </div>
                                <div>
                                    <label class="block text-[10px] font-black text-gray-500 dark:text-gray-400 mb-1.5">فروش به مشتری <span class="text-rose-500 font-normal">(برای 1 عدد)</span></label>
                                    <input type="text" name="custom_sale_price" placeholder="<?php echo number_format($retailTotal); ?>" class="w-full border border-gray-200 dark:border-slate-600 bg-white dark:bg-slate-800 p-2.5 rounded-lg text-xs font-bold font-mono outline-none focus:border-blue-500 transition dark:text-white shadow-sm" dir="ltr" onkeyup="formatCurrency(this)">
                                </div>
                                <?php if(!empty($myBanks)): ?>
                                <div>
                                    <label class="block text-[10px] font-black text-gray-500 dark:text-gray-400 mb-1.5">واریز شده به حساب (اختیاری)</label>
                                    <select name="bank_id" class="w-full border border-gray-200 dark:border-slate-600 bg-white dark:bg-slate-800 p-2.5 rounded-lg text-xs font-bold outline-none focus:border-blue-500 transition dark:text-white shadow-sm cursor-pointer">
                                        <option value="">-- انتخاب حساب --</option>
                                        <?php foreach($myBanks as $b): ?>
                                            <option value="<?php echo $b['id']; ?>"><?php echo htmlspecialchars($b['bank_name']); ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <?php endif; ?>
                            </div>

                            <?php if($isAdmin): ?>
                                <button type="button" disabled class="w-full bg-amber-100 text-amber-700 font-black py-3.5 rounded-xl cursor-not-allowed text-sm">ادمین امکان خرید ندارد</button>
                            <?php else: ?>
                                <button type="submit" id="btn-submit-<?php echo $cardId; ?>" class="w-full text-white font-black py-3.5 rounded-xl shadow-lg transition-all hover:-translate-y-0.5 flex items-center justify-center gap-2 <?php echo ($walletBalance < $finalPrice) ? 'opacity-50 cursor-not-allowed grayscale' : ''; ?>" style="background-color: <?php echo $hex; ?>; box-shadow: 0 4px 14px <?php echo $hex; ?>40;">
                                    <?php if($walletBalance < $finalPrice): ?>
                                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>
                                        موجودی ناکافی
                                    <?php else: ?>
                                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 3h2l.4 2M7 13h10l4-8H5.4M7 13L5.4 5M7 13l-2.293 2.293c-.63.63-.184 1.707.707 1.707H17m0 0a2 2 0 100 4 2 2 0 000-4zm-8 2a2 2 0 11-4 0 2 2 0 014 0z"></path></svg>
                                        خرید و تحویل آنی
                                    <?php endif; ?>
                                </button>
                            <?php endif; ?>
                        </form>
                    <?php endif; ?>
                </div>
            <?php endforeach; ?>
        </div>
    </div>
<?php endforeach; endif; ?>