<?php
require_once __DIR__ . '/../includes/session_check.php';
require_once __DIR__ . '/../includes/db.php';

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

// Admin-only access
if ($_SESSION['role'] !== 'admin') {
    echo json_encode(['error' => 'Unauthorized']);
    exit();
}

$recipientId = $_GET['recipient_id'] ?? null;

if (!$recipientId) {
    echo json_encode(['error' => 'Recipient ID missing']);
    exit();
}

try {
    // Obtener el nombre del usuario
    $stmt = $pdo->prepare("SELECT name FROM recipients WHERE id = ?");
    $stmt->execute([$recipientId]);
    $userName = $stmt->fetchColumn();

    // Obtener los grupos a los que pertenece el usuario
    $stmt = $pdo->prepare("
        SELECT tgm.chat_id, r.name as group_name
        FROM telegram_group_members tgm
        JOIN recipients r ON tgm.chat_id = r.platform_id AND r.platform = 'telegram' AND r.type = 'channel'
        WHERE tgm.recipient_id = ?
    ");
    $stmt->execute([$recipientId]);
    $groups = $stmt->fetchAll(PDO::FETCH_ASSOC);

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

} catch (PDOException $e) {
    error_log("Error fetching user groups: " . $e->getMessage());
    echo json_encode(['error' => 'Database error']);
} catch (Exception $e) {
    error_log("Error: " . $e->getMessage());
    echo json_encode(['error' => 'Server error']);
}
?>