<?php
session_start();
header('Content-Type: application/json');
require_once '../config/auth.php';
require_once '../config/database.php';

if(!isset($_SESSION['user_id'])) die(json_encode(['status'=>'error','message'=>'Belum login']));

$db = new Database();
$conn = $db->getConnection();
$role = $_SESSION['role'];
$user_id = $_SESSION['user_id'];

if($role == 'admin_dpw'){
    $sql = "SELECT j.*, 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 {
    // GEMBALA: AMBIL JEMAAT BERDASAR GEREJA DIA
    $sql = "SELECT j.*, g.nama_gereja 
            FROM jemaat j 
            INNER JOIN gereja g ON j.gereja_id = g.id 
            WHERE g.gembala_id =? 
            ORDER BY j.id DESC";
    $stmt = $conn->prepare($sql);
    $stmt->execute([$user_id]);
}

$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode(['status'=>'success','data'=>$data]);
?>