<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
require_once '../config.php';

header('Content-Type: application/json');

if (!isLoggedIn() || !isAdmin()) {
    echo json_encode(['success' => false, 'message' => 'دسترسی غیرمجاز']);
    exit;
}

$id = (int)($_GET['id'] ?? 0);
if ($id <= 0) {
    echo json_encode(['success' => false, 'message' => 'شناسه نامعتبر']);
    exit;
}

try {
    $stmt = $pdo->prepare("SELECT * FROM representatives WHERE id = ?");
    $stmt->execute([$id]);
    $rep = $stmt->fetch();

    if (!$rep) {
        echo json_encode(['success' => false, 'message' => 'نماینده یافت نشد']);
        exit;
    }

    // تعداد کاربران نماینده
    $stmt_count = $pdo->prepare("SELECT COUNT(*) FROM reseller_users WHERE representative_id = ?");
    $stmt_count->execute([$id]);
    $user_count = $stmt_count->fetchColumn();

    $rep['user_count'] = $user_count;
    $rep['total_usage_formatted'] = formatBytes($rep['total_usage'] ?? 0);

    echo json_encode(['success' => true, 'rep' => $rep]);

} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => 'خطای سرور: ' . $e->getMessage()]);
}
