<?php
// شروع session قبل از هر چیز
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once '../config.php';

// بررسی لاگین
if (!isLoggedIn()) {
    redirect('../login.php');
}

// بررسی دسترسی ادمین
if (!isAdmin()) {
    setMessage('دسترسی غیرمجاز', 'error');
    redirect('../login.php');
}

$page_title = 'مدیریت نمایندگان';

// افزودن نماینده جدید
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'add') {
    $username = $_POST['username'] ?? '';
    $password = $_POST['password'] ?? '';
    $full_name = $_POST['full_name'] ?? '';
    $email = $_POST['email'] ?? '';
    $phone = $_POST['phone'] ?? '';
    $panel_id = (int)($_POST['panel_id'] ?? 0);
    $traffic_limit = (int)($_POST['traffic_limit'] ?? 0) * 1024 * 1024 * 1024; // تبدیل به بایت
    $expiry_days = (int)($_POST['expiry_days'] ?? 0);
    $expiry_date = $expiry_days > 0 ? date('Y-m-d H:i:s', time() + ($expiry_days * 24 * 60 * 60)) : null;
    
    $default_remark = trim($_POST['default_remark'] ?? '');
    $price_per_gb = (float)($_POST['price_per_gb'] ?? 0);
    $price_per_day = (float)($_POST['price_per_day'] ?? 0);
    $discount_percent = max(0, min(100, (int)($_POST['discount_percent'] ?? 0)));
    $rank = isset($_POST['rank']) && $_POST['rank'] !== '' ? (int)$_POST['rank'] : null;
    if (empty($username) || empty($password) || $panel_id === 0) {
        setMessage('لطفاً فیلدهای ضروری را پر کنید', 'error');
    } else {
        try {
            $hashedPassword = hashPassword($password);
            $has_rank_col = $pdo->query("SHOW COLUMNS FROM representatives LIKE 'rank'")->rowCount() > 0;
            if ($has_rank_col) {
                $stmt = $pdo->prepare("INSERT INTO representatives (username, password, full_name, email, phone, panel_id, traffic_limit, expiry_date, default_remark, price_per_gb, price_per_day, discount_percent, rank) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
                $stmt->execute([$username, $hashedPassword, $full_name, $email, $phone, $panel_id, $traffic_limit, $expiry_date, $default_remark ?: null, $price_per_gb, $price_per_day, $discount_percent, $rank]);
            } else {
                $stmt = $pdo->prepare("INSERT INTO representatives (username, password, full_name, email, phone, panel_id, traffic_limit, expiry_date, default_remark, price_per_gb, price_per_day, discount_percent) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
                $stmt->execute([$username, $hashedPassword, $full_name, $email, $phone, $panel_id, $traffic_limit, $expiry_date, $default_remark ?: null, $price_per_gb, $price_per_day, $discount_percent]);
            }
            $rep_id = $pdo->lastInsertId();
            
            // افزودن inbound های مجاز (پنل همانی است که انتخاب شده)
            $add_panel_id = (int)($_POST['panel_id'] ?? 0);
            if ($add_panel_id > 0 && isset($_POST['inbound_ids']) && is_array($_POST['inbound_ids'])) {
                $limits = isset($_POST['inbound_limit']) && is_array($_POST['inbound_limit']) ? $_POST['inbound_limit'] : [];
                foreach ($_POST['inbound_ids'] as $inbound_id) {
                    $inbound_id = (int)$inbound_id;
                    if ($inbound_id > 0) {
                        $user_limit = (int)($limits[$inbound_id] ?? 0);
                        try {
                            $stmt = $pdo->prepare("INSERT INTO representative_inbounds (representative_id, panel_id, inbound_id, user_limit) VALUES (?, ?, ?, ?)");
                            $stmt->execute([$rep_id, $add_panel_id, $inbound_id, $user_limit]);
                        } catch (Exception $e) {
                            $stmt = $pdo->prepare("INSERT INTO representative_inbounds (representative_id, inbound_id, user_limit) VALUES (?, ?, ?)");
                            $stmt->execute([$rep_id, $inbound_id, $user_limit]);
                        }
                    }
                }
            }
            
            setMessage('نماینده با موفقیت افزوده شد');
            redirect('representatives.php');
        } catch (Exception $e) {
            setMessage('خطا در افزودن نماینده: ' . $e->getMessage(), 'error');
        }
    }
}

// به‌روزرسانی نماینده
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'update') {
    $id = (int)($_POST['id'] ?? 0);
    $traffic_limit = (int)($_POST['traffic_limit'] ?? 0) * 1024 * 1024 * 1024;
    $expiry_days = (int)($_POST['expiry_days'] ?? 0);
    $expiry_date = $expiry_days > 0 ? date('Y-m-d H:i:s', time() + ($expiry_days * 24 * 60 * 60)) : null;
    $default_remark = trim($_POST['default_remark'] ?? '');
    $price_per_gb = (float)($_POST['price_per_gb'] ?? 0);
    $price_per_day = (float)($_POST['price_per_day'] ?? 0);
    $discount_percent = max(0, min(100, (int)($_POST['discount_percent'] ?? 0)));
    $rank = isset($_POST['rank']) && $_POST['rank'] !== '' ? (int)$_POST['rank'] : null;
    
    try {
        $has_rank_col = $pdo->query("SHOW COLUMNS FROM representatives LIKE 'rank'")->rowCount() > 0;
        if ($has_rank_col) {
            $stmt = $pdo->prepare("UPDATE representatives SET traffic_limit = ?, expiry_date = ?, default_remark = ?, price_per_gb = ?, price_per_day = ?, discount_percent = ?, rank = ? WHERE id = ?");
            $stmt->execute([$traffic_limit, $expiry_date, $default_remark ?: null, $price_per_gb, $price_per_day, $discount_percent, $rank, $id]);
        } else {
            $stmt = $pdo->prepare("UPDATE representatives SET traffic_limit = ?, expiry_date = ?, default_remark = ?, price_per_gb = ?, price_per_day = ?, discount_percent = ? WHERE id = ?");
            $stmt->execute([$traffic_limit, $expiry_date, $default_remark ?: null, $price_per_gb, $price_per_day, $discount_percent, $id]);
        }
        
        // به‌روزرسانی inbound های مجاز (از یک یا چند پنل)
        $pdo->prepare("DELETE FROM representative_inbounds WHERE representative_id = ?")->execute([$id]);
        $has_panel_id = false;
        if (!empty($_POST['ri_check']) && is_array($_POST['ri_check'])) {
            foreach ($_POST['ri_check'] as $p_id => $inbounds) {
                $p_id = (int)$p_id;
                if ($p_id <= 0 || !is_array($inbounds)) continue;
                $limits = isset($_POST['ri_limit'][$p_id]) && is_array($_POST['ri_limit'][$p_id]) ? $_POST['ri_limit'][$p_id] : [];
                foreach ($inbounds as $inbound_id => $v) {
                    $inbound_id = (int)$inbound_id;
                    if ($inbound_id <= 0) continue;
                    $user_limit = (int)($limits[$inbound_id] ?? 0);
                    try {
                        $stmt = $pdo->prepare("INSERT INTO representative_inbounds (representative_id, panel_id, inbound_id, user_limit) VALUES (?, ?, ?, ?)");
                        $stmt->execute([$id, $p_id, $inbound_id, $user_limit]);
                        $has_panel_id = true;
                    } catch (Exception $e) {
                        $stmt = $pdo->prepare("INSERT INTO representative_inbounds (representative_id, inbound_id, user_limit) VALUES (?, ?, ?)");
                        $stmt->execute([$id, $inbound_id, $user_limit]);
                    }
                }
            }
        }
        if (!$has_panel_id && isset($_POST['inbound_ids']) && is_array($_POST['inbound_ids'])) {
            $limits = isset($_POST['inbound_limit']) && is_array($_POST['inbound_limit']) ? $_POST['inbound_limit'] : [];
            $rep_panel = (int)($pdo->query("SELECT panel_id FROM representatives WHERE id = " . (int)$id)->fetch()['panel_id'] ?? 0);
            foreach ($_POST['inbound_ids'] as $inbound_id) {
                $inbound_id = (int)$inbound_id;
                if ($inbound_id > 0 && $rep_panel > 0) {
                    $user_limit = (int)($limits[$inbound_id] ?? 0);
                    try {
                        $stmt = $pdo->prepare("INSERT INTO representative_inbounds (representative_id, panel_id, inbound_id, user_limit) VALUES (?, ?, ?, ?)");
                        $stmt->execute([$id, $rep_panel, $inbound_id, $user_limit]);
                    } catch (Exception $e) {
                        $stmt = $pdo->prepare("INSERT INTO representative_inbounds (representative_id, inbound_id, user_limit) VALUES (?, ?, ?)");
                        $stmt->execute([$id, $inbound_id, $user_limit]);
                    }
                }
            }
        }
        
        setMessage('نماینده با موفقیت به‌روزرسانی شد');
        redirect('representatives.php');
    } catch (Exception $e) {
        setMessage('خطا در به‌روزرسانی: ' . $e->getMessage(), 'error');
    }
}

// حذف نماینده
if (isset($_GET['delete'])) {
    $id = (int)$_GET['delete'];
    try {
        $stmt = $pdo->prepare("DELETE FROM representatives WHERE id = ?");
        $stmt->execute([$id]);
        setMessage('نماینده با موفقیت حذف شد');
        redirect('representatives.php');
    } catch (Exception $e) {
        setMessage('خطا در حذف نماینده: ' . $e->getMessage(), 'error');
    }
}

// تغییر وضعیت
if (isset($_GET['toggle'])) {
    $id = (int)$_GET['toggle'];
    $stmt = $pdo->prepare("UPDATE representatives SET status = IF(status = 'active', 'inactive', 'active') WHERE id = ?");
    $stmt->execute([$id]);
    redirect('representatives.php');
}

// به‌روزرسانی (refresh)
if (isset($_GET['refresh'])) {
    $id = (int)$_GET['refresh'];
    setMessage('به‌روزرسانی انجام شد');
    redirect('representatives.php');
}

// واریز به کیف پول نماینده
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'wallet_deposit') {
    $rep_id = (int)($_POST['rep_id'] ?? 0);
    $amount = (float)($_POST['amount'] ?? 0);
    $description = trim($_POST['description'] ?? 'واریز توسط ادمین');
    if ($rep_id > 0 && $amount > 0) {
        try {
            walletDeposit($pdo, $rep_id, $amount, 'admin_deposit', null, $description ?: 'واریز توسط ادمین');
            setMessage('مبلغ ' . number_format($amount) . ' تومان به کیف پول نماینده واریز شد.');
        } catch (Exception $e) {
            setMessage('خطا: ' . $e->getMessage(), 'error');
        }
    } else {
        setMessage('مبلغ و نماینده معتبر وارد کنید', 'error');
    }
    redirect('representatives.php');
}

// بررسی وجود فیلد last_activity
$has_last_activity = false;
try {
    $check = $pdo->query("SHOW COLUMNS FROM representatives LIKE 'last_activity'");
    $has_last_activity = $check->rowCount() > 0;
} catch (Exception $e) {
    $has_last_activity = false;
}

// بررسی وجود فیلد rank
$has_rank = false;
try {
    $check = $pdo->query("SHOW COLUMNS FROM representatives LIKE 'rank'");
    $has_rank = $check->rowCount() > 0;
} catch (Exception $e) {
    $has_rank = false;
}

// دریافت لیست نمایندگان با آمار
try {
    // ساخت query با توجه به وجود فیلد last_activity
    if ($has_last_activity) {
        $query = "
            SELECT r.*, 
                   p.name as panel_name,
                   (SELECT COUNT(*) FROM reseller_users WHERE representative_id = r.id) as total_users,
                   COALESCE((SELECT SUM(total_traffic) FROM reseller_users WHERE representative_id = r.id), 0) as total_user_traffic,
                   CASE 
                       WHEN r.last_activity IS NULL THEN 'offline'
                       WHEN TIMESTAMPDIFF(MINUTE, r.last_activity, NOW()) <= 5 THEN 'online'
                       ELSE 'offline'
                   END as online_status,
                   CASE 
                       WHEN r.expiry_date IS NULL THEN NULL
                       WHEN r.expiry_date < NOW() THEN TIMESTAMPDIFF(DAY, r.expiry_date, NOW())
                       ELSE TIMESTAMPDIFF(DAY, NOW(), r.expiry_date)
                   END as days_until_expiry
            FROM representatives r 
            JOIN panels p ON r.panel_id = p.id 
            ORDER BY " . ($has_rank ? "(r.rank IS NULL), r.rank ASC, " : "") . "r.created_at DESC
        ";
    } else {
        // اگر فیلد last_activity وجود ندارد، همه را offline نشان بده
        $query = "
            SELECT r.*, 
                   p.name as panel_name,
                   (SELECT COUNT(*) FROM reseller_users WHERE representative_id = r.id) as total_users,
                   COALESCE((SELECT SUM(total_traffic) FROM reseller_users WHERE representative_id = r.id), 0) as total_user_traffic,
                   'offline' as online_status,
                   CASE 
                       WHEN r.expiry_date IS NULL THEN NULL
                       WHEN r.expiry_date < NOW() THEN TIMESTAMPDIFF(DAY, r.expiry_date, NOW())
                       ELSE TIMESTAMPDIFF(DAY, NOW(), r.expiry_date)
                   END as days_until_expiry
            FROM representatives r 
            JOIN panels p ON r.panel_id = p.id 
            ORDER BY " . ($has_rank ? "(r.rank IS NULL), r.rank ASC, " : "") . "r.created_at DESC
        ";
    }
    
    $representatives = $pdo->query($query)->fetchAll();
} catch (Exception $e) {
    setMessage('خطا در دریافت لیست نمایندگان: ' . $e->getMessage(), 'error');
    $representatives = [];
}

// دریافت لیست پنل‌ها برای dropdown
$panels = $pdo->query("SELECT * FROM panels WHERE status = 'active' ORDER BY name")->fetchAll();

// تابع دریافت inbound های یک پنل
function getPanelInbounds($pdo, $panel_id) {
    try {
        $stmt = $pdo->prepare("SELECT * FROM panels WHERE id = ?");
        $stmt->execute([$panel_id]);
        $panel = $stmt->fetch();
        
        if (!$panel) return [];
        
        require_once __DIR__ . '/../api/XrayAPI.php';
        
        // آماده‌سازی تنظیمات proxy (با بررسی وجود فیلدها)
        $proxy_config = null;
        if (isset($panel['proxy_host']) && !empty($panel['proxy_host'])) {
            $proxy_config = [
                'type' => isset($panel['proxy_type']) ? $panel['proxy_type'] : 'socks5',
                'host' => $panel['proxy_host'],
                'port' => isset($panel['proxy_port']) ? (int)$panel['proxy_port'] : 1080,
                'username' => isset($panel['proxy_username']) ? $panel['proxy_username'] : null,
                'password' => isset($panel['proxy_password']) ? $panel['proxy_password'] : null,
                'use_on_error' => isset($panel['use_proxy']) && !empty($panel['use_proxy'])
            ];
        }
        
        $xrayAPI = new XrayAPI($panel['url'], $panel['username'], $panel['password'], $proxy_config);
        $inbounds_result = $xrayAPI->getInbounds();
        return $inbounds_result['obj'] ?? [];
    } catch (Exception $e) {
        error_log("خطا در getPanelInbounds: " . $e->getMessage());
        return [];
    }
}

// تابع دریافت inbound های مجاز یک نماینده
function getRepresentativeInbounds($pdo, $rep_id) {
    $stmt = $pdo->prepare("SELECT inbound_id FROM representative_inbounds WHERE representative_id = ?");
    $stmt->execute([$rep_id]);
    return array_column($stmt->fetchAll(), 'inbound_id');
}

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

<div class="card">
    <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="mb-0">مدیریت نمایندگان</h5>
        <button type="button" class="btn btn-light btn-sm" data-bs-toggle="modal" data-bs-target="#addRepModal">
            <i class="bi bi-person-plus"></i> افزودن نماینده جدید
        </button>
    </div>
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-hover align-middle">
                <thead class="table-light">
                    <tr>
                        <th style="width: 120px;">عملیات</th>
                        <?php if ($has_rank): ?><th style="width: 70px;">رتبه</th><?php endif; ?>
                        <th style="width: 100px;">وضعیت</th>
                        <th>نام کاربری</th>
                        <th style="width: 150px;">حجم استفاده شده</th>
                        <th style="width: 250px;">حد ترافیک</th>
                        <th style="width: 150px;">حجم فعلی</th>
                        <th style="width: 150px;">تاریخ انقضا</th>
                        <th style="width: 130px;">کیف پول</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($representatives)): ?>
                        <tr>
                            <td colspan="<?= 8 + ($has_rank ? 1 : 0) ?>" class="text-center text-muted py-4">
                                <i class="bi bi-inbox"></i> هیچ نماینده‌ای یافت نشد
                            </td>
                        </tr>
                    <?php else: ?>
                        <?php foreach ($representatives as $rep): 
                            try {
                                $used_traffic = isset($rep['total_user_traffic']) ? (float)$rep['total_user_traffic'] : 0;
                                $traffic_limit = isset($rep['traffic_limit']) ? (float)$rep['traffic_limit'] : 0;
                                $is_expired = !empty($rep['expiry_date']) && strtotime($rep['expiry_date']) < time();
                                $is_traffic_limited = $traffic_limit > 0 && $used_traffic >= $traffic_limit;
                                $traffic_percent = $traffic_limit > 0 ? ($used_traffic / $traffic_limit) * 100 : 0;
                                $traffic_percent = min(max($traffic_percent, 0), 100);
                                $is_online = isset($rep['online_status']) && $rep['online_status'] === 'online';
                            } catch (Exception $e) {
                                $used_traffic = 0;
                                $traffic_limit = 0;
                                $is_expired = false;
                                $is_traffic_limited = false;
                                $traffic_percent = 0;
                                $is_online = false;
                            }
                        ?>
                        <tr>
                            <td>
                                <div class="btn-group btn-group-sm" role="group">
                                    <a href="representative_monitor.php?id=<?= $rep['id'] ?>" 
                                       class="btn btn-outline-primary" title="داشبورد">
                                        <i class="bi bi-speedometer2"></i>
                                    </a>
                                    <button type="button" class="btn btn-outline-info" 
                                            onclick="editRepresentative(<?= htmlspecialchars(json_encode($rep, JSON_UNESCAPED_UNICODE | JSON_HEX_QUOT | JSON_HEX_APOS | JSON_PARTIAL_OUTPUT_ON_ERROR)) ?>, <?= isset($rep['panel_id']) ? (int)$rep['panel_id'] : 0 ?>)"
                                            title="ویرایش">
                                        <i class="bi bi-pencil"></i>
                                    </button>
                                    <button type="button" class="btn btn-outline-secondary" 
                                            onclick="showRepInfo(<?= htmlspecialchars(json_encode($rep, JSON_UNESCAPED_UNICODE | JSON_HEX_QUOT | JSON_HEX_APOS | JSON_PARTIAL_OUTPUT_ON_ERROR)) ?>)"
                                            title="اطلاعات">
                                        <i class="bi bi-info-circle"></i>
                                    </button>
                                    <a href="?refresh=<?= $rep['id'] ?>" class="btn btn-outline-success" 
                                       title="به‌روزرسانی">
                                        <i class="bi bi-arrow-clockwise"></i>
                                    </a>
                                    <a href="?delete=<?= $rep['id'] ?>" class="btn btn-outline-danger" 
                                       onclick="return confirm('آیا مطمئن هستید؟')"
                                       title="حذف">
                                        <i class="bi bi-trash"></i>
                                    </a>
                                </div>
                            </td>
                            <?php if ($has_rank): ?>
                            <td>
                                <?php if (!empty($rep['rank'])): ?>
                                    <span class="badge bg-primary"><?= (int)$rep['rank'] ?></span>
                                <?php else: ?>
                                    <span class="text-muted">—</span>
                                <?php endif; ?>
                            </td>
                            <?php endif; ?>
                            <td>
                                <div class="form-check form-switch">
                                    <input class="form-check-input" type="checkbox" 
                                           <?= $rep['status'] === 'active' ? 'checked' : '' ?>
                                           onchange="toggleStatus(<?= $rep['id'] ?>, this.checked)">
                                </div>
                                <div class="mt-1">
                                    <?php if ($is_online): ?>
                                        <span class="badge bg-success">آنلاین</span>
                                    <?php else: ?>
                                        <span class="badge bg-secondary">آفلاین</span>
                                    <?php endif; ?>
                                </div>
                            </td>
                            <td>
                                <div class="d-flex align-items-center">
                                    <span class="badge bg-<?= $is_online ? 'success' : 'secondary' ?> rounded-pill me-2" 
                                          style="width: 8px; height: 8px;"></span>
                                    <div>
                                        <strong><?= htmlspecialchars($rep['username']) ?></strong>
                                        <?php if ($rep['full_name']): ?>
                                            <br><small class="text-muted"><?= htmlspecialchars($rep['full_name']) ?></small>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </td>
                            <td><strong><?= number_format($used_traffic / (1024 * 1024 * 1024), 2) ?> GB</strong></td>
                            <td>
                                <?php if ($traffic_limit > 0): ?>
                                    <div class="progress" style="height: 25px;">
                                        <div class="progress-bar <?= $traffic_percent >= 100 ? 'bg-danger' : ($traffic_percent >= 80 ? 'bg-warning' : 'bg-success') ?>" 
                                             role="progressbar" 
                                             style="width: <?= $traffic_percent ?>%"
                                             aria-valuenow="<?= $traffic_percent ?>" 
                                             aria-valuemin="0" 
                                             aria-valuemax="100">
                                            <?= number_format($traffic_percent, 1) ?>%
                                        </div>
                                    </div>
                                    <small class="text-muted"><?= number_format($traffic_limit / (1024 * 1024 * 1024), 0) ?>GB</small>
                                <?php else: ?>
                                    <span class="text-muted">نامحدود</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <strong><?= number_format($used_traffic / (1024 * 1024 * 1024), 2) ?> GB</strong>
                            </td>
                            <td>
                                <?php if ($rep['expiry_date']): ?>
                                    <?php if ($rep['days_until_expiry'] < 0): ?>
                                        <span class="badge bg-danger">
                                            <?= abs($rep['days_until_expiry']) ?> روز پیش
                                        </span>
                                    <?php elseif ($rep['days_until_expiry'] == 0): ?>
                                        <span class="badge bg-warning">امروز</span>
                                    <?php else: ?>
                                        <span class="badge bg-info">
                                            <?= $rep['days_until_expiry'] ?> روز دیگر
                                        </span>
                                    <?php endif; ?>
                                <?php else: ?>
                                    <span class="text-muted">∞</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <?php $rep_balance = walletBalance($pdo, $rep['id']); ?>
                                <strong><?= number_format($rep_balance) ?></strong>
                                <button type="button" class="btn btn-sm btn-outline-success ms-1" 
                                        data-bs-toggle="modal" data-bs-target="#walletDepositModal"
                                        data-rep-id="<?= (int)$rep['id'] ?>"
                                        data-rep-name="<?= htmlspecialchars($rep['username']) ?>"
                                        onclick="setWalletDepositRep(<?= (int)$rep['id'] ?>, '<?= htmlspecialchars(addslashes($rep['username'])) ?>')"
                                        title="افزایش موجودی">
                                    <i class="bi bi-plus-lg"></i>
                                </button>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Modal افزودن نماینده -->
<div class="modal fade" id="addRepModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">افزودن نماینده جدید</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <div class="modal-body">
                    <input type="hidden" name="action" value="add">
                    <div class="mb-3">
                        <label class="form-label">نام کاربری <span class="text-danger">*</span></label>
                        <input type="text" name="username" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">رمز عبور <span class="text-danger">*</span></label>
                        <input type="password" name="password" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">پنل <span class="text-danger">*</span></label>
                        <select name="panel_id" id="add_panel_id" class="form-select" required onchange="loadInbounds(this.value, 'add')">
                            <option value="">انتخاب کنید</option>
                            <?php foreach ($panels as $panel): ?>
                                <option value="<?= $panel['id'] ?>"><?= htmlspecialchars($panel['name']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Inbound های مجاز <span class="text-danger">*</span></label>
                        <div id="add_inbounds_list" class="border p-3 rounded" style="max-height: 200px; overflow-y: auto;">
                            <small class="text-muted">ابتدا پنل را انتخاب کنید</small>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">حد ترافیک کل (GB) - 0 برای نامحدود</label>
                        <input type="number" name="traffic_limit" class="form-control" min="0" value="0">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">تعداد روز اعتبار - 0 برای نامحدود</label>
                        <input type="number" name="expiry_days" class="form-control" min="0" value="0">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">ریمارک پیش‌فرض در ساخت کاربر</label>
                        <input type="text" name="default_remark" class="form-control" placeholder="در ساخت کاربر اگر خالی بگذارند این قرار می‌گیرد">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">قیمت هر گیگ (تومان) — 0 = حساب نشود</label>
                        <input type="number" name="price_per_gb" class="form-control" min="0" step="0.01" value="0">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">قیمت هر روز اعتبار (تومان) — 0 = حساب نشود</label>
                        <input type="number" name="price_per_day" class="form-control" min="0" step="0.01" value="0">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">تخفیف (درصد) — 0 تا 100، 0 = استفاده از تخفیف سراسری</label>
                        <input type="number" name="discount_percent" class="form-control" min="0" max="100" value="0">
                    </div>
                    <?php if ($has_rank): ?>
                    <div class="mb-3">
                        <label class="form-label">رتبه (۱=بالاترین — خالی=بدون رتبه)</label>
                        <input type="number" name="rank" class="form-control" min="1" placeholder="خالی بگذارید">
                    </div>
                    <?php endif; ?>
                    <div class="mb-3">
                        <label class="form-label">نام کامل</label>
                        <input type="text" name="full_name" class="form-control">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">ایمیل</label>
                        <input type="email" name="email" class="form-control">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">تلفن</label>
                        <input type="text" name="phone" class="form-control">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">انصراف</button>
                    <button type="submit" class="btn btn-primary">افزودن</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Modal ویرایش نماینده -->
<div class="modal fade" id="editRepModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">ویرایش نماینده</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <div class="modal-body">
                    <input type="hidden" name="action" value="update">
                    <input type="hidden" name="id" id="edit_rep_id">
                    <div class="mb-3">
                        <label class="form-label">حد ترافیک کل (GB) - 0 برای نامحدود</label>
                        <input type="number" name="traffic_limit" id="edit_traffic_limit" class="form-control" min="0">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">تعداد روز اعتبار - 0 برای نامحدود</label>
                        <input type="number" name="expiry_days" id="edit_expiry_days" class="form-control" min="0">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">ریمارک پیش‌فرض در ساخت کاربر</label>
                        <input type="text" name="default_remark" id="edit_default_remark" class="form-control">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">قیمت هر گیگ (تومان) — 0 = حساب نشود</label>
                        <input type="number" name="price_per_gb" id="edit_price_per_gb" class="form-control" min="0" step="0.01">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">قیمت هر روز اعتبار (تومان) — 0 = حساب نشود</label>
                        <input type="number" name="price_per_day" id="edit_price_per_day" class="form-control" min="0" step="0.01">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">تخفیف (درصد) — 0 تا 100</label>
                        <input type="number" name="discount_percent" id="edit_discount_percent" class="form-control" min="0" max="100" value="0">
                    </div>
                    <?php if ($has_rank): ?>
                    <div class="mb-3">
                        <label class="form-label">رتبه (۱=بالاترین — خالی=بدون رتبه)</label>
                        <input type="number" name="rank" id="edit_rank" class="form-control" min="1" placeholder="خالی بگذارید">
                    </div>
                    <?php endif; ?>
                    <div class="mb-3">
                        <label class="form-label">اینباندهای مجاز (پنل اصلی)</label>
                        <div id="edit_inbounds_list" class="border p-3 rounded mb-2" style="max-height: 180px; overflow-y: auto;">
                            <small class="text-muted">در حال بارگذاری...</small>
                        </div>
                        <div class="mb-2">
                            <label class="form-label small text-muted">اینباند از سرورهای دیگر</label>
                            <div class="d-flex gap-2 flex-wrap align-items-center">
                                <select id="edit_extra_panel_id" class="form-select form-select-sm" style="width: auto;">
                                    <option value="">انتخاب پنل...</option>
                                    <?php foreach ($panels as $p): ?>
                                        <option value="<?= (int)$p['id'] ?>"><?= htmlspecialchars($p['name']) ?></option>
                                    <?php endforeach; ?>
                                </select>
                                <button type="button" class="btn btn-sm btn-outline-secondary" onclick="loadExtraPanelInbounds()">
                                    <i class="bi bi-plus-lg"></i> افزودن اینباند از این سرور
                                </button>
                            </div>
                        </div>
                        <div id="edit_inbounds_extra" class="border p-3 rounded" style="max-height: 200px; overflow-y: auto;"></div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">انصراف</button>
                    <button type="submit" class="btn btn-primary">ذخیره</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Modal واریز به کیف پول -->
<div class="modal fade" id="walletDepositModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">افزایش موجودی کیف پول</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <input type="hidden" name="action" value="wallet_deposit">
                <input type="hidden" name="rep_id" id="wallet_rep_id">
                <div class="modal-body">
                    <p class="mb-2">نماینده: <strong id="wallet_rep_name">-</strong></p>
                    <div class="mb-3">
                        <label class="form-label">مبلغ واریز <span class="text-danger">*</span></label>
                        <input type="number" name="amount" class="form-control" min="0.01" step="0.01" required placeholder="مثال: 50000">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">توضیح (اختیاری)</label>
                        <input type="text" name="description" class="form-control" placeholder="واریز توسط ادمین">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">انصراف</button>
                    <button type="submit" class="btn btn-success">واریز</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
var defaultInboundUserLimit = <?= json_encode(defaultInboundUserLimit($pdo)) ?>;
var panelsList = <?= json_encode(array_column($panels, 'name', 'id')) ?>;
function setWalletDepositRep(repId, repName) {
    document.getElementById('wallet_rep_id').value = repId;
    document.getElementById('wallet_rep_name').textContent = repName || ('نماینده #' + repId);
}

function toggleStatus(repId, isActive) {
    fetch('?toggle=' + repId)
        .then(() => {
            location.reload();
        });
}

function showRepInfo(rep) {
    try {
        const totalTraffic = rep.total_user_traffic ? (parseFloat(rep.total_user_traffic) / (1024*1024*1024)).toFixed(2) : '0.00';
        const trafficLimit = rep.traffic_limit && parseFloat(rep.traffic_limit) > 0 
            ? (parseFloat(rep.traffic_limit) / (1024*1024*1024)).toFixed(2) + ' GB' 
            : 'نامحدود';
        
        const info = `
            <div class="row">
                <div class="col-md-6">
                    <p><strong>نام کاربری:</strong> ${rep.username || '-'}</p>
                    <p><strong>نام کامل:</strong> ${rep.full_name || '-'}</p>
                    <p><strong>ایمیل:</strong> ${rep.email || '-'}</p>
                    <p><strong>تلفن:</strong> ${rep.phone || '-'}</p>
                </div>
                <div class="col-md-6">
                    <p><strong>پنل:</strong> ${rep.panel_name || '-'}</p>
                    <p><strong>کاربران:</strong> ${rep.total_users || 0}</p>
                    <p><strong>ترافیک مصرفی:</strong> ${totalTraffic} GB</p>
                    <p><strong>حد ترافیک:</strong> ${trafficLimit}</p>
                </div>
            </div>
        `;
        alert(info);
    } catch (e) {
        console.error('خطا در نمایش اطلاعات:', e);
        alert('خطا در نمایش اطلاعات نماینده');
    }
}

function loadInbounds(panelId, mode) {
    if (!panelId) {
        var target = (mode === 'edit') ? 'edit_inbounds_list' : 'add_inbounds_list';
        document.getElementById(target).innerHTML = '<small class="text-muted">ابتدا پنل را انتخاب کنید</small>';
        return;
    }
    var target = (mode === 'edit') ? 'edit_inbounds_list' : 'add_inbounds_list';
    document.getElementById(target).innerHTML = '<small class="text-muted">در حال بارگذاری...</small>';
    var useRiNames = (mode === 'edit');
    
    fetch('get_panel_inbounds.php?panel_id=' + panelId)
        .then(response => response.json())
        .then(data => {
            if (data.success && data.inbounds) {
                var html = useRiNames ? ('<small class="text-muted d-block mb-2">حد کاربر: ۰ = نامحدود</small>') : ('<small class="text-muted d-block mb-2">حد کاربر: ۰ = نامحدود</small>');
                data.inbounds.forEach(function(inbound) {
                    if (useRiNames) {
                        html += '<div class="d-flex align-items-center mb-2 flex-wrap"><div class="form-check me-2">' +
                            '<input class="form-check-input" type="checkbox" name="ri_check[' + panelId + '][' + inbound.id + ']" value="1" id="inbound_edit_' + panelId + '_' + inbound.id + '">' +
                            '<label class="form-check-label" for="inbound_edit_' + panelId + '_' + inbound.id + '">' + (inbound.remark || 'Inbound #' + inbound.id) + ' (' + (inbound.protocol || '') + ') - ' + (inbound.port || '') + '</label></div>' +
                            '<input type="number" name="ri_limit[' + panelId + '][' + inbound.id + ']" id="inbound_limit_edit_' + panelId + '_' + inbound.id + '" min="0" value="' + (defaultInboundUserLimit || 0) + '" class="form-control form-control-sm" style="width:90px" placeholder="حد"></div>';
                    } else {
                        html += '<div class="d-flex align-items-center mb-2 flex-wrap"><div class="form-check me-2">' +
                            '<input class="form-check-input" type="checkbox" name="inbound_ids[]" value="' + inbound.id + '" id="inbound_add_' + inbound.id + '">' +
                            '<label class="form-check-label" for="inbound_add_' + inbound.id + '">' + (inbound.remark || 'Inbound #' + inbound.id) + ' (' + (inbound.protocol || '') + ') - ' + (inbound.port || '') + '</label></div>' +
                            '<input type="number" name="inbound_limit[' + inbound.id + ']" id="inbound_limit_add_' + inbound.id + '" min="0" value="' + (defaultInboundUserLimit || 0) + '" class="form-control form-control-sm" style="width:90px" placeholder="حد"></div>';
                    }
                });
                document.getElementById(target).innerHTML = html || '<small class="text-muted">Inbound یافت نشد</small>';
            } else {
                document.getElementById(target).innerHTML = '<small class="text-danger">خطا در بارگذاری: ' + (data.message || 'نامشخص') + '</small>';
            }
        })
        .catch(function() {
            document.getElementById(target).innerHTML = '<small class="text-danger">خطا در بارگذاری</small>';
        });
}

function loadExtraPanelInbounds() {
    var sel = document.getElementById('edit_extra_panel_id');
    var panelId = parseInt(sel.value, 10);
    if (!panelId) return;
    if (document.getElementById('edit_inbounds_panel_' + panelId)) {
        sel.value = ''; return;
    }
    var panelName = sel.options[sel.selectedIndex].text;
    var wrap = document.createElement('div');
    wrap.id = 'edit_inbounds_panel_' + panelId;
    wrap.className = 'mb-3';
    wrap.innerHTML = '<h6 class="small text-muted mb-2">' + (panelName || ('پنل #' + panelId)) + '</h6><div class="inbounds_container"></div>';
    document.getElementById('edit_inbounds_extra').appendChild(wrap);
    var container = wrap.querySelector('.inbounds_container');
    container.innerHTML = '<small class="text-muted">در حال بارگذاری...</small>';
    fetch('get_panel_inbounds.php?panel_id=' + panelId)
        .then(function(r) { return r.json(); })
        .then(function(data) {
            if (data.success && data.inbounds && data.inbounds.length) {
                var html = '';
                data.inbounds.forEach(function(inbound) {
                    html += '<div class="d-flex align-items-center mb-2 flex-wrap"><div class="form-check me-2">' +
                        '<input class="form-check-input" type="checkbox" name="ri_check[' + panelId + '][' + inbound.id + ']" value="1" id="inbound_edit_' + panelId + '_' + inbound.id + '">' +
                        '<label class="form-check-label" for="inbound_edit_' + panelId + '_' + inbound.id + '">' + (inbound.remark || 'Inbound #' + inbound.id) + ' (' + (inbound.protocol || '') + ') - ' + (inbound.port || '') + '</label></div>' +
                        '<input type="number" name="ri_limit[' + panelId + '][' + inbound.id + ']" id="inbound_limit_edit_' + panelId + '_' + inbound.id + '" min="0" value="' + (defaultInboundUserLimit || 0) + '" class="form-control form-control-sm" style="width:90px" placeholder="حد"></div>';
                });
                container.innerHTML = html;
            } else {
                container.innerHTML = '<small class="text-muted">اینباندی یافت نشد</small>';
            }
            sel.value = '';
        })
        .catch(function() {
            container.innerHTML = '<small class="text-danger">خطا در بارگذاری</small>';
            sel.value = '';
        });
}

function loadExtraPanelInboundsByIdThenCheck(panelId, assignmentsArray) {
    if (document.getElementById('edit_inbounds_panel_' + panelId)) {
        assignmentsArray.forEach(function(a) {
            var cb = document.getElementById('inbound_edit_' + panelId + '_' + a.inbound_id);
            if (cb) cb.checked = true;
            var el = document.getElementById('inbound_limit_edit_' + panelId + '_' + a.inbound_id);
            if (el) el.value = a.user_limit || 0;
        });
        return;
    }
    var panelName = panelsList[panelId] || ('پنل #' + panelId);
    var wrap = document.createElement('div');
    wrap.id = 'edit_inbounds_panel_' + panelId;
    wrap.className = 'mb-3';
    wrap.innerHTML = '<h6 class="small text-muted mb-2">' + panelName + '</h6><div class="inbounds_container"></div>';
    document.getElementById('edit_inbounds_extra').appendChild(wrap);
    var container = wrap.querySelector('.inbounds_container');
    container.innerHTML = '<small class="text-muted">در حال بارگذاری...</small>';
    fetch('get_panel_inbounds.php?panel_id=' + panelId)
        .then(function(r) { return r.json(); })
        .then(function(data) {
            if (data.success && data.inbounds && data.inbounds.length) {
                var html = '';
                data.inbounds.forEach(function(inbound) {
                    html += '<div class="d-flex align-items-center mb-2 flex-wrap"><div class="form-check me-2">' +
                        '<input class="form-check-input" type="checkbox" name="ri_check[' + panelId + '][' + inbound.id + ']" value="1" id="inbound_edit_' + panelId + '_' + inbound.id + '">' +
                        '<label class="form-check-label" for="inbound_edit_' + panelId + '_' + inbound.id + '">' + (inbound.remark || 'Inbound #' + inbound.id) + ' (' + (inbound.protocol || '') + ') - ' + (inbound.port || '') + '</label></div>' +
                        '<input type="number" name="ri_limit[' + panelId + '][' + inbound.id + ']" id="inbound_limit_edit_' + panelId + '_' + inbound.id + '" min="0" value="' + (defaultInboundUserLimit || 0) + '" class="form-control form-control-sm" style="width:90px" placeholder="حد"></div>';
                });
                container.innerHTML = html;
                assignmentsArray.forEach(function(a) {
                    var cb = document.getElementById('inbound_edit_' + panelId + '_' + a.inbound_id);
                    if (cb) { cb.checked = true; }
                    var el = document.getElementById('inbound_limit_edit_' + panelId + '_' + a.inbound_id);
                    if (el) el.value = a.user_limit || 0;
                });
            } else {
                container.innerHTML = '<small class="text-muted">اینباندی یافت نشد</small>';
            }
        })
        .catch(function() {
            container.innerHTML = '<small class="text-danger">خطا در بارگذاری</small>';
        });
}

function editRepresentative(rep, panelId) {
    try {
        if (!rep || !rep.id) {
            alert('خطا: اطلاعات نماینده نامعتبر است');
            return;
        }
        
        document.getElementById('edit_rep_id').value = rep.id || '';
        const trafficLimitGB = rep.traffic_limit && parseFloat(rep.traffic_limit) > 0 
            ? Math.round(parseFloat(rep.traffic_limit) / (1024 * 1024 * 1024)) 
            : 0;
        document.getElementById('edit_traffic_limit').value = trafficLimitGB;
        
        if (rep.expiry_date) {
            try {
                const expiryDate = new Date(rep.expiry_date);
                const now = new Date();
                const diffTime = expiryDate - now;
                const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
                document.getElementById('edit_expiry_days').value = diffDays > 0 ? diffDays : 0;
            } catch (e) {
                document.getElementById('edit_expiry_days').value = 0;
            }
        } else {
            document.getElementById('edit_expiry_days').value = 0;
        }
        
        document.getElementById('edit_default_remark').value = rep.default_remark || '';
        var editRank = document.getElementById('edit_rank');
        if (editRank) editRank.value = (rep.rank != null && rep.rank !== '') ? rep.rank : '';
        document.getElementById('edit_price_per_gb').value = rep.price_per_gb != null ? rep.price_per_gb : 0;
        document.getElementById('edit_price_per_day').value = rep.price_per_day != null ? rep.price_per_day : 0;
        document.getElementById('edit_discount_percent').value = rep.discount_percent != null ? rep.discount_percent : 0;
        
        // بارگذاری inbound های پنل اصلی
        loadInbounds(panelId, 'edit');
        
        // انتخاب inbound های موجود (و بارگذاری پنل‌های دیگر در صورت وجود)
        setTimeout(function() {
            fetch('get_representative_inbounds.php?rep_id=' + rep.id)
                .then(function(response) {
                    if (!response.ok) throw new Error('خطا در دریافت پاسخ');
                    return response.json();
                })
                .then(function(data) {
                    if (!data.success) return;
                    var assignments = data.assignments || [];
                    if (assignments.length === 0 && data.inbound_ids && Array.isArray(data.inbound_ids)) {
                        data.inbound_ids.forEach(function(inboundId) {
                            var cb = document.getElementById('inbound_edit_' + panelId + '_' + inboundId);
                            if (cb) cb.checked = true;
                            var el = document.getElementById('inbound_limit_edit_' + panelId + '_' + inboundId);
                            if (el && data.limits && data.limits[inboundId] !== undefined) el.value = data.limits[inboundId];
                        });
                        return;
                    }
                    var byPanel = {};
                    assignments.forEach(function(a) {
                        if (!byPanel[a.panel_id]) byPanel[a.panel_id] = [];
                        byPanel[a.panel_id].push(a);
                    });
                    Object.keys(byPanel).forEach(function(pid) {
                        var list = byPanel[pid];
                        if (parseInt(pid, 10) === panelId) {
                            list.forEach(function(a) {
                                var cb = document.getElementById('inbound_edit_' + pid + '_' + a.inbound_id);
                                if (cb) cb.checked = true;
                                var el = document.getElementById('inbound_limit_edit_' + pid + '_' + a.inbound_id);
                                if (el) el.value = a.user_limit || 0;
                            });
                        } else {
                            loadExtraPanelInboundsByIdThenCheck(parseInt(pid, 10), list);
                        }
                    });
                })
                .catch(function(err) {
                    console.error('خطا در دریافت inbound های نماینده:', err);
                });
        }, 600);
        
        const modalElement = document.getElementById('editRepModal');
        if (modalElement && typeof bootstrap !== 'undefined') {
            new bootstrap.Modal(modalElement).show();
        } else {
            alert('خطا: Modal یافت نشد');
        }
    } catch (e) {
        console.error('خطا در editRepresentative:', e);
        alert('خطا در باز کردن فرم ویرایش');
    }
}
</script>

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