<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

if(!isset($_SESSION['user_id'])){
    header('Location: index.php');
    exit;
}

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

// PAKSA UPDATE gereja_id DARI DB TIAP LOAD
if(in_array($_SESSION['role'], ['gembala', 'bendahara'])){
    $stmt = $conn->prepare("SELECT gereja_id FROM users WHERE id = ?");
    $stmt->execute([$_SESSION['user_id']]);
    $gereja_id_db = $stmt->fetchColumn();
    
    $_SESSION['gereja_id'] = $gereja_id_db; 
    
    // DEBUGGING: KASIH TAU ID BERAPA
    if(empty($gereja_id_db) && $_SESSION['role'] == 'gembala'){
        die('<div class="alert alert-danger m-3">Error: gereja_id untuk user ID '.$_SESSION['user_id'].' masih kosong di tabel users. Jalankan UPDATE SQL dulu.</div>');
    }
}

function cek_role($role_yang_boleh){
    if($_SESSION['role'] != $role_yang_boleh && $_SESSION['role'] != 'admin_dpw'){
        die('Akses ditolak.');
    }
}
require_once 'functions.php';
?>

