<?php
session_start();
header('Content-Type: application/json');
include '../config/database.php';
$db = new Database();
$conn = $db->getConnection();

$username = $_POST['username'];
$password = $_POST['password'];

$stmt = $conn->prepare("SELECT u.*, g.nama_gereja 
                        FROM users u 
                        LEFT JOIN gereja g ON u.gereja_id = g.id 
                        WHERE u.username=?");
$stmt->execute([$username]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

if($user && password_verify($password, $user['password'])){
    $_SESSION['user_id'] = $user['id'];
    $_SESSION['nama'] = $user['nama'];
    $_SESSION['username'] = $user['username'];
    $_SESSION['role'] = $user['role'];
    $_SESSION['gereja_id'] = $user['gereja_id']; // Wajib buat filter data
    $_SESSION['nama_gereja'] = $user['nama_gereja']; 
    $_SESSION['foto'] = $user['foto'];
    $_SESSION['created'] = time();

    // TENTUKAN REDIRECT BERDASARKAN ROLE
    if($user['role'] == 'admin_dpw'){
        $redirect = 'dashboard.php';
    } elseif($user['role'] == 'gembala'){
        $redirect = 'dashboard.php';
    } elseif($user['role'] == 'bendahara'){
        $redirect = 'dashboard_bendahara.php'; // Arahkan ke dashboard khusus bendahara
    } else {
        $redirect = 'login.php'; // Fallback kalau role aneh
    }
    
    echo json_encode([
        'status'=>'success',
        'redirect'=>$redirect,
        'role'=>$user['role'],
        'nama'=>$user['nama']
    ]);
} else {
    echo json_encode(['status'=>'error','message'=>'Username/Password salah']);
}
?>