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

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

$user_id = $_SESSION['user_id'];

/* Pārbaudām, vai padots team_id */
if (!isset($_GET['team_id'])) {
    die("Team ID not provided.");
}

$team_id = (int)$_GET['team_id'];

/* Iegūstam komandas informāciju */
$team_stmt = $pdo->prepare("SELECT * FROM teams WHERE id = ?");
$team_stmt->execute([$team_id]);
$team = $team_stmt->fetch();

/* Ja komanda neeksistē */
if (!$team) {
    die("Team not found.");
}

/* Nosakām, vai lietotājs ir komandas īpašnieks */
$is_owner = ($team['created_by'] == $user_id);

/* Draugu pievienošana komandai (tikai īpašniekam) */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['friend_ids']) && $is_owner) {

    /* Sagatavojam vaicājumus */
    $insert = $pdo->prepare("INSERT INTO team_members (team_id, user_id) VALUES (?, ?)");
    $check = $pdo->prepare("SELECT 1 FROM team_members WHERE team_id = ? AND user_id = ?");

    /* Pievienojam tikai tos draugus, kuri vēl nav komandā */
    foreach ($_POST['friend_ids'] as $fid) {
        $fid = (int)$fid;
        $check->execute([$team_id, $fid]);
        if ($check->rowCount() === 0) {
            $insert->execute([$team_id, $fid]);
        }
    }

    header("Location: ?team_id=$team_id&added=1");
    exit();
}

/* Komandas dalībnieka noņemšana (tikai īpašniekam) */
if (isset($_GET['remove']) && $is_owner) {
    $remove_id = (int)$_GET['remove'];

    $del = $pdo->prepare("DELETE FROM team_members WHERE team_id = ? AND user_id = ?");
    $del->execute([$team_id, $remove_id]);

    header("Location: ?team_id=$team_id&removed=1");
    exit();
}

/* Iegūstam visus komandas dalībniekus */
$members = $pdo->prepare("
    SELECT u.id, u.name, u.email
    FROM users u
    JOIN team_members tm ON u.id = tm.user_id
    WHERE tm.team_id = ?
    ORDER BY u.name ASC
");
$members->execute([$team_id]);
$team_members = $members->fetchAll(PDO::FETCH_ASSOC);

/* Iegūstam draugus, kuri vēl nav šajā komandā */
$friends = $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 user_id FROM team_members WHERE team_id = ?
    )
    ORDER BY u.name ASC
");
$friends->execute([$user_id, $user_id, $user_id, $team_id]);
$available_friends = $friends->fetchAll(PDO::FETCH_ASSOC);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= htmlspecialchars($team['name']) ?> - Team View</title>
    <link rel="stylesheet" href="../css/style.css">
    <link rel="stylesheet" href="../css/team_view.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>

<main>
    <div class="team-view-container">
        <div class="team-header">
            <h2><?= htmlspecialchars($team['name']) ?></h2>
            <?php if ($is_owner): ?>
                <p style="margin: 10px 0 0 0; opacity: 0.9;">You are the team owner</p>
            <?php endif; ?>
        </div>

        <?php if (isset($_GET['added'])): ?>
            <div class="message-box success">Members added successfully!</div>
        <?php endif; ?>
        
        <?php if (isset($_GET['removed'])): ?>
            <div class="message-box success">Member removed successfully!</div>
        <?php endif; ?>

        <!-- Dalībnieku sadaļa -->
        <div class="members-section">
            <h3>Team Members (<?= count($team_members) ?>)</h3>
            
            <?php if (count($team_members) > 0): ?>
                <div class="members-grid">
                    <?php foreach ($team_members as $member): ?>
                        <div class="member-card">
                            <div class="member-info">
                                <div class="member-name"><?= htmlspecialchars($member['name']) ?></div>
                                <div class="member-email"><?= htmlspecialchars($member['email']) ?></div>
                            </div>
                            <?php if ($is_owner && $member['id'] != $user_id): ?>
                                <a href="?team_id=<?= $team_id ?>&remove=<?= $member['id'] ?>" 
                                   class="btn-remove-member"
                                   onclick="return confirm('Remove this member from the team?')">
                                   Remove
                                </a>
                            <?php endif; ?>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php else: ?>
                <div class="empty-members">
                    <p>No team members yet. Add friends to the team below!</p>
                </div>
            <?php endif; ?>
        </div>

        <!-- Sadaļa “Pievienot draugus” (tikai īpašniekam) -->
        <?php if ($is_owner): ?>
            <div class="add-friends-section">
                <h3>Add Friends to Team</h3>

                <?php if (count($available_friends) > 0): ?>
                    <form method="post">
                        <div class="friend-checkbox-container">
                            <?php foreach ($available_friends as $friend): ?>
                                <label class="friend-checkbox-label">
                                    <input type="checkbox" name="friend_ids[]" value="<?= $friend['id'] ?>">
                                    <div class="checkbox-friend-info">
                                        <span class="checkbox-friend-name"><?= htmlspecialchars($friend['name']) ?></span>
                                        <span class="checkbox-friend-email"><?= htmlspecialchars($friend['email']) ?></span>
                                    </div>
                                </label>
                            <?php endforeach; ?>
                        </div>
                        <button type="submit" class="btn-add-selected">Add Selected Friends to Team</button>
                    </form>
                <?php else: ?>
                    <div class="no-friends-message">
                        <p>All your friends are already in this team!</p>
                    </div>
                <?php endif; ?>
            </div>
        <?php endif; ?>

        <a href="teams.php" class="back-to-teams">← Back to Teams</a>
    </div>
</main>

</body>
</html>