<?php
header("Content-Type: application/json");
require_once __DIR__ . "/../auth/require-auth.php";
require_once __DIR__ . "/../services/db.php";

$conn = db();
$projectId = isset($_GET['project_id']) ? (int)$_GET['project_id'] : (isset($_GET['id']) ? (int)$_GET['id'] : 1);

// Query distinct members including project owner + project_members
$sql = "SELECT DISTINCT u.id, u.name, u.email, u.avatar_url 
        FROM users u 
        WHERE u.id IN (
            SELECT owner_id FROM projects WHERE id = ?
            UNION
            SELECT user_id FROM project_members WHERE project_id = ?
        )";

$stmt = sqlsrv_query($conn, $sql, [$projectId, $projectId]);

$members = [];
if ($stmt !== false) {
    while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
        $members[] = [
            "id" => (int)$row['id'],
            "name" => $row['name'],
            "email" => $row['email'],
            "avatar_url" => $row['avatar_url']
        ];
    }
}

// If no user found in database, fallback to session user
if (empty($members) && isset($_SESSION['user'])) {
    $members[] = [
        "id" => $_SESSION['user']['id'] ?? 1,
        "name" => $_SESSION['user']['name'] ?? 'User',
        "email" => $_SESSION['user']['email'] ?? ''
    ];
}

echo json_encode($members);