<?php
require_once __DIR__ . "/require-auth.php";
require_once __DIR__ . "/../services/db.php";

function requireProjectRole($conn, $projectId, $allowedRoles = ["owner", "member"]) {
    global $authUser;

    $sql = "SELECT role FROM project_members
            WHERE project_id = ? AND user_id = ?";
    $stmt = sqlsrv_query($conn, $sql, [$projectId, $authUser["id"]]);
    $row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC);

    if (!$row) {
        http_response_code(403);
        echo json_encode(["error" => "Not a project member"]);
        exit;
    }

    if (!in_array($row["role"], $allowedRoles)) {
        http_response_code(403);
        echo json_encode(["error" => "Insufficient permissions"]);
        exit;
    }

    return $row["role"];
}
