<?php
// modules/bonuses.php
require_once '../includes/auth.php';
checkLogin();
require_once '../config/db.php';
require_once '../includes/functions.php';

if (!isAdmin()) {
    header("Location: dashboard.php");
    exit;
}

$msg = '';
$error = '';

try {
    $pdo->exec("CREATE TABLE IF NOT EXISTS `global_settings` (
      `setting_key` varchar(50) NOT NULL,
      `setting_value` text DEFAULT NULL,
      PRIMARY KEY (`setting_key`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");
    $pdo->exec("INSERT IGNORE INTO `global_settings` (`setting_key`, `setting_value`) VALUES 
        ('bonus_system_status', '1'),
        ('bonus_timer_active', '0'),
        ('bonus_timer_date', '2027-01-01 00:00:00')");
} catch (PDOException $e) {}

if (!function_exists('jalali_to_gregorian')) {
    function jalali_to_gregorian($jy, $jm, $jd, $mod = '') {
        $jy += 1595;
        $days = -355668 + (365 * $jy) + ((int)($jy / 33) * 8) + ((int)((($jy % 33) + 3) / 4)) + $jd + (($jm < 7) ? ($jm - 1) * 31 : (($jm - 7) * 30) + 186);
        $gy = 400 * ((int)($days / 146097));
        $days %= 146097;
        if ($days > 36524) {
            $gy += 100 * ((int)(--$days / 36524));
            $days %= 36524;
            if ($days >= 365) $days++;
        }
        $gy += 4 * ((int)($days / 1461));
        $days %= 1461;
        if ($days > 365) {
            $gy += (int)(($days - 1) / 365);
            $days = ($days - 1) % 365;
        }
        $gd = $days + 1;
        $sal_a = array(0, 31, (($gy % 4 == 0 && $gy % 100 != 0) || ($gy % 400 == 0)) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
        for ($gm = 0; $gm < 13 && $gd > $sal_a[$gm]; $gm++) $gd -= $sal_a[$gm];
        return ($mod == '') ? array($gy, $gm, $gd) : $gy . $mod . sprintf("%02d", $gm) . $mod . sprintf("%02d", $gd);
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    
    // ۱. فعال/غیرفعال کردن کل سیستم بونوس
    if ($_POST['action'] === 'toggle_global_bonus') {
        $status = $_POST['bonus_system_status'] === '1' ? '1' : '0';
        $pdo->prepare("UPDATE global_settings SET setting_value = ? WHERE setting_key = 'bonus_system_status'")->execute([$status]);
        $msg = "وضعیت سیستم بونوس با موفقیت تغییر کرد.";
    }

    // ۲. بروزرسانی تایمر اختصاصی بونوس
    if ($_POST['action'] === 'update_bonus_timer') {
        $shamsiDateInput = trim($_POST['target_date_shamsi']); 
        $timeInput = trim($_POST['target_time']); 
        $isActive = isset($_POST['timer_is_active']) ? '1' : '0';

        if ($isActive && (empty($shamsiDateInput) || empty($timeInput))) {
            $error = "تاریخ و ساعت پایان الزامی است.";
        } elseif ($isActive) {
            $dateParts = explode('/', $shamsiDateInput);
            if (count($dateParts) == 3) {
                $gregorianDate = jalali_to_gregorian((int)$dateParts[0], (int)$dateParts[1], (int)$dateParts[2], '-');
                $formattedDateTime = $gregorianDate . ' ' . $timeInput . ':00';
                
                $pdo->prepare("UPDATE global_settings SET setting_value = ? WHERE setting_key = 'bonus_timer_active'")->execute([$isActive]);
                $pdo->prepare("UPDATE global_settings SET setting_value = ? WHERE setting_key = 'bonus_timer_date'")->execute([$formattedDateTime]);
                $msg = "تایمر زمان‌بندی بونوس با موفقیت ذخیره شد.";
            } else {
                $error = "فرمت تاریخ شمسی نامعتبر است.";
            }
        } else {
            $pdo->prepare("UPDATE global_settings SET setting_value = '0' WHERE setting_key = 'bonus_timer_active'")->execute();
            $msg = "تایمر بونوس با موفقیت خاموش شد.";
        }
    }

    // ۳. افزودن سطح بونوس جدید
    if ($_POST['action'] === 'add_tier') {
        $tierName = trim($_POST['tier_name']);
        $minAmount = (int)str_replace(',', '', $_POST['min_amount']);
        $bonusPercent = (int)$_POST['bonus_percent'];

        if (empty($tierName) || $minAmount <= 0 || $bonusPercent <= 0) {
            $error = "لطفاً تمام مقادیر را به درستی وارد کنید.";
        } else {
            $stmt = $pdo->prepare("INSERT INTO bonus_settings (tier_name, min_amount, bonus_percent, is_active) VALUES (?, ?, ?, 1)");
            $stmt->execute([$tierName, $minAmount, $bonusPercent]);
            $msg = "سطح پاداش جدید اضافه شد.";
        }
    }

    // ۴. ویرایش سطح بونوس
    if ($_POST['action'] === 'edit_tier') {
        $tierId = (int)$_POST['tier_id'];
        $tierName = trim($_POST['tier_name']);
        $minAmount = (int)str_replace(',', '', $_POST['min_amount']);
        $bonusPercent = (int)$_POST['bonus_percent'];

        if (empty($tierName) || $minAmount <= 0 || $bonusPercent <= 0) {
            $error = "مقادیر ویرایش نامعتبر است.";
        } else {
            $stmt = $pdo->prepare("UPDATE bonus_settings SET tier_name = ?, min_amount = ?, bonus_percent = ? WHERE id = ?");
            $stmt->execute([$tierName, $minAmount, $bonusPercent, $tierId]);
            $msg = "تغییرات سطح بونوس با موفقیت ذخیره شد.";
        }
    }

    // ۵. تغییر وضعیت فعال/غیرفعال بودن یک سطح خاص
    if ($_POST['action'] === 'toggle_tier') {
        $tierId = (int)$_POST['tier_id'];
        $pdo->exec("UPDATE bonus_settings SET is_active = NOT is_active WHERE id = $tierId");
        $msg = "وضعیت سطح پاداش تغییر کرد.";
    }

    // ۶. حذف یک سطح بونوس
    if ($_POST['action'] === 'delete_tier') {
        $tierId = (int)$_POST['tier_id'];
        $pdo->exec("DELETE FROM bonus_settings WHERE id = $tierId");
        $msg = "سطح پاداش با موفقیت حذف شد.";
    }
}

// ==========================================
// دریافت اطلاعات از دیتابیس برای نمایش
// ==========================================
$isBonusSystemActive = $pdo->query("SELECT setting_value FROM global_settings WHERE setting_key = 'bonus_system_status'")->fetchColumn() === '1';
$bonusTimerActive = $pdo->query("SELECT setting_value FROM global_settings WHERE setting_key = 'bonus_timer_active'")->fetchColumn() === '1';
$bonusTimerDate = $pdo->query("SELECT setting_value FROM global_settings WHERE setting_key = 'bonus_timer_date'")->fetchColumn();

$shamsiDate = '';
$timePart = '';
if (!empty($bonusTimerDate) && $bonusTimerDate != '0000-00-00 00:00:00') {
    $dt = new DateTime($bonusTimerDate);
    $shamsiDate = sprintf("%04d/%02d/%02d", ...gregorian_to_jalali($dt->format('Y'), $dt->format('m'), $dt->format('d')));
    $timePart = $dt->format('H:i');
}

$bonuses = $pdo->query("SELECT * FROM bonus_settings ORDER BY min_amount ASC")->fetchAll();

require_once '../includes/header.php';
?>

<div class="mb-6 flex justify-between items-end">
    <div>
        <h1 class="text-2xl font-black text-gray-800 dark:text-white tracking-tight">سیستم بونوس مالی</h1>
        <p class="text-sm text-gray-500 dark:text-gray-400 mt-1">مدیریت تایمر اختصاصی و پاداش‌های واریزی کیف پول نمایندگان</p>
    </div>
</div>

<?php if($msg): ?><div class="bg-green-100 dark:bg-emerald-900/30 border border-green-400 dark:border-emerald-800 text-green-700 dark:text-emerald-400 px-4 py-3 rounded-xl mb-6 font-bold shadow-sm">✅ <?php echo $msg; ?></div><?php endif; ?>
<?php if($error): ?><div class="bg-red-100 dark:bg-rose-900/30 border border-red-400 dark:border-rose-800 text-red-700 dark:text-rose-400 px-4 py-3 rounded-xl mb-6 font-bold shadow-sm">❌ <?php echo $error; ?></div><?php endif; ?>

<div class="grid grid-cols-1 lg:grid-cols-3 gap-8 mb-8">
    
    <!-- ۱. مستر سوییچ کل بونوس‌ها -->
    <div class="lg:col-span-1 space-y-6">
        <div class="bg-white dark:bg-slate-800 rounded-3xl shadow-sm border border-gray-100 dark:border-slate-700 p-6 md:p-8 h-full flex flex-col justify-between">
            <div>
                <div class="w-16 h-16 rounded-2xl flex items-center justify-center text-4xl mb-4 shadow-sm <?php echo $isBonusSystemActive ? 'bg-emerald-100 text-emerald-600 dark:bg-emerald-900/40 dark:text-emerald-400' : 'bg-gray-100 text-gray-400 dark:bg-slate-700 dark:text-gray-500'; ?>">
                    🎁
                </div>
                <h2 class="text-xl font-black text-gray-800 dark:text-white mb-2">سیستم پاداش (بونوس)</h2>
                <p class="text-xs text-gray-500 dark:text-gray-400 font-bold leading-relaxed mb-6">
                    این دکمه کنترل کل سیستم است. با غیرفعال کردن آن، تمام بنرها و درصدهای بونوس فوراً خاموش می‌شوند.
                </p>
            </div>
            
            <form method="POST">
                <input type="hidden" name="action" value="toggle_global_bonus">
                <input type="hidden" name="bonus_system_status" value="<?php echo $isBonusSystemActive ? '0' : '1'; ?>">
                <button type="submit" class="w-full py-4 rounded-xl font-black text-white transition-all shadow-md flex items-center justify-center gap-2 <?php echo $isBonusSystemActive ? 'bg-rose-500 hover:bg-rose-600' : 'bg-emerald-500 hover:bg-emerald-600'; ?>">
                    <?php if($isBonusSystemActive): ?>
                        <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="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 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="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>
                        روشن کردن سیستم بونوس
                    <?php endif; ?>
                </button>
            </form>
        </div>
    </div>

    <!-- ۲. مدیریت تایمر اختصاصی بونوس -->
    <div class="lg:col-span-2 space-y-6">
        <div class="bg-white dark:bg-slate-800 rounded-3xl shadow-sm border border-gray-100 dark:border-slate-700 p-6 md:p-8 border-t-8 border-t-amber-500 relative overflow-hidden h-full">
            <div class="absolute -right-6 -top-6 text-8xl opacity-10">⏱️</div>
            <h2 class="text-xl font-black text-gray-800 dark:text-white mb-6 relative z-10 flex items-center gap-2">
                <svg class="w-6 h-6 text-amber-500" 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>
                تایمر زمان‌بندی بونوس
            </h2>
            
            <p class="text-xs text-gray-500 dark:text-gray-400 mb-6 font-bold leading-relaxed relative z-10">
                اگر تایمر را فعال کنید، یک شمارش معکوس روی بنر بونوس در کیف پول و سایدبار نمایش داده می‌شود. پس از اتمام زمان، سیستم بونوس به صورت خودکار <span class="text-rose-500">غیرفعال خواهد شد</span>.
            </p>

            <form method="POST" class="space-y-5 relative z-10">
                <input type="hidden" name="action" value="update_bonus_timer">
                
                <div class="flex items-center gap-3 bg-amber-50 dark:bg-amber-900/20 p-4 rounded-xl border border-amber-200 dark:border-amber-800 mb-4">
                    <input type="checkbox" name="timer_is_active" id="timer_is_active" value="1" <?php echo $bonusTimerActive ? 'checked' : ''; ?> class="w-5 h-5 text-amber-600 rounded focus:ring-amber-500 cursor-pointer" onchange="toggleBonusDateInputs(this.checked)">
                    <label for="timer_is_active" class="font-bold text-sm text-amber-800 dark:text-amber-200 cursor-pointer select-none">فعال‌سازی شمارش معکوس بونوس</label>
                </div>
                
                <div id="bonusDateInputsContainer" class="grid grid-cols-2 gap-4 transition-opacity <?php echo $bonusTimerActive ? '' : 'opacity-50 pointer-events-none'; ?>">
                    <div>
                        <label class="block text-sm font-bold text-gray-700 dark:text-gray-300 mb-2">تاریخ پایان (شمسی)</label>
                        <input type="text" name="target_date_shamsi" id="bonus_date_input" value="<?php echo htmlspecialchars($shamsiDate); ?>" placeholder="مثال: 1403/12/29" class="w-full border-2 border-gray-200 dark:border-slate-600 p-3 rounded-xl focus:border-amber-500 outline-none font-mono font-bold bg-gray-50 dark:bg-slate-700 dark:text-white text-sm" dir="ltr" <?php echo $bonusTimerActive ? 'required' : ''; ?>>
                    </div>
                    <div>
                        <label class="block text-sm font-bold text-gray-700 dark:text-gray-300 mb-2">ساعت پایان</label>
                        <input type="time" name="target_time" id="bonus_time_input" value="<?php echo htmlspecialchars($timePart); ?>" class="w-full border-2 border-gray-200 dark:border-slate-600 p-3 rounded-xl focus:border-amber-500 outline-none font-mono font-bold bg-gray-50 dark:bg-slate-700 dark:text-white text-sm" dir="ltr" <?php echo $bonusTimerActive ? 'required' : ''; ?>>
                    </div>
                </div>

                <button type="submit" class="w-full bg-amber-500 hover:bg-amber-600 text-white font-bold py-3.5 rounded-xl transition shadow-md flex items-center justify-center gap-2 mt-4">
                    ذخیره تایمر بونوس
                </button>
            </form>
        </div>
    </div>
</div>

<div class="space-y-8">
    <!-- فرم افزودن سطح جدید -->
    <div class="bg-white dark:bg-slate-800 rounded-3xl shadow-sm border border-gray-100 dark:border-slate-700 p-6 md:p-8 border-t-8 border-t-emerald-500">
        <h2 class="text-base font-bold text-gray-800 dark:text-white mb-6 flex items-center gap-2">
            <svg class="w-5 h-5 text-emerald-500" 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>
            افزودن سطح بونوس جدید
        </h2>
        
        <form method="POST" class="grid grid-cols-1 md:grid-cols-4 gap-4 items-end">
            <input type="hidden" name="action" value="add_tier">
            
            <div class="md:col-span-1">
                <label class="block text-xs font-bold text-gray-500 dark:text-gray-400 mb-2">نام سطح (مثال: ویژه)</label>
                <input type="text" name="tier_name" required class="w-full border-2 border-gray-200 dark:border-slate-600 p-2.5 rounded-xl focus:border-emerald-500 outline-none font-bold text-sm bg-gray-50 dark:bg-slate-700 dark:text-white">
            </div>
            
            <div class="md:col-span-1">
                <label class="block text-xs font-bold text-gray-500 dark:text-gray-400 mb-2">حداقل واریزی خالص (تومان)</label>
                <input type="text" name="min_amount" required placeholder="5,000,000" class="w-full border-2 border-gray-200 dark:border-slate-600 p-2.5 rounded-xl focus:border-emerald-500 outline-none font-mono font-bold text-emerald-600 dark:text-emerald-400 bg-transparent text-sm" dir="ltr" onkeyup="formatCurrency(this)">
            </div>

            <div class="md:col-span-1">
                <label class="block text-xs font-bold text-gray-500 dark:text-gray-400 mb-2">درصد پاداش (٪)</label>
                <div class="relative">
                    <input type="number" name="bonus_percent" required min="1" max="100" placeholder="10" class="w-full border-2 border-gray-200 dark:border-slate-600 p-2.5 rounded-xl focus:border-emerald-500 outline-none font-mono font-bold text-amber-600 dark:text-amber-400 bg-transparent text-sm" dir="ltr">
                    <span class="absolute right-4 top-3 text-gray-400 font-bold">٪</span>
                </div>
            </div>

            <div class="md:col-span-1">
                <button type="submit" class="w-full bg-emerald-500 hover:bg-emerald-600 text-white font-bold py-3 rounded-xl transition shadow-sm text-sm">ثبت سطح جدید</button>
            </div>
        </form>
    </div>

    <!-- لیست سطوح فعلی -->
    <div class="bg-white dark:bg-slate-800 rounded-3xl shadow-sm border border-gray-100 dark:border-slate-700 overflow-hidden">
        <div class="p-6 border-b border-gray-100 dark:border-slate-700 bg-gray-50 dark:bg-slate-800/80">
            <h2 class="text-base font-black text-gray-800 dark:text-white flex items-center gap-2">
                <span class="text-xl">📊</span> سطوح پاداش تعریف شده
            </h2>
        </div>
        
        <div class="overflow-x-auto p-4">
            <?php if(empty($bonuses)): ?>
                <div class="text-center py-10 text-gray-400 font-bold bg-gray-50 dark:bg-slate-700/30 rounded-2xl border border-dashed border-gray-200 dark:border-slate-600">هیچ سطح پاداشی تعریف نشده است.</div>
            <?php else: ?>
                <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 rounded-tr-xl">نام سطح</th>
                            <th class="px-4 py-3">حداقل مبلغ واریزی</th>
                            <th class="px-4 py-3 text-amber-600 dark:text-amber-400">درصد پاداش</th>
                            <th class="px-4 py-3 text-center">وضعیت</th>
                            <th class="px-4 py-3 text-center rounded-tl-xl">عملیات</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-gray-100 dark:divide-slate-700">
                        <?php foreach($bonuses as $b): ?>
                            <tr class="hover:bg-gray-50 dark:hover:bg-slate-700/30 transition <?php echo !$isBonusSystemActive ? 'opacity-60 grayscale' : ''; ?>">
                                <td class="px-4 py-4 font-black text-gray-800 dark:text-gray-200">
                                    ⭐ <?php echo htmlspecialchars($b['tier_name']); ?>
                                </td>
                                <td class="px-4 py-4 font-mono font-bold text-emerald-600 dark:text-emerald-400" dir="ltr">
                                    <?php echo number_format($b['min_amount']); ?>
                                </td>
                                <td class="px-4 py-4 font-black text-amber-600 dark:text-amber-400 text-lg" dir="ltr">
                                    <?php echo $b['bonus_percent']; ?>٪
                                </td>
                                <td class="px-4 py-4 text-center">
                                    <?php if(!$isBonusSystemActive): ?>
                                        <span class="bg-gray-100 text-gray-500 dark:bg-slate-700 dark:text-gray-400 px-3 py-1 rounded-lg text-xs font-bold border border-gray-200 dark:border-slate-600 cursor-not-allowed">غیرفعال (سراسری)</span>
                                    <?php else: ?>
                                        <form method="POST">
                                            <input type="hidden" name="action" value="toggle_tier">
                                            <input type="hidden" name="tier_id" value="<?php echo $b['id']; ?>">
                                            <?php if($b['is_active']): ?>
                                                <button type="submit" class="bg-green-100 text-green-700 dark:bg-emerald-900/30 dark:text-emerald-400 px-3 py-1 rounded-lg text-xs font-bold hover:bg-red-100 hover:text-red-700 transition border border-green-200 dark:border-emerald-800">فعال</button>
                                            <?php else: ?>
                                                <button type="submit" class="bg-gray-100 text-gray-500 dark:bg-slate-700 dark:text-gray-400 px-3 py-1 rounded-lg text-xs font-bold hover:bg-green-100 hover:text-green-700 transition border border-gray-200 dark:border-slate-600">خاموش</button>
                                            <?php endif; ?>
                                        </form>
                                    <?php endif; ?>
                                </td>
                                <td class="px-4 py-4 text-center flex justify-center gap-2">
                                    <!-- دکمه ویرایش -->
                                    <button type="button" <?php echo !$isBonusSystemActive ? 'disabled' : ''; ?> onclick="openEditModal(<?php echo $b['id']; ?>, '<?php echo htmlspecialchars($b['tier_name'], ENT_QUOTES); ?>', '<?php echo number_format($b['min_amount']); ?>', <?php echo $b['bonus_percent']; ?>)" class="text-blue-500 hover:text-blue-700 bg-blue-50 dark:bg-blue-900/30 p-2 rounded-lg transition disabled:cursor-not-allowed" title="ویرایش">
                                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"></path></svg>
                                    </button>
                                    <form method="POST" onsubmit="return confirm('حذف کامل این سطح؟');">
                                        <input type="hidden" name="action" value="delete_tier">
                                        <input type="hidden" name="tier_id" value="<?php echo $b['id']; ?>">
                                        <button type="submit" <?php echo !$isBonusSystemActive ? 'disabled' : ''; ?> class="text-rose-500 hover:text-rose-700 bg-rose-50 dark:bg-rose-900/30 p-2 rounded-lg transition disabled:cursor-not-allowed" title="حذف">
                                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path></svg>
                                        </button>
                                    </form>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endif; ?>
        </div>
    </div>

</div>

<!-- مودال ویرایش سطح بونوس -->
<div id="editModal" class="fixed inset-0 bg-black/60 backdrop-blur-sm hidden items-center justify-center z-50 px-4 transition-opacity opacity-0">
    <div class="bg-white dark:bg-slate-800 rounded-3xl shadow-2xl w-full max-w-lg overflow-hidden transform scale-95 transition-transform border border-gray-100 dark:border-slate-700" id="editModalContent">
        <div class="bg-blue-50 dark:bg-blue-900/30 px-6 py-4 border-b border-blue-100 dark:border-blue-800 flex justify-between items-center">
            <h3 class="font-black text-blue-800 dark:text-blue-300">ویرایش سطح پاداش</h3>
            <button type="button" onclick="closeEditModal()" class="text-blue-400 hover:text-rose-500 text-2xl transition">&times;</button>
        </div>
        <form method="POST" class="p-6 space-y-4">
            <input type="hidden" name="action" value="edit_tier">
            <input type="hidden" name="tier_id" id="edit_tier_id">
            
            <div>
                <label class="block text-sm font-bold text-gray-700 dark:text-gray-300 mb-2">نام سطح</label>
                <input type="text" name="tier_name" id="edit_tier_name" required class="w-full border-2 border-gray-200 dark:border-slate-600 p-3 rounded-xl focus:border-blue-500 outline-none font-bold text-sm bg-gray-50 dark:bg-slate-700 dark:text-white">
            </div>
            
            <div>
                <label class="block text-sm font-bold text-gray-700 dark:text-gray-300 mb-2">حداقل مبلغ شارژ (تومان)</label>
                <input type="text" name="min_amount" id="edit_min_amount" required class="w-full border-2 border-gray-200 dark:border-slate-600 p-3 rounded-xl focus:border-blue-500 outline-none font-mono font-bold text-emerald-600 dark:text-emerald-400 bg-transparent" dir="ltr" onkeyup="formatCurrency(this)">
            </div>

            <div>
                <label class="block text-sm font-bold text-gray-700 dark:text-gray-300 mb-2">درصد پاداش (٪)</label>
                <input type="number" name="bonus_percent" id="edit_bonus_percent" required min="1" max="100" class="w-full border-2 border-gray-200 dark:border-slate-600 p-3 rounded-xl focus:border-blue-500 outline-none font-mono font-bold text-amber-600 dark:text-amber-400 bg-transparent" dir="ltr">
            </div>

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

<script>
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 toggleBonusDateInputs(isActive) {
    const container = document.getElementById('bonusDateInputsContainer');
    if (isActive) {
        container.classList.remove('opacity-50', 'pointer-events-none');
        document.getElementById('bonus_date_input').required = true;
        document.getElementById('bonus_time_input').required = true;
    } else {
        container.classList.add('opacity-50', 'pointer-events-none');
        document.getElementById('bonus_date_input').required = false;
        document.getElementById('bonus_time_input').required = false;
    }
}

const editModal = document.getElementById('editModal');
const editModalContent = document.getElementById('editModalContent');

function openEditModal(id, name, amount, percent) {
    document.getElementById('edit_tier_id').value = id;
    document.getElementById('edit_tier_name').value = name;
    document.getElementById('edit_min_amount').value = amount;
    document.getElementById('edit_bonus_percent').value = percent;
    
    editModal.classList.remove('hidden');
    editModal.classList.add('flex');
    setTimeout(() => {
        editModal.classList.remove('opacity-0');
        editModalContent.classList.remove('scale-95');
    }, 10);
}

function closeEditModal() {
    editModal.classList.add('opacity-0');
    editModalContent.classList.add('scale-95');
    setTimeout(() => {
        editModal.classList.add('hidden');
        editModal.classList.remove('flex');
    }, 300);
}

editModal.addEventListener('click', function(e) {
    if (e.target === editModal) closeEditModal();
});
</script>

<?php require_once '../includes/footer.php'; ?>