<?php
// api/teams.php
require_once __DIR__ . '/db.php';
session_start();

header('Content-Type: application/json');

function sendResponse($data, $statusCode = 200) {
    http_response_code($statusCode);
    echo json_encode($data);
    exit;
}

if (!isset($_SESSION['user_id'])) {
    sendResponse(['error' => 'Unauthorized.'], 401);
}

// Zkontroluje roli uživatele
function getRole($db, $boardId, $userId) {
    $stmt = $db->prepare('SELECT role FROM board_members WHERE board_id = ? AND user_id = ?');
    $stmt->execute([$boardId, $userId]);
    $member = $stmt->fetch();
    return $member ? $member['role'] : false;
}

$db = Database::getInstance()->getConnection();
$method = $_SERVER['REQUEST_METHOD'];
$userId = $_SESSION['user_id'];
$input = json_decode(file_get_contents('php://input'), true);

if ($method === 'GET') {
    $boardId = isset($_GET['board_id']) ? intval($_GET['board_id']) : 0;
    if (!$boardId) sendResponse(['error' => 'Board ID required.'], 400);

    if (!getRole($db, $boardId, $userId)) {
        sendResponse(['error' => 'Access denied.'], 403);
    }

    $stmt = $db->prepare('
        SELECT u.id, u.username, u.email, bm.role, bm.joined_at 
        FROM board_members bm
        JOIN users u ON bm.user_id = u.id
        WHERE bm.board_id = ?
        ORDER BY bm.role = "owner" DESC, bm.joined_at ASC
    ');
    $stmt->execute([$boardId]);
    $members = $stmt->fetchAll();

    sendResponse(['members' => $members]);
}
elseif ($method === 'POST') {
    // Přidání uživatele k boardu
    $boardId = $input['board_id'] ?? 0;
    $targetUserId = $input['user_id'] ?? 0;
    $role = in_array($input['role'] ?? '', ['editor', 'viewer', 'owner']) ? $input['role'] : 'editor';

    if (!$boardId || !$targetUserId) sendResponse(['error' => 'Missing parameters.'], 400);

    $myRole = getRole($db, $boardId, $userId);
    if ($myRole !== 'owner' && $myRole !== 'editor') {
        sendResponse(['error' => 'Only owners or editors can invite people.'], 403);
    }

    try {
        $stmt = $db->prepare('INSERT IGNORE INTO board_members (board_id, user_id, role) VALUES (?, ?, ?)');
        $stmt->execute([$boardId, $targetUserId, $role]);
        sendResponse(['message' => 'User added to board.'], 201);
    } catch (Exception $e) {
        sendResponse(['error' => 'Failed to add user.'], 500);
    }
}
elseif ($method === 'PUT') {
    // Změna role uživatele
    $boardId = $input['board_id'] ?? 0;
    $targetUserId = $input['user_id'] ?? 0;
    $newRole = in_array($input['role'] ?? '', ['editor', 'viewer', 'owner']) ? $input['role'] : null;

    if (!$boardId || !$targetUserId || !$newRole) sendResponse(['error' => 'Invalid parameters.'], 400);

    $myRole = getRole($db, $boardId, $userId);
    if ($myRole !== 'owner') {
        sendResponse(['error' => 'Only the owner can change roles.'], 403);
    }

    $stmt = $db->prepare('UPDATE board_members SET role = ? WHERE board_id = ? AND user_id = ?');
    $stmt->execute([$newRole, $boardId, $targetUserId]);
    sendResponse(['message' => 'Role updated.']);
}
elseif ($method === 'DELETE') {
    // Odstranění uživatele z boardu / opuštění boardu
    $boardId = $input['board_id'] ?? 0;
    $targetUserId = $input['user_id'] ?? 0;

    if (!$boardId || !$targetUserId) sendResponse(['error' => 'Missing parameters.'], 400);

    $myRole = getRole($db, $boardId, $userId);
    if ($myRole !== 'owner' && $targetUserId !== $userId) {
        // Můžu vyhodit jedině jako owner, nebo pokud se chci z boardu odejít sám (target == me)
        sendResponse(['error' => 'Insufficient permission to remove this user.'], 403);
    }

    // Owner nesmí smazat sám sebe z board_members, musel by smazat board celý
    if ($myRole === 'owner' && $targetUserId === $userId) {
        sendResponse(['error' => 'Owner cannot leave the board. Delete the board instead, or transfer ownership.'], 403);
    }

    $stmt = $db->prepare('DELETE FROM board_members WHERE board_id = ? AND user_id = ?');
    $stmt->execute([$boardId, $targetUserId]);
    sendResponse(['message' => 'User removed from the board.']);
}
else {
    sendResponse(['error' => 'Invalid method.'], 405);
}
