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

// ==========================================
// دریافت اطلاعات و محاسبات گزارشات انبار
// ==========================================
$discountsList = $pdo->query("SELECT * FROM plan_discounts")->fetchAll(PDO::FETCH_ASSOC);
$discountsArr = [];
foreach($discountsList as $d) { $discountsArr[$d['plan_name']][$d['volume']] = $d['discount_percent']; }

$availableItems = $pdo->query("SELECT i.plan_name, i.volume, i.volume_unit, p.cost_price, p.admin_cost_price FROM inventory i JOIN plans p ON i.plan_name = p.plan_name WHERE i.status = 'available'")->fetchAll();
$totalAgentValue = 0; $totalAdminCostValue = 0;

foreach($availableItems as $item) {
    $vol = (float)$item['volume']; 
    $vUnit = $item['volume_unit'] ?? 'GB';
    $pName = $item['plan_name'];
    
    $volForPrice = ($vUnit === 'MB') ? ($vol / 1024) : $vol;
    $baseAgentPrice = $item['cost_price'] * $volForPrice; 
    $baseAdminPrice = $item['admin_cost_price'] * $volForPrice;
    
    if(isset($discountsArr[$pName][(int)$vol])) {
        $discPercent = $discountsArr[$pName][(int)$vol];
        $baseAgentPrice = $baseAgentPrice - ($baseAgentPrice * ($discPercent / 100));
    }
    $totalAgentValue += $baseAgentPrice; $totalAdminCostValue += $baseAdminPrice;
}
$potentialProfit = $totalAgentValue - $totalAdminCostValue;

$planStockItems = $pdo->query("
    SELECT i.plan_name, i.volume, i.volume_unit,
           SUM(CASE WHEN i.status = 'available' THEN 1 ELSE 0 END) as available_count, 
           MAX(p.color_code) as color_code,
           (SELECT account_username FROM inventory WHERE plan_name = i.plan_name AND volume = i.volume AND COALESCE(volume_unit, 'GB') = COALESCE(i.volume_unit, 'GB') ORDER BY id DESC LIMIT 1) as last_username
    FROM inventory i LEFT JOIN plans p ON i.plan_name = p.plan_name 
    GROUP BY i.plan_name, i.volume, i.volume_unit ORDER BY i.plan_name ASC, i.volume ASC
")->fetchAll();

$inventoryList = $pdo->query("SELECT inventory.*, users.fullname FROM inventory LEFT JOIN users ON inventory.operator_id = users.id ORDER BY inventory.id DESC")->fetchAll(PDO::FETCH_ASSOC);
$missingSubItems = $pdo->query("SELECT id, plan_name, volume, volume_unit, account_username FROM inventory WHERE status = 'available' AND (config_link IS NULL OR config_link = '')")->fetchAll();

// استخراج سرورهای یکتا از لیست انبار برای دریافت دیتای لایو
$uniqueServers = array_unique(array_column($inventoryList, 'server_id'));
if (empty($uniqueServers)) $uniqueServers = [1];
?>

<style>
    .sub-watcher-alert { animation: pulseWarning 2s infinite; }
    @keyframes pulseWarning { 0% { box-shadow: 0 0 0 0px rgba(225, 29, 72, 0.4); } 100% { box-shadow: 0 0 0 15px rgba(225, 29, 72, 0); } }
</style>

<?php if(!empty($missingSubItems)): ?>
<div class="bg-rose-50 dark:bg-rose-900/20 border-2 border-rose-500 p-6 rounded-3xl mb-8 shadow-lg relative overflow-hidden sub-watcher-alert">
    <div class="absolute -right-4 -top-4 opacity-10 text-8xl">🚨</div>
    <div class="relative z-10">
        <h3 class="text-lg font-black text-rose-700 dark:text-rose-400 mb-2 flex items-center gap-2"><span class="text-2xl animate-pulse">🚨</span> اخطار ناظر سیستم: محصولات فاقد لینک ساب پیدا شد!</h3>
        <p class="text-sm font-bold text-rose-600 dark:text-rose-300 mb-4">محصولات زیر به صورت ناقص در انبار ثبت شده‌اند. فوراً لینک ساب آن‌ها را وارد کنید:</p>
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">
            <?php foreach($missingSubItems as $mItem): ?>
                <div class="bg-white dark:bg-slate-800 p-3 rounded-xl shadow-sm border border-rose-200 flex justify-between items-center">
                    <div><span class="block text-[10px] text-gray-500 font-bold"><?php echo htmlspecialchars($mItem['plan_name']); ?> (<?php echo $mItem['volume']; ?> <?php echo $mItem['volume_unit'] ?? 'GB'; ?>)</span><span class="text-sm font-mono text-gray-800 dark:text-white" dir="ltr"><?php echo htmlspecialchars($mItem['account_username']); ?></span></div>
                    <button onclick="openEditDbItem(<?php echo $mItem['id']; ?>, '<?php echo htmlspecialchars($mItem['account_username']); ?>', '')" class="bg-rose-500 hover:bg-rose-600 text-white text-[10px] font-bold px-3 py-1.5 rounded-lg transition">تکمیل اطلاعات</button>
                </div>
            <?php endforeach; ?>
        </div>
    </div>
</div>
<?php endif; ?>

<div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
    <div class="bg-gradient-to-br from-blue-600 to-blue-800 rounded-3xl shadow-lg p-6 text-white relative overflow-hidden">
        <div class="absolute -right-4 -bottom-4 opacity-20 text-7xl">💰</div>
        <h3 class="text-xs font-bold text-blue-100 mb-1 relative z-10">ارزش کل انبار (قیمت نماینده)</h3>
        <div class="text-3xl font-black relative z-10" dir="ltr"><?php echo number_format($totalAgentValue); ?> <span class="text-xs font-normal">T</span></div>
    </div>
    <div class="bg-white dark:bg-slate-800 border border-gray-100 dark:border-slate-700 rounded-3xl p-6 shadow-sm">
        <h3 class="text-xs font-bold text-gray-500">ارزش سرمایه (خرید ادمین)</h3>
        <div class="text-2xl font-black dark:text-white" dir="ltr"><?php echo number_format($totalAdminCostValue); ?> <span class="text-xs font-normal">T</span></div>
    </div>
    <div class="bg-white dark:bg-slate-800 border border-emerald-100 dark:border-emerald-900 rounded-3xl p-6 shadow-sm relative overflow-hidden">
        <div class="absolute right-0 top-0 w-2 h-full bg-emerald-500"></div>
        <h3 class="text-xs font-bold text-emerald-600">سود خالص بالقوه</h3>
        <div class="text-2xl font-black text-emerald-700 dark:text-emerald-500" dir="ltr"><?php echo number_format($potentialProfit); ?> <span class="text-xs font-normal">T</span></div>
    </div>
</div>

<?php if(!empty($planStockItems)): 
    $groupedStocks = []; foreach($planStockItems as $stock) { $groupedStocks[$stock['plan_name']][] = $stock; }
?>
<div class="mb-8 space-y-6">
    <h4 class="text-lg font-black text-gray-700 dark:text-gray-300 flex items-center gap-2">📊 موجودی انبار به تفکیک طرح</h4>
    <?php foreach($groupedStocks as $planName => $stocks): $planColor = $stocks[0]['color_code'] ?: '#3b82f6'; ?>
    <div class="bg-gray-50/50 dark:bg-slate-800/50 p-5 rounded-3xl border border-gray-100 dark:border-slate-700 relative overflow-hidden">
        <div class="absolute right-0 top-0 w-1.5 h-full" style="background-color: <?php echo $planColor; ?>"></div>
        <h5 class="text-sm font-black text-gray-800 dark:text-white mb-4 pr-3"><?php echo htmlspecialchars($planName); ?></h5>
        <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 pr-3">
            <?php foreach($stocks as $stock): 
                $count = (int)$stock['available_count']; $isZeroStock = ($count === 0); $isLowStock = ($count > 0 && $count < 5); $lastUname = $stock['last_username'] ?: '-';
                $volUnit = $stock['volume_unit'] ?? 'GB';
                if ($isZeroStock) { $cardClasses = "bg-red-50 dark:bg-rose-900/20 ring-1 ring-red-500/50 opacity-80"; $badgeText = "❌ تمام شد"; $badgeClasses = "text-red-700 bg-red-100"; } 
                elseif ($isLowStock) { $cardClasses = "bg-amber-50 dark:bg-amber-900/20 ring-1 ring-amber-500/50"; $badgeText = "⚠️ رو به اتمام: $count"; $badgeClasses = "text-amber-700 bg-amber-100 animate-pulse"; } 
                else { $cardClasses = "bg-white dark:bg-slate-800 shadow-sm border border-gray-100 dark:border-slate-600"; $badgeText = "موجودی: $count"; $badgeClasses = "text-gray-600 bg-gray-100"; }
            ?>
                <div class="p-4 rounded-2xl relative <?php echo $cardClasses; ?>">
                    <div class="flex justify-between items-start mb-3"><div class="text-xl font-black dark:text-white" dir="ltr"><?php echo $stock['volume']; ?> <?php echo $volUnit; ?></div><div class="text-[10px] font-bold px-2 py-1 rounded <?php echo $badgeClasses; ?>"><?php echo $badgeText; ?></div></div>
                </div>
            <?php endforeach; ?>
        </div>
    </div>
    <?php endforeach; ?>
</div>
<?php endif; ?>

<?php 
// لود کردن فایل جدید که حاوی جدول لایو، مودال‌ها و کدهای قدرتمند JS است
require_once 'stock_table.php'; 
?>