<?php
session_start();
include '../config/database.php';
$db = new Database();
$conn = $db->getConnection();

$role = $_SESSION['role'];
$user_id = $_SESSION['user_id'];

if($role == 'admin' || $role == 'admin_dpw'){
    $sql = "SELECT j.id, j.nama_lengkap, j.no_hp, g.nama_gereja 
            FROM jemaat j 
            LEFT JOIN pelayan p ON j.id = p.jemaat_id 
            LEFT JOIN gereja g ON j.gereja_id = g.id 
            WHERE p.id IS NULL ORDER BY j.nama_lengkap";
    $stmt = $conn->query($sql);
} else {
    $stmt_user = $conn->prepare("SELECT gereja_id FROM users WHERE id =?");
    $stmt_user->execute([$user_id]);
    $gereja_id = $stmt_user->fetchColumn();
    
    $sql = "SELECT j.id, j.nama_lengkap, j.no_hp 
            FROM jemaat j 
            LEFT JOIN pelayan p ON j.id = p.jemaat_id 
            WHERE j.gereja_id =? AND p.id IS NULL ORDER BY j.nama_lengkap";
    $stmt = $conn->prepare($sql);
    $stmt->execute([$gereja_id]);
}

header('Content-Type: application/json');
echo json_encode(['data' => $stmt->fetchAll(PDO::FETCH_ASSOC)]);
?>