<?php
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../config/auth.php';
$user = requireAuth();
$db   = getDB();

$action    = post('action', 'list');
$projectId = (int)post('project_id', 0);
if (!$projectId) apiError('Project ID required.', 422);

if ($action === 'list') {
    $stmt = $db->prepare("
        SELECT pm.*, u.full_name, u.email,
               r.name AS role_name
        FROM project_members pm
        JOIN users u ON u.id = pm.user_id
        LEFT JOIN roles r ON r.id = u.role_id
        WHERE pm.project_id=?
        ORDER BY pm.role, full_name
    ");
    $stmt->execute([$projectId]);
    apiSuccess(['members' => $stmt->fetchAll()]);
}

if ($action === 'add') {
    $userId = (int)post('user_id', 0);
    if (!$userId) apiError('User ID required.', 422);
    // upsert
    $db->prepare("
        INSERT INTO project_members (project_id, user_id, role)
        VALUES (?,?,?)
        ON DUPLICATE KEY UPDATE role=VALUES(role)
    ")->execute([$projectId, $userId, post('role','member')]);
    apiSuccess([], 'Member added.');
}

if ($action === 'remove') {
    $userId = (int)post('user_id', 0);
    $db->prepare("DELETE FROM project_members WHERE project_id=? AND user_id=?")->execute([$projectId, $userId]);
    apiSuccess([], 'Member removed.');
}

apiError('Unknown action.', 400);
