<?php
session_start();
header('Content-Type: application/json');
if(!isset($_SESSION['user_id'])) die(json_encode(['status'=>'error','message'=>'Akses ditolak']));

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

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

try {
    if($role == 'admin_dpw'){
        // TAMBAH j.kaum DI SELECT
        $sql = "SELECT j.id, j.no_anggota, j.nama_lengkap, j.nik, j.foto, j.no_hp, j.jenis_kelamin, j.kaum, j.status_baptis, g.nama_gereja 
                FROM jemaat j 
                LEFT JOIN gereja g ON j.gereja_id=g.id 
                ORDER BY j.id DESC";
        $stmt = $conn->prepare($sql);
        $stmt->execute();
    } else {
        // TAMBAH j.kaum DI SELECT
        $sql = "SELECT j.id, j.no_anggota, j.nama_lengkap, j.nik, j.foto, j.no_hp, j.jenis_kelamin, j.kaum, j.status_baptis, g.nama_gereja 
                FROM jemaat j 
                LEFT JOIN gereja g ON j.gereja_id=g.id 
                WHERE j.gereja_id=? 
                ORDER BY j.id DESC";
        $stmt = $conn->prepare($sql);
        $stmt->execute([$gereja_id]);
    }
    
    $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
    echo json_encode(['status'=>'success','data'=>$data]);
    
} catch(PDOException $e){
    echo json_encode(['status'=>'error','message'=>$e->getMessage()]);
}
?>