<?php
// api_get_user.php
error_log("DEBUG: api_get_user.php script started at " . date('Y-m-d H:i:s'));

// Konfigurasi sesi agar berlaku di semua subdomain
ini_set('session.cookie_domain', '.sumberbarokahsentosa.my.id');

// Optional: Set cookie parameters for SameSite if you encounter issues, especially with HTTPS
// If you are using HTTPS, uncomment and adjust these lines.
// If not using HTTPS, 'secure' must be false, but SameSite=None usually requires secure.
/*
session_set_cookie_params([
    'lifetime' => 0, // 0 means until browser closes
    'path' => '/',
    'domain' => '.sumberbarokahsentosa.my.id',
    'secure' => true, // Set to true if using HTTPS, false otherwise. SameSite=None usually requires secure.
    'httponly' => true,
    'samesite' => 'Lax' // Change to 'None' if 'Lax' causes issues with cross-subdomain, but requires 'secure'
]);
*/

session_start();

// --- PASTIKAN BARIS INI ADA UNTUK DEBUGGING ---
error_log("API_GET_USER: PHPSESSID from cookie: " . ($_COOKIE['PHPSESSID'] ?? 'NOT SET IN COOKIE'));
error_log("API_GET_USER: Session ID: " . session_id());
error_log("API_GET_USER: Session data (username): " . ($_SESSION['username'] ?? 'NOT SET IN SESSION'));
error_log("API_GET_USER: Session data (role): " . ($_SESSION['role'] ?? 'NOT SET IN SESSION')); // Tambahkan log role
// --- AKHIR DEBUGGING ---

// Konfigurasi CORS
header("Access-Control-Allow-Origin: https://sumberbarokahsentosa.my.id");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization");

header('Content-Type: application/json');

$response = [
    'loggedIn' => false,
    'username' => null,
    'role' => null // Tambahkan role ke respons default
];

if (isset($_SESSION['username']) && !empty($_SESSION['username'])) {
    $response = [
        'loggedIn' => true,
        'username' => $_SESSION['username'],
        'role' => $_SESSION['role'] ?? null // Ambil role dari sesi
    ];
}

echo json_encode($response);
?>