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

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

if (!$calendar_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 friend_id
if (isset($_POST['email'])) {
    $stmt = $pdo->prepare("SELECT id FROM users WHERE email = ?");
    $stmt->execute([$_POST['email']]);
    $friend = $stmt->fetch();
    if (!$friend) { echo "No user"; exit(); }
    $friend_id = $friend['id'];
} elseif (isset($_POST['friend_id'])) {
    $friend_id = (int)$_POST['friend_id'];
} else {
    echo "Email or friend_id required";
    exit();
}

// Pārbaudām vai ir apstiprināta draudzība
$friendship_stmt = $pdo->prepare("
    SELECT id FROM friends 
    WHERE (
        (user_id = ? AND friend_id = ?) 
        OR 
        (user_id = ? AND friend_id = ?)
    ) AND status = 'accepted'
");
$friendship_stmt->execute([$user_id, $friend_id, $friend_id, $user_id]);
if (!$friendship_stmt->fetch()) {
    echo "Not friends";
    exit();
}

// Pārbaudām vai draugs jau nav 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, $friend_id, $calendar_id]);
if ($exists_stmt->fetch()) {
    echo "Already added";
    exit();
}

// Pievienojam draugu kalendāram
$insert = $pdo->prepare("
    INSERT INTO friends (user_id, friend_id, calendar_id, can_edit, status)
    VALUES (?, ?, ?, 0, 'accepted')
");
$insert->execute([$user_id, $friend_id, $calendar_id]);

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

echo "OK";