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

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

if ($id <= 0) {
    echo json_encode(["calendar" => false, "friends" => []]);
    exit();
}

$stmt = $pdo->prepare("SELECT * FROM calendars WHERE id=? AND user_id=?");
$stmt->execute([$id, $user]);
$calendar = $stmt->fetch();

$friends = $pdo->prepare("
    SELECT f.id, u.name, f.can_edit
    FROM friends f
    JOIN users u ON f.friend_id = u.id
    WHERE f.calendar_id=? AND f.user_id=?
");
$friends->execute([$id, $user]);
$list = $friends->fetchAll(PDO::FETCH_ASSOC);

echo json_encode([ "calendar" => $calendar ?: false, "friends" => $list ]);