<?php
// includes/auth.php — helper session & autentikasi

session_start();

function isLoggedIn(): bool {
    return isset($_SESSION['user_id']);
}

function requireLogin(): void {
    if (!isLoggedIn()) {
        header('Location: ' . BASE_URL . 'index.php');
        exit;
    }
}

function requireAdmin(): void {
    requireLogin();
    if ($_SESSION['role'] !== 'admin') {
        header('Location: ' . BASE_URL . 'kasir/dashboard.php');
        exit;
    }
}

function requireKasir(): void {
    requireLogin();
    // kasir maupun admin boleh akses halaman kasir
}

function currentUser(): array {
    return [
        'id'   => $_SESSION['user_id']   ?? null,
        'nama' => $_SESSION['nama']       ?? '',
        'role' => $_SESSION['role']       ?? '',
    ];
}

function formatRp(float $angka): string {
    return 'Rp ' . number_format($angka, 0, ',', '.');
}

function generateNoTransaksi(string $metode = 'tunai'): string {
    $prefix = $metode === 'qris' ? 'TRQ' : 'TRT';
    return $prefix . '-' . date('Ymd') . '-' . strtoupper(substr(uniqid(), -5));
}
