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

if (!isset($_SESSION['user_id'])) {
    header("Location: ../users/login.php");
    exit();
}

$user_id = $_SESSION['user_id'];

// Iegūt tikai APSTIPRINĀTUS draugus (abos virzienos)
$friends_stmt = $pdo->prepare("
    SELECT u.id, u.name 
    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'
        )
    )
    ORDER BY u.name ASC
");
$friends_stmt->execute([$user_id, $user_id, $user_id]);
$friends = $friends_stmt->fetchAll(PDO::FETCH_ASSOC);

// Iegūt komandas
$teams_stmt = $pdo->prepare("SELECT * FROM teams WHERE created_by = ? ORDER BY name ASC");
$teams_stmt->execute([$user_id]);
$teams = $teams_stmt->fetchAll(PDO::FETCH_ASSOC);

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $name  = trim($_POST['name']);
    $selected_friends = $_POST['friends']      ?? [];
    $friend_roles     = $_POST['friend_roles'] ?? [];
    $selected_teams   = $_POST['teams']        ?? [];
    $team_roles       = $_POST['team_roles']   ?? [];

    if (!empty($name)) {
        // Izveido kalendāru
        $stmt = $pdo->prepare("INSERT INTO calendars (user_id, name) VALUES (?, ?)");
        $stmt->execute([$user_id, $name]);
        $calendar_id = $pdo->lastInsertId();

        // Pievieno draugus
        foreach ($selected_friends as $friend_id => $val) {
            $role     = $friend_roles[$friend_id] ?? 'viewer';
            $can_edit = ($role === 'editor') ? 1 : 0;

            // Pārbaudām vai jau nav pievienots
            $exists = $pdo->prepare("
                SELECT id FROM friends 
                WHERE user_id = ? AND friend_id = ? AND calendar_id = ?
            ");
            $exists->execute([$user_id, $friend_id, $calendar_id]);

            if (!$exists->fetch()) {
                $pdo->prepare("
                    INSERT INTO friends (user_id, friend_id, can_edit, calendar_id, status)
                    VALUES (?, ?, ?, ?, 'accepted')
                ")->execute([$user_id, $friend_id, $can_edit, $calendar_id]);
            }

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

        // Pievieno komandas
        foreach ($selected_teams as $team_id => $val) {
            $role     = $team_roles[$team_id] ?? 'viewer';
            $can_edit = ($role === 'editor') ? 1 : 0;

            // 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);

            foreach ($members as $member_id) {
                $exists = $pdo->prepare("
                    SELECT id FROM friends 
                    WHERE user_id = ? AND friend_id = ? AND calendar_id = ?
                ");
                $exists->execute([$user_id, $member_id, $calendar_id]);

                if (!$exists->fetch()) {
                    $pdo->prepare("
                        INSERT INTO friends (user_id, friend_id, can_edit, calendar_id, status)
                        VALUES (?, ?, ?, ?, 'accepted')
                    ")->execute([$user_id, $member_id, $can_edit, $calendar_id]);
                }

                // calendar_access
                $pdo->prepare("
                    INSERT IGNORE INTO calendar_access (calendar_id, user_id, can_edit)
                    VALUES (?, ?, ?)
                ")->execute([$calendar_id, $member_id, $can_edit]);
            }
        }

        header("Location: ../dashboard.php");
        exit();
    } else {
        $error = "Please enter a calendar name.";
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Create Calendar</title>
<link rel="stylesheet" href="../css/calendar.css">
</head>
<body>
<nav>
    <ul>
        <li><a href="../dashboard.php">Dashboard</a></li>
        <li><a href="../calendar/calendar.php">Calendar</a></li>
        <li><a href="../tasks/tasks.php">All Tasks</a></li>
        <li><a href="../teams/teams.php">Teams</a></li>
        <li><a href="../friends/add_friend.php">Friends</a></li>
        <li><a href="../profile/profile.php">Profile</a></li>
        <li><a href="../users/logout.php">Logout</a></li>
    </ul>
</nav>

<div class="form-container">
    <h2>Create New Calendar</h2>

    <?php if (isset($error)) echo "<p class='error'>$error</p>"; ?>

    <form method="POST">
        <label>Calendar Name</label>
        <input type="text" name="name" required>

        <!-- DRAUGI -->
        <h3>Add Friends</h3>
        <?php if (!empty($friends)): ?>
            <div class="friends-container">
                <?php foreach ($friends as $f): ?>
                    <label class="friend-item">
                        <input type="checkbox" name="friends[<?= $f['id'] ?>]" value="1">
                        <?= htmlspecialchars($f['name']) ?>
                        <span class="role-select">
                            <select name="friend_roles[<?= $f['id'] ?>]">
                                <option value="viewer">Viewer</option>
                                <option value="editor">Editor</option>
                            </select>
                        </span>
                    </label>
                <?php endforeach; ?>
            </div>
        <?php else: ?>
            <p style="color:#666; font-style:italic;">No friends available to add.</p>
        <?php endif; ?>

        <!-- KOMANDAS -->
        <h3>Add Teams</h3>
        <?php if (!empty($teams)): ?>
            <div class="teams-container">
                <?php foreach ($teams as $team): ?>
                    <label class="team-item">
                        <input type="checkbox" name="teams[<?= $team['id'] ?>]" value="1">
                        <?= htmlspecialchars($team['name']) ?>
                        <span class="role-select">
                            <select name="team_roles[<?= $team['id'] ?>]">
                                <option value="viewer">Viewer</option>
                                <option value="editor">Editor</option>
                            </select>
                        </span>
                    </label>
                <?php endforeach; ?>
            </div>
        <?php else: ?>
            <p style="color:#666; font-style:italic;">No teams available to add.</p>
        <?php endif; ?>

        <button type="submit">Create Calendar</button>
        <a href="../dashboard.php" class="cancel-link">Cancel</a>
    </form>
</div>
</body>
</html>