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

$calendar_id = $_POST['calendar_id'] ?? 0;
$team_id     = $_POST['team_id']     ?? 0;
$user_id     = $_SESSION['user_id']  ?? 0;

if (!$calendar_id || !$team_id || !$user_id) {
    echo "Invalid request";
    exit();
}

// Pārbaudām, vai kalendārs pieder lietotājam
$check_stmt = $pdo->prepare("SELECT id FROM calendars WHERE id = ? AND user_id = ?");
$check_stmt->execute([$calendar_id, $user_id]);
if (!$check_stmt->fetch()) {
    echo "Calendar not found";
    exit();
}

// Iegūstam visus komandas dalībniekus
$members_stmt = $pdo->prepare("SELECT user_id FROM team_members WHERE team_id = ?");
$members_stmt->execute([$team_id]);
$members = $members_stmt->fetchAll(PDO::FETCH_COLUMN);

if (!$members) {
    echo "No members in this team";
    exit();
}

$count = 0;

foreach ($members as $member_id) {
    // Pārbaudām vai šis lietotājs jau ir pievienots šim kalendāram
    $exists_stmt = $pdo->prepare("
        SELECT id FROM friends 
        WHERE user_id = ? AND friend_id = ? AND calendar_id = ?
    ");
    $exists_stmt->execute([$user_id, $member_id, $calendar_id]);

    if (!$exists_stmt->fetch()) {
        // Pievienojam ar status accepted, jo komandas dalībnieki jau ir apstiprināti
        $insert_stmt = $pdo->prepare("
            INSERT INTO friends (user_id, friend_id, calendar_id, can_edit, status)
            VALUES (?, ?, ?, 0, 'accepted')
        ");
        $insert_stmt->execute([$user_id, $member_id, $calendar_id]);

        // Pievienojam arī calendar_access tabulā
        $access_stmt = $pdo->prepare("
            INSERT IGNORE INTO calendar_access (calendar_id, user_id, can_edit)
            VALUES (?, ?, 0)
        ");
        $access_stmt->execute([$calendar_id, $member_id]);

        $count++;
    }
}

echo "OK:$count";