<?php
session_start();
include '../database/db.php';

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['friends'=>[], 'teams'=>[]]);
    exit();
}

$user_id = $_SESSION['user_id'];
$calendar_id = isset($_GET['calendar_id']) ? intval($_GET['calendar_id']) : 0;

if ($calendar_id <= 0) {
    echo json_encode(['friends'=>[], 'teams'=>[]]);
    exit();
}

// Tikai apstiprinātie draugi, kuri vēl nav pievienoti šim kalendāram
$friends_stmt = $pdo->prepare("
    SELECT u.id, u.name, u.email
    FROM users u
    WHERE u.id != ?
    AND (
        u.id IN (
            SELECT friend_id FROM friends 
            WHERE user_id = ? AND status = 'accepted'
        )
        OR
        u.id IN (
            SELECT user_id FROM friends 
            WHERE friend_id = ? AND status = 'accepted'
        )
    )
    AND u.id NOT IN (
        SELECT friend_id FROM friends 
        WHERE user_id = ? AND calendar_id = ?
    )
    ORDER BY u.name
");
$friends_stmt->execute([$user_id, $user_id, $user_id, $user_id, $calendar_id]);
$available_friends = $friends_stmt->fetchAll(PDO::FETCH_ASSOC);

// Lietotāja komandas ar dalībnieku skaitu
$teams_stmt = $pdo->prepare("
    SELECT t.id, t.name, COUNT(tm.user_id) as member_count
    FROM teams t
    LEFT JOIN team_members tm ON t.id = tm.team_id
    WHERE t.created_by = ?
    GROUP BY t.id
    ORDER BY t.name
");
$teams_stmt->execute([$user_id]);
$available_teams = $teams_stmt->fetchAll(PDO::FETCH_ASSOC);

echo json_encode([
    'friends' => $available_friends,
    'teams'   => $available_teams
]);