<?php
header("Content-Type: application/json");
include '../../config.php';

// Pata user_id kutoka kwa GET parameters
$user_id = isset($_GET['user_id']) ? intval($_GET['user_id']) : 0;

if ($user_id === 0) {
    echo json_encode(["error" => "Invalid parameters"]);
    exit;
}

// Pata branch_id na type ya user
$query = "SELECT branch_id, type FROM users WHERE id = ?";
$stmt = $conn->prepare($query);
$stmt->bind_param("i", $user_id);
$stmt->execute();
$stmt->bind_result($branch_id, $user_type);
$stmt->fetch();
$stmt->close();

// Kama admin (branch_id = 0 na type = 1), chukua users wote
if ($branch_id == 0 && $user_type == 1) {
    $sql = "SELECT 
                u.id,
                u.firstname,
                u.lastname,
                u.email,
                u.phone,
                u.branch_id,
                u.type,
                u.created_at,
                b.branch_name,
                IF(u.id = ?, 'Admin', '') AS badge
            FROM users u
            LEFT JOIN branches b ON u.branch_id = b.branch_id
            ORDER BY IF(u.id = ?, 0, 1), u.firstname ASC"; // Admin kwanza, halafu alphabetical
} else {
    // Kama si admin, chukua users wa branch zake tu
    $sql = "SELECT 
                u.id,
                u.firstname,
                u.lastname,
                u.email,
                u.phone,
                u.branch_id,
                u.type,
                u.created_at,
                b.branch_name,
                IF(u.id = ?, 'Admin', '') AS badge
            FROM users u
            INNER JOIN branches b ON u.branch_id = b.branch_id
            WHERE u.branch_id IN (SELECT branch_id FROM branches WHERE user_id = ?)
            ORDER BY IF(u.id = ?, 0, 1), u.firstname ASC"; // Admin kwanza, halafu alphabetical
}

$stmt = $conn->prepare($sql);
if ($branch_id == 0 && $user_type == 1) {
    $stmt->bind_param("ii", $user_id, $user_id);
} else {
    $stmt->bind_param("iii", $user_id, $user_id, $user_id);
}

$stmt->execute();
$result = $stmt->get_result();

$staffs = [];
while ($row = $result->fetch_assoc()) {
    $staffs[] = $row;
}

$stmt->close();
$conn->close();

echo json_encode($staffs);
?>
