<?php
require_once 'auth.php';
require_once 'db/config.php';

if (!is_logged_in()) {
    header('Location: login.php');
    exit();
}

$user_id = $_SESSION['user_id'];
$pdo = db();
$teams = [];
$error_message = '';

// Handle team creation
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['create_team'])) {
    $team_name = trim($_POST['team_name']);
    if (!empty($team_name)) {
        try {
            // Create the team
            $stmt = $pdo->prepare("INSERT INTO teams (name, owner_user_id) VALUES (?, ?)");
            $stmt->execute([$team_name, $user_id]);
            $team_id = $pdo->lastInsertId();

            // Automatically add the creator as a member with the 'owner' role
            $stmt = $pdo->prepare("INSERT INTO team_members (team_id, user_id, role) VALUES (?, ?, 'owner')");
            $stmt->execute([$team_id, $user_id]);
            
            header('Location: teams.php'); // Redirect to avoid form resubmission
            exit();
        } catch (PDOException $e) {
            error_log("Database error in teams.php (create team): " . $e->getMessage());
            $error_message = "Failed to create team. Please try again.";
        }
    }
}

// Fetch teams for the current user
try {
    $stmt = $pdo->prepare(
        "SELECT t.id, t.name, t.owner_user_id FROM teams t " .
        "JOIN team_members tm ON t.id = tm.team_id " .
        "WHERE tm.user_id = ?"
    );
    $stmt->execute([$user_id]);
    $teams = $stmt->fetchAll();
} catch (PDOException $e) {
    error_log("Database error in teams.php (fetch teams): " . $e->getMessage());
    $error_message = "Failed to load teams. Please contact support.";
}


require_once 'partials/header.php';

?>

<div class="container mt-5">
    <div class="row">
        <div class="col-md-8">
            <h2>My Teams</h2>
            <?php if (!empty($error_message)): ?>
                <div class="alert alert-danger"><?php echo htmlspecialchars($error_message); ?></div>
            <?php endif; ?>
            
            <?php if (empty($teams)): ?>
                <p>You are not a member of any teams yet.</p>
            <?php else: ?>
                <ul class="list-group">
                    <?php foreach ($teams as $team): ?>
                        <li class="list-group-item d-flex justify-content-between align-items-center">
                            <a href="team.php?id=<?php echo $team['id']; ?>"><?php echo htmlspecialchars($team['name']); ?></a>
                            <?php if ($team['owner_user_id'] == $user_id): ?>
                                <span class="badge bg-primary rounded-pill">Owner</span>
                            <?php endif; ?>
                        </li>
                    <?php endforeach; ?>
                </ul>
            <?php endif; ?>
        </div>
        <div class="col-md-4">
            <div class="card">
                <div class="card-body">
                    <h5 class="card-title">Create a New Team</h5>
                    <form method="POST">
                        <div class="mb-3">
                            <label for="team_name" class="form-label">Team Name</label>
                            <input type="text" class="form-control" id="team_name" name="team_name" required>
                        </div>
                        <button type="submit" name="create_team" class="btn btn-primary">Create Team</button>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<?php 
require_once 'partials/footer.php';
?>