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

require_once '../config.php';

if (!isAdmin()) {
    header('Content-Type: application/json');
    echo json_encode(['success' => false, 'message' => 'دسترسی غیرمجاز']);
    exit;
}

$rep_id = (int)($_GET['rep_id'] ?? 0);

if ($rep_id === 0) {
    header('Content-Type: application/json');
    echo json_encode(['success' => false, 'message' => 'نماینده انتخاب نشده']);
    exit;
}

try {
    try {
        $stmt = $pdo->prepare("SELECT panel_id, inbound_id, COALESCE(user_limit, 0) as user_limit FROM representative_inbounds WHERE representative_id = ?");
        $stmt->execute([$rep_id]);
        $rows = $stmt->fetchAll();
    } catch (Exception $e) {
        $stmt = $pdo->prepare("SELECT inbound_id FROM representative_inbounds WHERE representative_id = ?");
        $stmt->execute([$rep_id]);
        $rows = $stmt->fetchAll();
        foreach ($rows as &$r) { $r['panel_id'] = null; $r['user_limit'] = 0; }
        unset($r);
    }
    $inbound_ids = array_column($rows, 'inbound_id');
    $limits = [];
    $assignments = [];
    foreach ($rows as $r) {
        $limits[(string)$r['inbound_id']] = (int)($r['user_limit'] ?? 0);
        if (isset($r['panel_id']) && $r['panel_id'] !== null) {
            $assignments[] = ['panel_id' => (int)$r['panel_id'], 'inbound_id' => (int)$r['inbound_id'], 'user_limit' => (int)($r['user_limit'] ?? 0)];
        }
    }
    
    header('Content-Type: application/json');
    echo json_encode([
        'success' => true,
        'inbound_ids' => $inbound_ids,
        'limits' => $limits,
        'assignments' => $assignments
    ]);
    
} catch (Exception $e) {
    header('Content-Type: application/json');
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?>
