<?php
// modules/provider.php
if (session_status() === PHP_SESSION_NONE) { session_start(); }

require_once '../includes/auth.php';
checkLogin();

// این ماژول فقط مختص مدیریت کل سیستم است
if (!isAdmin()) {
    die("دسترسی غیرمجاز. این بخش فقط مختص مدیریت کل سیستم است.");
}

require_once '../config/db.php';

$msg = $_GET['msg'] ?? '';
$error = $_GET['error'] ?? '';

// ==========================================
// 🛡️ ۱. ارتقای خودکار دیتابیس (Migration)
// ==========================================
try {
    // ساخت جداول در صورت عدم وجود
    $pdo->exec("CREATE TABLE IF NOT EXISTS `provider_settlements` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `server_id` int(11) NOT NULL DEFAULT 1,
      `gb_amount` int(11) NOT NULL,
      `paid_amount` bigint(20) NOT NULL,
      `description` varchar(255) DEFAULT NULL,
      `created_at` timestamp NOT NULL DEFAULT current_timestamp(),
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;");

    $pdo->exec("CREATE TABLE IF NOT EXISTS `external_usages` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `server_id` int(11) NOT NULL DEFAULT 1,
      `gb_amount` int(11) NOT NULL,
      `cost_amount` bigint(20) NOT NULL,
      `description` varchar(255) DEFAULT NULL,
      `created_at` timestamp NOT NULL DEFAULT current_timestamp(),
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;");

    // اگر جداول از قبل بودند، ستون server_id به آنها اضافه می‌شود (بدون پاک شدن دیتای قبلی)
    $pdo->exec("ALTER TABLE `provider_settlements` ADD COLUMN IF NOT EXISTS `server_id` INT(11) NOT NULL DEFAULT 1 AFTER `id`;");
    $pdo->exec("ALTER TABLE `external_usages` ADD COLUMN IF NOT EXISTS `server_id` INT(11) NOT NULL DEFAULT 1 AFTER `id`;");
} catch (PDOException $e) {}

// ==========================================
// ⚙️ ۲. استخراج لیست سرورها و سرور فعال
// ==========================================
$serversList = $pdo->query("SELECT * FROM servers ORDER BY id ASC")->fetchAll(PDO::FETCH_ASSOC);
$active_server_id = $_GET['server_id'] ?? ($serversList[0]['id'] ?? 1);

// ==========================================
// 📝 ۳. پردازش فرم‌ها (ثبت، ویرایش و حذف)
// ==========================================
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    $sId = $_POST['server_id'] ?? $active_server_id;
    
    if ($action === 'add_settlement') {
        $gb = (int)$_POST['gb_amount'];
        $paid = (int)str_replace(',', '', $_POST['paid_amount']);
        $desc = $_POST['description'];
        $stmt = $pdo->prepare("INSERT INTO provider_settlements (server_id, gb_amount, paid_amount, description) VALUES (?, ?, ?, ?)");
        $stmt->execute([$sId, $gb, $paid, $desc]);
        header("Location: provider.php?server_id=$sId&msg=success"); exit;
    }
    elseif ($action === 'edit_settlement') {
        $id = $_POST['id'];
        $gb = (int)$_POST['gb_amount'];
        $paid = (int)str_replace(',', '', $_POST['paid_amount']);
        $desc = $_POST['description'];
        $stmt = $pdo->prepare("UPDATE provider_settlements SET gb_amount=?, paid_amount=?, description=? WHERE id=? AND server_id=?");
        $stmt->execute([$gb, $paid, $desc, $id, $sId]);
        header("Location: provider.php?server_id=$sId&msg=success"); exit;
    }
    elseif ($action === 'delete_settlement') {
        $id = $_POST['id'];
        $stmt = $pdo->prepare("DELETE FROM provider_settlements WHERE id=? AND server_id=?");
        $stmt->execute([$id, $sId]);
        header("Location: provider.php?server_id=$sId&msg=success"); exit;
    }
    elseif ($action === 'add_external') {
        $gb = (int)$_POST['gb_amount'];
        $cost = (int)str_replace(',', '', $_POST['cost_amount']);
        $desc = $_POST['description'];
        $stmt = $pdo->prepare("INSERT INTO external_usages (server_id, gb_amount, cost_amount, description) VALUES (?, ?, ?, ?)");
        $stmt->execute([$sId, $gb, $cost, $desc]);
        header("Location: provider.php?server_id=$sId&msg=success"); exit;
    }
    elseif ($action === 'delete_external') {
        $id = $_POST['id'];
        $stmt = $pdo->prepare("DELETE FROM external_usages WHERE id=? AND server_id=?");
        $stmt->execute([$id, $sId]);
        header("Location: provider.php?server_id=$sId&msg=success"); exit;
    }
}

// ==========================================
// 📊 ۴. محاسبات مالی اختصاصی سرور
// ==========================================
$settlements = $pdo->prepare("SELECT * FROM provider_settlements WHERE server_id = ? ORDER BY id DESC");
$settlements->execute([$active_server_id]);
$settlements = $settlements->fetchAll(PDO::FETCH_ASSOC);

$externals = $pdo->prepare("SELECT * FROM external_usages WHERE server_id = ? ORDER BY id DESC");
$externals->execute([$active_server_id]);
$externals = $externals->fetchAll(PDO::FETCH_ASSOC);

// استخراج حجم فروخته شده از انبار (با پشتیبانی از دیتای قدیمی که server_id نداشتند)
$invStmt = $pdo->prepare("SELECT SUM(volume) FROM inventory WHERE status = 'sold' AND IFNULL(server_id, 1) = ?");
$invStmt->execute([$active_server_id]);
$invGb = (int)$invStmt->fetchColumn();

$extGb = $extCost = 0;
foreach($externals as $e) { $extGb += $e['gb_amount']; $extCost += $e['cost_amount']; }

$setGb = $setPaid = 0;
foreach($settlements as $s) { $setGb += $s['gb_amount']; $setPaid += $s['paid_amount']; }

$totalSoldGb = $invGb + $extGb;
$remainingGb = $totalSoldGb - $setGb;

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

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<style>
    .custom-scrollbar::-webkit-scrollbar { width: 4px; height: 4px; }
    .custom-scrollbar::-webkit-scrollbar-thumb { background: #cbd5e1; border-radius: 10px; }
    html.dark .custom-scrollbar::-webkit-scrollbar-thumb { background: #475569; }
</style>

<div class="w-full pb-10 px-4 md:px-0">
    
    <?php if($msg === 'success'): ?>
        <div class="bg-emerald-50 border border-emerald-200 text-emerald-800 px-5 py-4 rounded-2xl mb-6 font-bold shadow-sm flex items-center gap-2">
            <span>✅</span> عملیات با موفقیت انجام شد.
        </div>
    <?php endif; ?>

    <div class="bg-white dark:bg-slate-800 rounded-3xl p-6 md:p-8 mb-6 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 -right-5 -top-5 opacity-[0.03] dark:opacity-[0.05] text-9xl pointer-events-none">🏢</div>
        <div class="relative z-10 text-center md:text-right mb-4 md:mb-0">
            <h1 class="text-2xl font-black text-gray-900 dark:text-white flex items-center gap-2">مدیریت تامین‌کنندگان و سرورها</h1>
            <p class="text-gray-500 text-xs font-bold mt-1">حساب‌وکتاب دقیق هزینه‌ها و بدهی‌ها به تفکیک سرور</p>
        </div>
        <form method="GET" class="relative z-10 w-full md:w-auto">
            <select name="server_id" onchange="this.form.submit()" class="w-full md:w-auto border-2 border-blue-600 rounded-xl px-4 py-2.5 text-sm font-bold text-blue-700 dark:text-blue-400 bg-blue-50 dark:bg-blue-900/20 focus:outline-none cursor-pointer shadow-sm">
                <?php if(empty($serversList)): ?>
                    <option value="">سروری یافت نشد</option>
                <?php else: ?>
                    <?php foreach($serversList as $srv): ?>
                        <option value="<?= $srv['id'] ?>" <?= $srv['id'] == $active_server_id ? 'selected' : '' ?>>
                            تامین‌کننده: <?= htmlspecialchars($srv['name']) ?>
                        </option>
                    <?php endforeach; ?>
                <?php endif; ?>
            </select>
        </form>
    </div>

    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
        
        <div class="bg-gradient-to-br from-blue-50 to-indigo-50 dark:from-slate-800 dark:to-slate-800 rounded-3xl p-5 border border-blue-100 dark:border-slate-700 shadow-sm relative overflow-hidden group">
            <div class="absolute -left-4 -bottom-4 opacity-10 text-6xl group-hover:scale-110 transition-transform duration-500">📡</div>
            <div class="text-xs font-bold text-blue-600 dark:text-blue-400 mb-2 flex items-center gap-1.5 relative z-10">
                <span class="relative flex h-2 w-2">
                  <span class="animate-ping absolute inline-flex h-full w-full rounded-full bg-blue-400 opacity-75"></span>
                  <span class="relative inline-flex rounded-full h-2 w-2 bg-blue-500"></span>
                </span>
                حجم کل مصرفی در سرور
            </div>
            <div id="live_usage_value" class="h-8 flex items-center relative z-10">
                <span class="animate-pulse text-xs text-gray-400 font-bold">در حال استعلام لایو...</span>
            </div>
        </div>
        
        <div class="bg-white dark:bg-slate-800 rounded-3xl p-5 border border-gray-100 dark:border-slate-700 shadow-sm">
            <div class="text-xs font-bold text-gray-500 dark:text-gray-400 mb-2 flex items-center gap-1">📊 کل حجم فروخته شده</div>
            <div class="text-2xl font-black text-gray-800 dark:text-white" dir="ltr"><?= number_format($totalSoldGb) ?> <span class="text-xs font-normal text-gray-400">GB</span></div>
            <div class="text-[9px] text-gray-400 mt-1 font-mono text-right">انبار + متفرقه</div>
        </div>

        <div class="bg-white dark:bg-slate-800 rounded-3xl p-5 border border-emerald-100 dark:border-slate-700 shadow-sm">
            <div class="text-xs font-bold text-emerald-600 dark:text-emerald-400 mb-2 flex items-center gap-1">✔️ حجم تسویه شده</div>
            <div class="text-2xl font-black text-emerald-600 dark:text-emerald-400" dir="ltr"><?= number_format($setGb) ?> <span class="text-xs font-normal text-emerald-400/50">GB</span></div>
            <div class="text-[9px] text-emerald-500 mt-1 font-mono text-right" dir="ltr"><?= number_format($setPaid) ?> T</div>
        </div>

        <div class="bg-white dark:bg-slate-800 rounded-3xl p-5 border border-rose-100 dark:border-slate-700 shadow-sm">
            <div class="text-xs font-bold text-rose-500 mb-2 flex items-center gap-1">⚠️ بدهی به تامین‌کننده</div>
            <div class="text-2xl font-black text-rose-600 dark:text-rose-400" dir="ltr"><?= number_format($remainingGb) ?> <span class="text-xs font-normal text-rose-400/50">GB</span></div>
            <div class="text-[9px] text-rose-400 mt-1 text-right">حجم باقیمانده برای تسویه</div>
        </div>
    </div>

    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
        
        <div class="bg-white dark:bg-slate-800 rounded-3xl shadow-sm border border-gray-100 dark:border-slate-700 overflow-hidden flex flex-col">
            <div class="bg-emerald-50 dark:bg-emerald-900/20 p-5 border-b border-emerald-100 dark:border-slate-700 flex justify-between items-center">
                <h2 class="font-black text-emerald-700 dark:text-emerald-400 flex items-center gap-2 text-sm">💰 تسویه‌حساب‌های سرور</h2>
                <button onclick="openModal('settlementModal')" class="bg-emerald-600 hover:bg-emerald-700 text-white text-[11px] font-bold px-3 py-1.5 rounded-lg transition shadow-sm">+ ثبت تسویه</button>
            </div>
            <div class="p-0 overflow-x-auto flex-1 custom-scrollbar">
                <table class="w-full text-sm text-right" dir="rtl">
                    <thead class="bg-gray-50 dark:bg-slate-700/50 text-[10px] text-gray-500 uppercase tracking-wider">
                        <tr>
                            <th class="px-4 py-3 font-black">تاریخ و بابت</th>
                            <th class="px-4 py-3 font-black">حجم تسویه</th>
                            <th class="px-4 py-3 font-black">مبلغ پرداختی</th>
                            <th class="px-4 py-3 font-black text-center">عملیات</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-gray-100 dark:divide-slate-700 text-gray-700 dark:text-gray-300">
                        <?php foreach($settlements as $s): ?>
                        <tr class="hover:bg-gray-50 dark:hover:bg-slate-700/30 transition">
                            <td class="px-4 py-3">
                                <div class="text-xs font-bold text-gray-800 dark:text-gray-200"><?= htmlspecialchars($s['description']) ?: 'بدون توضیحات' ?></div>
                                <div class="font-mono text-[9px] text-gray-400 mt-1" dir="ltr"><?= substr($s['created_at'], 0, 16) ?></div>
                            </td>
                            <td class="px-4 py-3 font-black text-emerald-600 dark:text-emerald-400" dir="ltr"><?= number_format($s['gb_amount']) ?> <span class="text-[9px] font-normal">GB</span></td>
                            <td class="px-4 py-3 font-mono font-bold" dir="ltr"><?= number_format($s['paid_amount']) ?> <span class="text-[9px] text-gray-400">T</span></td>
                            <td class="px-4 py-3 text-center">
                                <div class="flex justify-center gap-2">
                                    <button onclick="editSettlement(<?= $s['id'] ?>, <?= $s['gb_amount'] ?>, '<?= $s['paid_amount'] ?>', '<?= htmlspecialchars($s['description'], ENT_QUOTES) ?>')" class="text-blue-500 hover:text-blue-700 p-1 bg-blue-50 dark:bg-slate-700 rounded transition" 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" class="inline" onsubmit="return confirm('آیا از حذف این تسویه اطمینان دارید؟')">
                                        <input type="hidden" name="action" value="delete_settlement">
                                        <input type="hidden" name="server_id" value="<?= $active_server_id ?>">
                                        <input type="hidden" name="id" value="<?= $s['id'] ?>">
                                        <button type="submit" class="text-rose-500 hover:text-rose-700 p-1 bg-rose-50 dark:bg-slate-700 rounded transition" 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>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                        <?php if(empty($settlements)): ?>
                        <tr><td colspan="4" class="text-center py-10 text-xs font-bold text-gray-400">هیچ تسویه‌ای ثبت نشده است.</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <div class="bg-white dark:bg-slate-800 rounded-3xl shadow-sm border border-gray-100 dark:border-slate-700 overflow-hidden flex flex-col">
            <div class="bg-amber-50 dark:bg-amber-900/20 p-5 border-b border-amber-100 dark:border-slate-700 flex justify-between items-center">
                <h2 class="font-black text-amber-700 dark:text-amber-400 flex items-center gap-2 text-sm">🔌 مصارف متفرقه و تست</h2>
                <button onclick="openModal('externalModal')" class="bg-amber-500 hover:bg-amber-600 text-white text-[11px] font-bold px-3 py-1.5 rounded-lg transition shadow-sm">+ ثبت مصرف</button>
            </div>
            <div class="p-0 overflow-x-auto flex-1 custom-scrollbar">
                <table class="w-full text-sm text-right" dir="rtl">
                    <thead class="bg-gray-50 dark:bg-slate-700/50 text-[10px] text-gray-500 uppercase tracking-wider">
                        <tr>
                            <th class="px-4 py-3 font-black">تاریخ و بابت</th>
                            <th class="px-4 py-3 font-black">حجم ثبت شده</th>
                            <th class="px-4 py-3 font-black">ارزش ریالی</th>
                            <th class="px-4 py-3 font-black text-center">عملیات</th>
                        </tr>
                    </thead>
                    <tbody class="divide-y divide-gray-100 dark:divide-slate-700 text-gray-700 dark:text-gray-300">
                        <?php foreach($externals as $e): ?>
                        <tr class="hover:bg-gray-50 dark:hover:bg-slate-700/30 transition">
                            <td class="px-4 py-3">
                                <div class="text-xs font-bold text-gray-800 dark:text-gray-200"><?= htmlspecialchars($e['description']) ?: 'بدون توضیحات' ?></div>
                                <div class="font-mono text-[9px] text-gray-400 mt-1" dir="ltr"><?= substr($e['created_at'], 0, 16) ?></div>
                            </td>
                            <td class="px-4 py-3 font-black text-amber-600 dark:text-amber-400" dir="ltr"><?= number_format($e['gb_amount']) ?> <span class="text-[9px] font-normal">GB</span></td>
                            <td class="px-4 py-3 font-mono font-bold" dir="ltr"><?= number_format($e['cost_amount']) ?> <span class="text-[9px] text-gray-400">T</span></td>
                            <td class="px-4 py-3 text-center">
                                <form method="POST" class="inline" onsubmit="return confirm('حذف شود؟')">
                                    <input type="hidden" name="action" value="delete_external">
                                    <input type="hidden" name="server_id" value="<?= $active_server_id ?>">
                                    <input type="hidden" name="id" value="<?= $e['id'] ?>">
                                    <button type="submit" class="text-rose-500 hover:text-rose-700 p-1 bg-rose-50 dark:bg-slate-700 rounded transition" 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; ?>
                        <?php if(empty($externals)): ?>
                        <tr><td colspan="4" class="text-center py-10 text-xs font-bold text-gray-400">هیچ مصرف متفرقه‌ای ثبت نشده است.</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<div id="settlementModal" class="fixed inset-0 bg-black/60 hidden items-center justify-center z-[100] px-4 backdrop-blur-sm">
    <div class="bg-white dark:bg-slate-800 rounded-3xl w-full max-w-sm p-6 shadow-2xl border border-gray-100 dark:border-slate-700">
        <h3 class="font-black text-emerald-600 dark:text-emerald-400 mb-5 text-center text-lg flex items-center justify-center gap-2" id="settlementModalTitle">💰 ثبت تسویه‌حساب جدید</h3>
        <form method="POST">
            <input type="hidden" name="action" id="settlementAction" value="add_settlement">
            <input type="hidden" name="server_id" value="<?= $active_server_id ?>">
            <input type="hidden" name="id" id="settlementId" value="">
            <div class="space-y-4">
                <div>
                    <label class="text-xs font-bold text-gray-600 dark:text-gray-300 block mb-1.5">حجم تسویه شده (GB)</label>
                    <input type="number" name="gb_amount" id="set_gb" required class="w-full border border-gray-200 dark:border-slate-600 p-2.5 rounded-xl bg-gray-50 dark:bg-slate-700 dark:text-white outline-none focus:border-emerald-500 transition" dir="ltr">
                </div>
                <div>
                    <label class="text-xs font-bold text-gray-600 dark:text-gray-300 block mb-1.5">مبلغ پرداختی (تومان)</label>
                    <input type="text" name="paid_amount" id="set_paid" required onkeyup="formatCurrency(this)" class="w-full border border-gray-200 dark:border-slate-600 p-2.5 rounded-xl bg-gray-50 dark:bg-slate-700 dark:text-white font-mono font-black text-emerald-600 outline-none focus:border-emerald-500 transition" dir="ltr">
                </div>
                <div>
                    <label class="text-xs font-bold text-gray-600 dark:text-gray-300 block mb-1.5">بابت / توضیحات</label>
                    <input type="text" name="description" id="set_desc" placeholder="مثلا: واریز به حساب مدیریت..." class="w-full border border-gray-200 dark:border-slate-600 p-2.5 rounded-xl bg-gray-50 dark:bg-slate-700 dark:text-white outline-none focus:border-emerald-500 transition text-sm">
                </div>
            </div>
            <div class="flex gap-3 mt-6 pt-2">
                <button type="button" onclick="closeModal('settlementModal')" class="flex-1 bg-gray-100 dark:bg-slate-700 text-gray-600 dark:text-white p-3 rounded-xl font-bold transition hover:bg-gray-200 dark:hover:bg-slate-600">لغو</button>
                <button type="submit" class="flex-1 bg-emerald-600 hover:bg-emerald-700 transition text-white p-3 rounded-xl font-bold shadow-sm">ذخیره اطلاعات</button>
            </div>
        </form>
    </div>
</div>

<div id="externalModal" class="fixed inset-0 bg-black/60 hidden items-center justify-center z-[100] px-4 backdrop-blur-sm">
    <div class="bg-white dark:bg-slate-800 rounded-3xl w-full max-w-sm p-6 shadow-2xl border border-gray-100 dark:border-slate-700">
        <h3 class="font-black text-amber-600 dark:text-amber-500 mb-5 text-center text-lg flex items-center justify-center gap-2">🔌 ثبت مصرف متفرقه</h3>
        <form method="POST">
            <input type="hidden" name="action" value="add_external">
            <input type="hidden" name="server_id" value="<?= $active_server_id ?>">
            <div class="space-y-4">
                <div>
                    <label class="text-xs font-bold text-gray-600 dark:text-gray-300 block mb-1.5">حجم مصرفی (GB)</label>
                    <input type="number" name="gb_amount" required class="w-full border border-gray-200 dark:border-slate-600 p-2.5 rounded-xl bg-gray-50 dark:bg-slate-700 dark:text-white outline-none focus:border-amber-500 transition" dir="ltr">
                </div>
                <div>
                    <label class="text-xs font-bold text-gray-600 dark:text-gray-300 block mb-1.5">ارزش ریالی (تومان)</label>
                    <input type="text" name="cost_amount" required onkeyup="formatCurrency(this)" class="w-full border border-gray-200 dark:border-slate-600 p-2.5 rounded-xl bg-gray-50 dark:bg-slate-700 dark:text-white font-mono font-black text-amber-600 outline-none focus:border-amber-500 transition" dir="ltr">
                </div>
                <div>
                    <label class="text-xs font-bold text-gray-600 dark:text-gray-300 block mb-1.5">توضیحات (پلتفرم یا شخص)</label>
                    <input type="text" name="description" placeholder="مثلا: مصرف شخصی یا تست سرور" required class="w-full border border-gray-200 dark:border-slate-600 p-2.5 rounded-xl bg-gray-50 dark:bg-slate-700 dark:text-white outline-none focus:border-amber-500 transition text-sm">
                </div>
            </div>
            <div class="flex gap-3 mt-6 pt-2">
                <button type="button" onclick="closeModal('externalModal')" class="flex-1 bg-gray-100 dark:bg-slate-700 text-gray-600 dark:text-white p-3 rounded-xl font-bold transition hover:bg-gray-200 dark:hover:bg-slate-600">لغو</button>
                <button type="submit" class="flex-1 bg-amber-500 hover:bg-amber-600 transition text-white p-3 rounded-xl font-bold shadow-sm">ثبت مصرف</button>
            </div>
        </form>
    </div>
</div>

<script>
    // تابع فرمت‌دهی پول
    function formatCurrency(input) {
        let value = input.value.replace(/,/g, '').replace(/[^0-9]/g, '');
        if (value !== '') { input.value = Number(value).toLocaleString(); } 
        else { input.value = ''; }
    }

    // باز و بسته کردن مودال‌ها
    function openModal(id) { 
        document.getElementById(id).classList.remove('hidden'); 
        document.getElementById(id).classList.add('flex'); 
    }
    function closeModal(id) { 
        document.getElementById(id).classList.add('hidden'); 
        document.getElementById(id).classList.remove('flex'); 
    }

    // مقداردهی فرم ویرایش تسویه
    function editSettlement(id, gb, paid, desc) {
        document.getElementById('settlementModalTitle').innerHTML = '✏️ ویرایش تسویه‌حساب';
        document.getElementById('settlementAction').value = 'edit_settlement';
        document.getElementById('settlementId').value = id;
        document.getElementById('set_gb').value = gb;
        
        let pInput = document.getElementById('set_paid');
        pInput.value = paid;
        formatCurrency(pInput);
        
        document.getElementById('set_desc').value = desc;
        openModal('settlementModal');
    }

    // دریافت وضعیت لایو از سرور اصلی بدون رفرش صفحه
    $(document).ready(function() {
        let sId = <?= $active_server_id ?>;
        if(sId) {
            $.ajax({
                url: 'pasarguard/pasarguard_api.php',
                type: 'GET',
                data: { ajax_call: 'users_list', server_id: sId },
                dataType: 'json'
            }).done(function(res) {
                if(res && !res.error) {
                    let users = Array.isArray(res) ? res : (res.users || res.data || []);
                    let totalBytes = 0;
                    users.forEach(u => { totalBytes += parseInt(u.used_traffic || 0); });
                    let gb = (totalBytes / (1024 * 1024 * 1024)).toFixed(2);
                    
                    $('#live_usage_value').html(`<span dir="ltr" class="text-3xl font-black text-blue-600 dark:text-blue-400 drop-shadow-sm">${gb} <span class="text-sm text-blue-400 dark:text-blue-500 font-bold">GB</span></span>`);
                } else {
                    $('#live_usage_value').html('<span class="text-rose-500 text-xs font-bold mt-2 px-2 py-1 bg-rose-50 dark:bg-rose-900/30 rounded-lg">❌ خطا در دریافت از سرور</span>');
                }
            }).fail(function() {
                $('#live_usage_value').html('<span class="text-rose-500 text-xs font-bold mt-2 px-2 py-1 bg-rose-50 dark:bg-rose-900/30 rounded-lg">❌ خطای ارتباط با سرور</span>');
            });
        }
    });
</script>

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