<?php
// modules/inventory/widgets/plans.php

// واکشی لیست تخفیف‌های ثبت شده از دیتابیس برای استفاده در جاوااسکریپت
$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'];
}
?>

<div class="grid grid-cols-1 xl:grid-cols-3 gap-6">
    <div class="xl:col-span-1 bg-white dark:bg-slate-800 rounded-3xl shadow-sm border border-gray-100 dark:border-slate-700 p-6 border-t-8 border-t-purple-500 h-fit">
        <h2 class="text-lg font-bold mb-4 text-gray-800 dark:text-white">تعریف طرح جدید</h2>
        <form method="POST" class="space-y-4" action="inventory.php">
            <input type="hidden" name="action" value="add_plan">
            <div class="grid grid-cols-1 md:grid-cols-5 gap-3">
                <div class="md:col-span-2">
                    <label class="block text-xs font-bold mb-1 dark:text-gray-300">نام طرح (فارسی)</label>
                    <input type="text" name="plan_name" required class="w-full border-2 border-gray-200 dark:border-slate-600 p-2.5 rounded-xl outline-none focus:border-purple-500 bg-transparent dark:text-white" dir="ltr">
                </div>
                <div class="md:col-span-2">
                    <label class="block text-[11px] font-bold text-gray-500 dark:text-gray-400 mb-1">نام انگلیسی (برای یوزرنیم)</label>
                    <input type="text" name="plan_name_en" class="w-full border-2 border-gray-200 dark:border-slate-600 p-2.5 rounded-xl outline-none focus:border-purple-500 bg-transparent dark:text-white" dir="ltr" placeholder="Silver">
                </div>
                <div class="md:col-span-1">
                    <label class="block text-xs font-bold mb-1 dark:text-gray-300">رنگ</label>
                    <input type="color" name="color_code" value="#3b82f6" class="w-full h-[46px] rounded-xl cursor-pointer border-2 border-gray-200 dark:border-slate-600 p-1 bg-transparent">
                </div>
            </div>
            
            <div class="space-y-3 bg-purple-50/50 dark:bg-purple-900/20 p-4 rounded-xl border border-purple-100 dark:border-purple-800/50">
                <div>
                    <label class="block text-xs font-bold text-gray-700 dark:text-gray-300 mb-1">قیمت خرید ادمین / ۱ گیگ (تومان)</label>
                    <input type="text" name="admin_cost_price" required class="w-full border dark:border-slate-600 p-2 rounded-lg outline-none font-mono bg-transparent dark:text-white" dir="ltr" onkeyup="formatCurrency(this)">
                </div>
                <div>
                    <label class="block text-xs font-black text-purple-700 dark:text-purple-400 mb-1">فروش به نماینده / ۱ گیگ (کسر از کیف پول)</label>
                    <input type="text" name="cost_price" required class="w-full border-2 border-purple-300 dark:border-purple-600 p-2 rounded-lg outline-none font-bold text-purple-800 dark:text-purple-300 font-mono bg-transparent" dir="ltr" onkeyup="formatCurrency(this)">
                </div>
                <div>
                    <label class="block text-xs font-bold text-gray-700 dark:text-gray-300 mb-1">فروش به مشتری نهایی / ۱ گیگ (تومان)</label>
                    <input type="text" name="retail_price" required class="w-full border dark:border-slate-600 p-2 rounded-lg outline-none font-mono bg-transparent dark:text-white" dir="ltr" onkeyup="formatCurrency(this)">
                </div>
            </div>

            <div class="bg-gray-50 dark:bg-slate-700 p-4 rounded-xl border border-gray-200 dark:border-slate-600">
                <p class="text-[10px] text-blue-500 font-bold mb-2">💡 برای مدیریت پیشرفته تخفیف‌های حجمی، ابتدا طرح را ذخیره کنید، سپس از جدول سمت چپ روی «تخفیف‌ها» کلیک کنید.</p>
            </div>
            <button type="submit" class="w-full bg-purple-600 hover:bg-purple-700 text-white font-bold py-3 rounded-xl transition shadow">ذخیره طرح پایه</button>
        </form>
    </div>

    <div class="xl:col-span-2 bg-white dark:bg-slate-800 rounded-3xl shadow-sm border border-gray-100 dark:border-slate-700 p-6">
        <h2 class="text-lg font-bold mb-4 text-gray-800 dark:text-white">طرح‌های فعال و فرمول قیمت‌گذاری</h2>
        <div class="overflow-x-auto">
            <table class="w-full text-sm text-right text-gray-600 dark:text-gray-400">
                <thead class="bg-gray-100 dark:bg-slate-700/50 text-gray-700 dark:text-gray-300">
                    <tr>
                        <th class="px-4 py-3">رنگ / نام طرح</th>
                        <th class="px-4 py-3">نام انگلیسی</th>
                        <th class="px-4 py-3">خرید ادمین</th>
                        <th class="px-4 py-3 text-purple-700 dark:text-purple-400">قیمت نماینده</th>
                        <th class="px-4 py-3 text-center">عملیات مدیریت</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-100 dark:divide-slate-700">
                    <?php if(empty($plansList)): ?>
                        <tr><td colspan="5" class="text-center py-6 text-gray-500 font-bold">هیچ طرحی تعریف نشده است.</td></tr>
                    <?php else: foreach($plansList as $p): 
                        $isActive = (!isset($p['is_active']) || $p['is_active'] == 1);
                        $rowClass = $isActive ? '' : 'opacity-60 bg-gray-50 dark:bg-slate-800/50';
                    ?>
                        <tr class="hover:bg-gray-50 dark:hover:bg-slate-700/30 transition <?php echo $rowClass; ?>">
                            <td class="px-4 py-3 font-black text-gray-800 dark:text-gray-200 flex items-center gap-2">
                                <span class="w-4 h-4 rounded-full border border-gray-300 dark:border-gray-600 shadow-sm shrink-0" style="background-color: <?php echo htmlspecialchars($p['color_code']); ?>"></span>
                                <?php echo htmlspecialchars($p['plan_name']); ?>
                                <?php if(!$isActive): ?>
                                    <span class="text-[9px] bg-rose-100 text-rose-600 px-1.5 py-0.5 rounded-full dark:bg-rose-900/30 dark:text-rose-400 whitespace-nowrap">غیرفعال</span>
                                <?php endif; ?>
                            </td>
                            <td class="px-4 py-3 font-mono text-xs text-gray-500" dir="ltr"><?php echo htmlspecialchars($p['plan_name_en'] ?? ''); ?></td>
                            <td class="px-4 py-3 font-mono text-xs" dir="ltr"><?php echo number_format($p['admin_cost_price']); ?></td>
                            <td class="px-4 py-3 font-mono font-bold text-purple-700 dark:text-purple-400 bg-purple-50/50 dark:bg-purple-900/10" dir="ltr"><?php echo number_format($p['cost_price']); ?></td>
                            <td class="px-4 py-3 text-center flex gap-1 justify-center flex-wrap">
                                <form method="POST" action="inventory.php" class="inline">
                                    <input type="hidden" name="action" value="toggle_plan_status">
                                    <input type="hidden" name="plan_id" value="<?php echo $p['id']; ?>">
                                    <?php if($isActive): ?>
                                        <button type="submit" class="text-amber-600 font-bold text-xs bg-amber-50 dark:bg-amber-900/30 px-3 py-1.5 rounded-lg hover:bg-amber-100 transition" title="مخفی کردن این طرح در فروشگاه">خاموش</button>
                                    <?php else: ?>
                                        <button type="submit" class="text-emerald-600 font-bold text-xs bg-emerald-50 dark:bg-emerald-900/30 px-3 py-1.5 rounded-lg hover:bg-emerald-100 transition shadow-sm" title="نمایش مجدد این طرح در فروشگاه">روشن</button>
                                    <?php endif; ?>
                                </form>
                                <button onclick="openDiscounts('<?php echo htmlspecialchars($p['plan_name']); ?>')" class="text-fuchsia-600 font-bold text-xs bg-fuchsia-50 dark:bg-fuchsia-900/30 px-3 py-1.5 rounded-lg hover:bg-fuchsia-100 transition">تخفیف‌های حجمی 🎁</button>
                                <button onclick="openEditPlan(<?php echo $p['id']; ?>, '<?php echo htmlspecialchars($p['plan_name']); ?>', '<?php echo htmlspecialchars($p['plan_name_en'] ?? ''); ?>', '<?php echo $p['admin_cost_price']; ?>', '<?php echo $p['cost_price']; ?>', '<?php echo $p['retail_price']; ?>', '<?php echo htmlspecialchars($p['color_code']); ?>')" class="text-blue-500 font-bold text-xs bg-blue-50 dark:bg-blue-900/30 px-3 py-1.5 rounded-lg hover:bg-blue-100 transition">ویرایش</button>
                                <form method="POST" action="inventory.php" onsubmit="return confirm('حذف این طرح؟ (اکانت‌های انبار حذف نمی‌شوند)');" class="inline">
                                    <input type="hidden" name="action" value="delete_plan"><input type="hidden" name="plan_id" value="<?php echo $p['id']; ?>">
                                    <button type="submit" class="text-red-500 font-bold text-xs bg-red-50 dark:bg-red-900/30 px-3 py-1.5 rounded-lg hover:bg-red-100 transition">حذف</button>
                                </form>
                            </td>
                        </tr>
                    <?php endforeach; endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<div id="discountModal" class="fixed inset-0 bg-black/60 hidden flex items-center justify-center z-[120] p-4 backdrop-blur-sm">
    <div class="bg-white dark:bg-slate-800 rounded-3xl p-6 max-w-2xl w-full shadow-2xl">
        <div class="flex justify-between items-center mb-6 border-b border-gray-100 dark:border-slate-700 pb-4">
            <h2 class="text-xl font-black text-fuchsia-600 dark:text-fuchsia-400">مدیریت تخفیف‌های حجمی طرح: <span id="discount_plan_title" class="text-gray-800 dark:text-white"></span></h2>
            <button onclick="closeDiscounts()" class="text-gray-400 hover:text-red-500 text-2xl font-bold">&times;</button>
        </div>
        
        <p class="text-xs font-bold text-gray-500 dark:text-gray-400 mb-6 leading-relaxed">
            در اینجا می‌توانید برای هر حجم خاص از این طرح، درصد تخفیف متفاوتی تعریف کنید. این درصد به صورت خودکار روی قیمت خرید نماینده و قیمت فروش مشتری اعمال شده و در حسابداری سیستم ثبت می‌گردد.
        </p>

        <form method="POST" action="inventory.php" class="bg-fuchsia-50 dark:bg-fuchsia-900/20 p-4 rounded-2xl border border-fuchsia-100 dark:border-fuchsia-800/50 mb-6">
            <input type="hidden" name="action" value="add_discount">
            <input type="hidden" name="plan_name" id="discount_plan_input">
            <div class="grid grid-cols-1 sm:grid-cols-3 gap-3 items-end">
                <div>
                    <label class="block text-xs font-bold text-gray-700 dark:text-gray-300 mb-1">حجم محصول (GB)</label>
                    <input type="number" name="volume" required min="1" class="w-full border-2 border-white dark:border-slate-600 p-2.5 rounded-xl outline-none focus:border-fuchsia-500 bg-white dark:bg-slate-700 dark:text-white" dir="ltr" placeholder="مثلا 10">
                </div>
                <div>
                    <label class="block text-xs font-bold text-gray-700 dark:text-gray-300 mb-1">درصد تخفیف (%)</label>
                    <input type="number" name="discount_percent" required min="1" max="100" class="w-full border-2 border-white dark:border-slate-600 p-2.5 rounded-xl outline-none focus:border-fuchsia-500 bg-white dark:bg-slate-700 dark:text-white" dir="ltr" placeholder="مثلا 15">
                </div>
                <button type="submit" class="w-full bg-fuchsia-600 hover:bg-fuchsia-700 text-white font-bold py-3 rounded-xl transition shadow-sm text-sm">➕ افزودن تخفیف</button>
            </div>
        </form>

        <div class="max-h-[300px] overflow-y-auto custom-scrollbar pr-2">
            <table class="w-full text-sm text-right">
                <thead class="bg-gray-100 dark:bg-slate-700 text-gray-600 dark:text-gray-300">
                    <tr>
                        <th class="px-4 py-2 rounded-tr-lg">حجم</th>
                        <th class="px-4 py-2 text-fuchsia-600 dark:text-fuchsia-400">درصد تخفیف</th>
                        <th class="px-4 py-2 text-center rounded-tl-lg">حذف</th>
                    </tr>
                </thead>
                <tbody id="discount_table_body" class="divide-y divide-gray-100 dark:divide-slate-700">
                    </tbody>
            </table>
        </div>
    </div>
</div>

<div id="editPlanModal" class="fixed inset-0 bg-black/50 dark:bg-slate-900/80 hidden flex items-center justify-center z-[100] p-4 backdrop-blur-sm transition-opacity">
    <div class="bg-white dark:bg-slate-800 rounded-3xl p-8 max-w-md w-full shadow-2xl transform scale-100 transition-transform">
        <h2 class="text-xl font-bold mb-6 text-gray-800 dark:text-white">ویرایش اطلاعات پایه طرح</h2>
        <form method="POST" class="space-y-4" action="inventory.php">
            <input type="hidden" name="action" value="edit_plan">
            <input type="hidden" name="plan_id" id="edit_plan_id">
            
            <div class="grid grid-cols-2 gap-3">
                <div class="col-span-1">
                    <label class="block text-xs font-bold mb-1 dark:text-gray-300">نام طرح (فارسی)</label>
                    <input type="text" name="plan_name" id="edit_plan_name" required class="w-full border-2 border-gray-200 dark:border-slate-600 p-2.5 rounded-xl outline-none focus:border-blue-500 bg-transparent dark:text-white" dir="ltr">
                </div>
                <div class="col-span-1">
                    <label class="block text-[11px] font-bold text-gray-500 dark:text-gray-400 mb-1">نام انگلیسی</label>
                    <input type="text" name="plan_name_en" id="edit_plan_name_en" class="w-full border-2 border-gray-200 dark:border-slate-600 p-2.5 rounded-xl outline-none focus:border-blue-500 bg-transparent dark:text-white" dir="ltr">
                </div>
            </div>
            
            <div class="grid grid-cols-3 gap-2">
                <div>
                    <label class="block text-[10px] font-bold text-gray-500 dark:text-gray-400 mb-1">خرید ادمین</label>
                    <input type="text" name="admin_cost_price" id="edit_admin_cost" required class="w-full border-2 border-gray-200 dark:border-slate-600 p-2 rounded-xl outline-none font-mono text-sm bg-transparent dark:text-white" dir="ltr" onkeyup="formatCurrency(this)">
                </div>
                <div>
                    <label class="block text-[10px] font-bold text-purple-600 dark:text-purple-400 mb-1">قیمت نماینده</label>
                    <input type="text" name="cost_price" id="edit_cost_price" required class="w-full border-2 border-purple-300 dark:border-purple-600 p-2 rounded-xl outline-none font-bold font-mono text-sm text-purple-700 dark:text-purple-300 bg-purple-50 dark:bg-purple-900/20" dir="ltr" onkeyup="formatCurrency(this)">
                </div>
                <div>
                    <label class="block text-[10px] font-bold text-gray-500 dark:text-gray-400 mb-1">مشتری نهایی</label>
                    <input type="text" name="retail_price" id="edit_retail_price" required class="w-full border-2 border-gray-200 dark:border-slate-600 p-2 rounded-xl outline-none font-mono text-sm bg-transparent dark:text-white" dir="ltr" onkeyup="formatCurrency(this)">
                </div>
            </div>
            
            <input type="hidden" name="color_code" id="edit_color_code">

            <div class="flex gap-2 pt-2">
                <button type="submit" class="flex-1 bg-blue-600 text-white py-3 rounded-xl font-bold hover:bg-blue-700 transition">ذخیره تغییرات</button>
                <button type="button" onclick="closeEditPlan()" class="flex-1 bg-gray-100 dark:bg-slate-700 text-gray-700 dark:text-gray-300 py-3 rounded-xl font-bold transition">انصراف</button>
            </div>
        </form>
    </div>
</div>

<script>
    const discountsData = <?php echo json_encode($discountsArr); ?>;

    // تابع جداکننده ۳ رقم برای مبالغ (تومان)
    function formatCurrency(input) {
        let value = input.value.replace(/,/g, '').replace(/\D/g, '');
        if (value) input.value = Number(value).toLocaleString('en-US');
        else input.value = '';
    }

    function openEditPlan(id, name, name_en, admin, cost, retail, color) {
        document.getElementById('edit_plan_id').value = id;
        document.getElementById('edit_plan_name').value = name;
        document.getElementById('edit_plan_name_en').value = name_en;
        document.getElementById('edit_admin_cost').value = Number(admin).toLocaleString('en-US');
        document.getElementById('edit_cost_price').value = Number(cost).toLocaleString('en-US');
        document.getElementById('edit_retail_price').value = Number(retail).toLocaleString('en-US');
        document.getElementById('edit_color_code').value = color;
        
        document.getElementById('editPlanModal').classList.remove('hidden');
        document.getElementById('editPlanModal').classList.add('flex');
    }

    function closeEditPlan() {
        document.getElementById('editPlanModal').classList.add('hidden');
        document.getElementById('editPlanModal').classList.remove('flex');
    }

    function openDiscounts(planName) {
        document.getElementById('discount_plan_title').innerText = planName;
        document.getElementById('discount_plan_input').value = planName;
        renderDiscountTable(planName);
        document.getElementById('discountModal').classList.remove('hidden');
    }

    function closeDiscounts() {
        document.getElementById('discountModal').classList.add('hidden');
    }

    function renderDiscountTable(planName) {
        const tbody = document.getElementById('discount_table_body');
        tbody.innerHTML = '';
        if(discountsData[planName]) {
            for (const [vol, percent] of Object.entries(discountsData[planName])) {
                tbody.innerHTML += `
                <tr class="hover:bg-gray-50 dark:hover:bg-slate-700/30">
                    <td class="px-4 py-3 font-mono font-black text-gray-800 dark:text-gray-200" dir="ltr">${vol} GB</td>
                    <td class="px-4 py-3 font-black text-fuchsia-600 dark:text-fuchsia-400" dir="ltr">${percent} %</td>
                    <td class="px-4 py-3 text-center">
                        <form method="POST" action="inventory.php" onsubmit="return confirm('حذف این رول تخفیف؟');">
                            <input type="hidden" name="action" value="delete_discount">
                            <input type="hidden" name="plan_name" value="${planName}">
                            <input type="hidden" name="volume" value="${vol}">
                            <button type="submit" class="text-red-500 bg-red-50 dark:bg-rose-900/30 px-3 py-1 rounded-lg text-xs font-bold transition hover:bg-red-100">حذف</button>
                        </form>
                    </td>
                </tr>`;
            }
        } else {
            tbody.innerHTML = '<tr><td colspan="3" class="text-center py-4 text-gray-500 font-bold text-xs">هیچ تخفیف اختصاصی برای این طرح ثبت نشده است.</td></tr>';
        }
    }
</script>