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

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

if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    header('Location: teams.php');
    exit();
}

$team_id = $_GET['id'];
$user_id = $_SESSION['user_id'];
$pdo = db();

// Get the current user's role in the team
$stmt = $pdo->prepare("SELECT role FROM team_members WHERE team_id = ? AND user_id = ?");
$stmt->execute([$team_id, $user_id]);
$current_user_role = $stmt->fetchColumn();

// Fetch team details
$stmt = $pdo->prepare("SELECT name, owner_user_id FROM teams WHERE id = ?");
$stmt->execute([$team_id]);
$team = $stmt->fetch();

if (!$team) {
    header('Location: teams.php');
    exit();
}

$is_owner = ($current_user_role == 'owner');
$is_admin = ($current_user_role == 'admin');
$is_member = $current_user_role;

// Handle POST requests for team management
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Must be a member to perform any action
    if (!$is_member) {
        header("Location: team.php?id=$team_id");
        exit();
    }

    // Add a new member
    if (isset($_POST['add_member']) && ($is_owner || $is_admin)) {
        $email = trim($_POST['email']);
        $stmt = $pdo->prepare("SELECT id FROM users WHERE email = ?");
        $stmt->execute([$email]);
        $new_member_id = $stmt->fetchColumn();

        if ($new_member_id) {
            // Add as a 'member' by default
            $stmt = $pdo->prepare("INSERT IGNORE INTO team_members (team_id, user_id, role) VALUES (?, ?, 'member')");
            $stmt->execute([$team_id, $new_member_id]);
        }
    }

    // Remove a member
    if (isset($_POST['remove_member']) && isset($_POST['member_id'])) {
        $member_id_to_remove = $_POST['member_id'];

        // Get the role of the member to be removed
        $stmt = $pdo->prepare("SELECT role FROM team_members WHERE team_id = ? AND user_id = ?");
        $stmt->execute([$team_id, $member_id_to_remove]);
        $member_to_remove_role = $stmt->fetchColumn();

        // Owners can remove anyone except themselves
        // Admins can only remove members
        if ($is_owner && $member_id_to_remove != $user_id) {
            $stmt = $pdo->prepare("DELETE FROM team_members WHERE team_id = ? AND user_id = ?");
            $stmt->execute([$team_id, $member_id_to_remove]);
        } elseif ($is_admin && $member_to_remove_role == 'member') {
            $stmt = $pdo->prepare("DELETE FROM team_members WHERE team_id = ? AND user_id = ?");
            $stmt->execute([$team_id, $member_id_to_remove]);
        }
    }

    // Promote to Admin
    if (isset($_POST['promote_admin']) && isset($_POST['member_id']) && $is_owner) {
        $member_id_to_promote = $_POST['member_id'];
        $stmt = $pdo->prepare("UPDATE team_members SET role = 'admin' WHERE team_id = ? AND user_id = ? AND role = 'member'");
        $stmt->execute([$team_id, $member_id_to_promote]);
    }

    // Demote to Member
    if (isset($_POST['demote_admin']) && isset($_POST['member_id']) && $is_owner) {
        $member_id_to_demote = $_POST['member_id'];
        $stmt = $pdo->prepare("UPDATE team_members SET role = 'member' WHERE team_id = ? AND user_id = ? AND role = 'admin'");
        $stmt->execute([$team_id, $member_id_to_demote]);
    }
    
    // Transfer Ownership
    if (isset($_POST['make_owner']) && isset($_POST['member_id']) && $is_owner) {
        $new_owner_id = $_POST['member_id'];
        // Start transaction
        $pdo->beginTransaction();
        try {
            // New owner becomes 'owner'
            $stmt = $pdo->prepare("UPDATE team_members SET role = 'owner' WHERE team_id = ? AND user_id = ?");
            $stmt->execute([$team_id, $new_owner_id]);

            // Old owner becomes 'admin'
            $stmt = $pdo->prepare("UPDATE team_members SET role = 'admin' WHERE team_id = ? AND user_id = ?");
            $stmt->execute([$team_id, $user_id]);
            
            // Update owner_user_id in teams table
            $stmt = $pdo->prepare("UPDATE teams SET owner_user_id = ? WHERE id = ?");
            $stmt->execute([$new_owner_id, $team_id]);

            $pdo->commit();
        } catch (Exception $e) {
            $pdo->rollBack();
        }
    }

    // Leave team
    if (isset($_POST['leave_team']) && !$is_owner) {
        $stmt = $pdo->prepare("DELETE FROM team_members WHERE team_id = ? AND user_id = ?");
        $stmt->execute([$team_id, $user_id]);
        header("Location: teams.php"); // Redirect to teams list after leaving
        exit();
    }

    header("Location: team.php?id=$team_id");
    exit();
}

require_once 'partials/header.php';

// Fetch all team members with their roles and user details
$stmt = $pdo->prepare(
    "SELECT u.id, u.name, u.email, tm.role FROM users u " .
    "JOIN team_members tm ON u.id = tm.user_id " .
    "WHERE tm.team_id = ? ORDER BY tm.role, u.name"
);
$stmt->execute([$team_id]);
$members = $stmt->fetchAll();

?>

<div class="container mt-5">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2>Team: <?php echo htmlspecialchars($team['name']); ?></h2>
        <?php if ($is_member && !$is_owner): ?>
            <form method="POST" onsubmit="return confirm('Are you sure you want to leave this team?');">
                <button type="submit" name="leave_team" class="btn btn-danger">Leave Team</button>
            </form>
        <?php elseif ($is_owner): ?>
             <span class="text-muted">You are the owner. Transfer ownership to leave.</span>
        <?php endif; ?>
    </div>

    <?php if (!$is_member): ?>
        <div class="alert alert-warning">You are not a member of this team.</div>
        <?php // In a future step, we could show a public/private status and a join button here ?>
    <?php else: ?>
        <?php if ($is_owner || $is_admin): ?>
        <div class="card mb-4">
            <div class="card-header">Add New Member</div>
            <div class="card-body">
                <form method="POST" class="row g-3">
                    <div class="col-auto">
                        <input type="email" class="form-control" name="email" placeholder="Enter user's email" required>
                    </div>
                    <div class="col-auto">
                        <button type="submit" name="add_member" class="btn btn-primary">Add Member</button>
                    </div>
                </form>
            </div>
        </div>
        <?php endif; ?>

        <h4>Members (<?php echo count($members); ?>)</h4>
        <div class="list-group">
            <?php foreach ($members as $member): ?>
                <div class="list-group-item d-flex justify-content-between align-items-center">
                    <div>
                        <strong><?php echo htmlspecialchars($member['name']); ?></strong> (<?php echo htmlspecialchars($member['email']); ?>)
                        <span class="badge bg-secondary ms-2"><?php echo ucfirst($member['role']); ?></span>
                    </div>
                    <div class="btn-group">
                        <?php if ($is_owner && $member['id'] !== $user_id): ?>
                            <form method="POST" class="d-inline" onsubmit="return confirm('Promote this member to Admin?');">
                                <input type="hidden" name="member_id" value="<?php echo $member['id']; ?>">
                                <?php if ($member['role'] == 'member'): ?>
                                <button type="submit" name="promote_admin" class="btn btn-sm btn-outline-secondary">Promote to Admin</button>
                                <?php elseif ($member['role'] == 'admin'): ?>
                                <form method="POST" class="d-inline" onsubmit="return confirm('Demote this member to Member?');">
                                    <input type="hidden" name="member_id" value="<?php echo $member['id']; ?>">
                                    <button type="submit" name="demote_admin" class="btn btn-sm btn-outline-warning">Demote to Member</button>
                                </form>
                                <?php endif; ?>
                            </form>
                            <form method="POST" class="d-inline ms-1" onsubmit="return confirm('Make this member the new owner? You will become an Admin.');">
                                <input type="hidden" name="member_id" value="<?php echo $member['id']; ?>">
                                <button type="submit" name="make_owner" class="btn btn-sm btn-outline-primary">Make Owner</button>
                            </form>
                             <form method="POST" class="d-inline ms-1" onsubmit="return confirm('Are you sure you want to remove this member?');">
                                <input type="hidden" name="member_id" value="<?php echo $member['id']; ?>">
                                <button type="submit" name="remove_member" class="btn btn-sm btn-danger">Remove</button>
                            </form>
                        <?php elseif ($is_admin && $member['role'] === 'member'): ?>
                            <form method="POST" class="d-inline" onsubmit="return confirm('Are you sure you want to remove this member?');">
                                <input type="hidden" name="member_id" value="<?php echo $member['id']; ?>">
                                <button type="submit" name="remove_member" class="btn btn-sm btn-danger">Remove</button>
                            </form>
                        <?php endif; ?>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>
</div>

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