<?php
/**
 * API untuk mendapatkan data session user
 * Endpoint: /get-session.php
 */

session_start();
require_once 'config/database.php';

// Set CORS headers
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
header('Content-Type: application/json');

// Handle preflight OPTIONS request
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

try {
    // Cek apakah user sudah login
    if (!isset($_SESSION['user_id'])) {
        echo json_encode([
            'success' => false,
            'message' => 'User not logged in'
        ]);
        exit;
    }

    // Ambil data user dari database
    $pdo = getPDOConnection();
    $stmt = $pdo->prepare('
        SELECT 
            u.id,
            u.username,
            u.full_name,
            u.is_admin,
            u.is_active,
            u.position_id,
            CASE 
                WHEN u.is_admin = 1 AND u.position_id IS NULL THEN "Admin"
                ELSE p.name 
            END as position_name,
            p.order_index
        FROM users u
        LEFT JOIN positions p ON u.position_id = p.id
        WHERE u.id = ? AND u.is_active = 1
    ');
    $stmt->execute([$_SESSION['user_id']]);
    $user = $stmt->fetch();

    if (!$user) {
        echo json_encode([
            'success' => false,
            'message' => 'User not found or inactive'
        ]);
        exit;
    }

    // Siapkan data untuk JavaScript
    $userData = [
        'id' => $user['id'],
        'username' => $user['username'],
        'fullName' => $user['full_name'],
        'isAdmin' => (bool)$user['is_admin'],
        'positionId' => $user['position_id'],
        'positionName' => $user['position_name'],
        'positionIndex' => $user['order_index'] ? (int)$user['order_index'] - 1 : -1, // Convert to 0-based index
        'role' => $user['is_admin'] ? 'admin' : 'user'
    ];

    echo json_encode([
        'success' => true,
        'user' => $userData
    ]);

} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Database error: ' . $e->getMessage()
    ]);
}
?>
