<?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'] === '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');
}

// صفحه‌بندی و ترتیب نمایش نمایندگان
$page = max(1, (int)($_GET['page'] ?? 1));
$per_page = 50;
$offset = ($page - 1) * $per_page;

try {
    $has_rank_col = $pdo->query("SHOW COLUMNS FROM representatives LIKE 'rank'")->rowCount() > 0;
} catch (Exception $e) {
    $has_rank_col = false;
}
$order_sql = $has_rank_col ? "ORDER BY rank ASC, id DESC" : "ORDER BY id DESC";

// تعداد کل نمایندگان برای صفحه‌بندی
try {
    $total_reps = (int)$pdo->query("SELECT COUNT(*) FROM representatives")->fetchColumn();
} catch (Exception $e) {
    $total_reps = 0;
}
$total_pages = $per_page > 0 ? (int)ceil($total_reps / $per_page) : 1;

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

<div class="card admin-main-card">
    <div class="card-header d-flex justify-content-between align-items-center">
        <h3 class="card-title mb-0"><?= htmlspecialchars($page_title) ?></h3>
        <a href="representative_add.php" class="btn btn-primary btn-sm">
            <i class="bi bi-person-plus"></i> افزودن نماینده جدید
        </a>
    </div>
    <div class="card-body">
         <div class="table-responsive">
            <table class="table table-striped table-hover align-middle">
                <thead>
                    <tr>
                        <th>عملیات</th>
                        <th>رتبه</th>
                        <th>وضعیت</th>
                        <th>نام کاربری</th>
                        <th>حجم مصرفی</th>
                        <th>حجم کل</th>
                        <th>تاریخ انقضا</th>
                        <th>کیف پول</th>
                    </tr>
                </thead>
                <tbody>
                    <?php 
                    // واکشی نمایندگان با صفحه‌بندی
                    $stmt_reps = $pdo->prepare("SELECT * FROM representatives {$order_sql} LIMIT :limit OFFSET :offset");
                    $stmt_reps->bindValue(':limit', $per_page, PDO::PARAM_INT);
                    $stmt_reps->bindValue(':offset', $offset, PDO::PARAM_INT);
                    $stmt_reps->execute();
                    $representatives = $stmt_reps->fetchAll();
                    if (empty($representatives)): 
                    ?>
                        <tr>
                            <td colspan="8" class="text-center text-muted py-4">
                                <i class="bi bi-inbox"></i> هیچ نماینده‌ای یافت نشد
                            </td>
                        </tr>
                    <?php else: ?>
                        <?php foreach ($representatives as $rep): ?>
                        <tr>
                            <td>
                                <div class="btn-group btn-group-sm" role="group">
                                    <a href="representative_monitor.php?id=<?= $rep['id'] ?>" class="btn btn-soft-primary" title="داشبورد">
                                        <i class="bi bi-speedometer2"></i>
                                    </a>
                                    <a href="representative_edit.php?id=<?= $rep['id'] ?>" class="btn btn-soft-info" title="ویرایش">
                                        <i class="bi bi-pencil"></i>
                                    </a>
                                    <a href="?delete=<?= $rep['id'] ?>" class="btn btn-soft-danger" 
                                       onclick="return confirm('آیا مطمئن هستید؟')"
                                       title="حذف">
                                        <i class="bi bi-trash"></i>
                                    </a>
                                </div>
                            </td>
                            <td><span class="badge bg-secondary"><?= $rep['rank'] ?? 'N/A' ?></span></td>
                            <td>
                                <a href="?toggle=<?= $rep['id'] ?>">
                                    <span class="badge bg-<?= $rep['status'] === 'active' ? 'success' : 'danger' ?>">
                                        <?= $rep['status'] === 'active' ? 'فعال' : 'غیرفعال' ?>
                                    </span>
                                </a>
                            </td>
                            <td>
                                <a href="#" onclick="showRepInfo(<?= $rep['id'] ?>); return false;" class="text-decoration-none">
                                    <?= htmlspecialchars($rep['username']) ?>
                                </a>
                            </td>
                            <td><span class="badge bg-warning"><?= formatBytes($rep['total_usage'] ?? 0) ?></span></td>
                            <td><span class="badge bg-primary"><?= formatBytes($rep['traffic_limit'] ?? 0) ?></span></td>
                            <td><?= $rep['expiry_date'] ? jdate('Y-m-d', strtotime($rep['expiry_date'])) : 'نامحدود' ?></td>
                            <td>
                                <span class="badge bg-dark" style="cursor:pointer;" onclick="showDepositModal(<?= $rep['id'] ?>, '<?= htmlspecialchars($rep['username']) ?>')">
                                    <?= number_format($rep['wallet_balance'] ?? 0) ?> تومان
                                </span>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<?php if ($total_pages > 1): ?>
    <nav aria-label="نمایش صفحات" class="mt-3">
        <ul class="pagination justify-content-center">
            <?php
            $base_url = strtok($_SERVER['REQUEST_URI'], '?');
            $buildUrl = function($p) use ($base_url) {
                return htmlspecialchars($base_url . '?page=' . max(1, (int)$p));
            };
            ?>
            <li class="page-item <?= $page <= 1 ? 'disabled' : '' ?>">
                <a class="page-link" href="<?= $buildUrl($page - 1) ?>">قبلی</a>
            </li>
            <?php for ($p = 1; $p <= $total_pages; $p++): ?>
                <li class="page-item <?= $p === $page ? 'active' : '' ?>">
                    <a class="page-link" href="<?= $buildUrl($p) ?>"><?= $p ?></a>
                </li>
            <?php endfor; ?>
            <li class="page-item <?= $page >= $total_pages ? 'disabled' : '' ?>">
                <a class="page-link" href="<?= $buildUrl($page + 1) ?>">بعدی</a>
            </li>
        </ul>
    </nav>
<?php endif; ?>


<!-- Info Modal -->
<div class="modal fade" id="infoModal" tabindex="-1" aria-labelledby="infoModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="infoModalLabel">اطلاعات نماینده</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body" id="infoModalBody">
                <!-- Info will be loaded here -->
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">بستن</button>
            </div>
        </div>
    </div>
</div>


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