<?php
/**
 * Authentication & Session Guard
 * Gym Booking System (FITZONE)
 */

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

/**
 * Generate a full URL using BASE_URL
 */
function url(string $path): string {
    return BASE_URL . '/' . ltrim($path, '/');
}

/**
 * Generate or retrieve CSRF token
 */
function csrfToken(): string {
    if (empty($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    }
    return $_SESSION['csrf_token'];
}

/**
 * Validate CSRF token from POST
 */
function validateCsrf(): bool {
    return isset($_POST['csrf_token']) && hash_equals($_SESSION['csrf_token'] ?? '', $_POST['csrf_token']);
}

/**
 * Check if user is logged in
 */
function isLoggedIn(): bool {
    return isset($_SESSION['user_id']);
}

/**
 * Get current user data from session
 */
function getCurrentUser(): ?array {
    if (!isLoggedIn()) return null;
    return [
        'id'   => $_SESSION['user_id'],
        'nama' => $_SESSION['nama'] ?? '',
        'role' => $_SESSION['role'] ?? '',
        'email'=> $_SESSION['email'] ?? '',
    ];
}

/**
 * Require login — redirect to login page if not authenticated
 */
function requireLogin(): void {
    if (!isLoggedIn()) {
        $_SESSION['flash'] = ['type' => 'error', 'message' => 'Silakan login terlebih dahulu.'];
        header('Location: ' . url('/login_member.php'));
        exit;
    }
}

/**
 * Require admin role
 */
function requireAdmin(): void {
    requireLogin();
    if ($_SESSION['role'] !== 'admin') {
        $_SESSION['flash'] = ['type' => 'error', 'message' => 'Akses ditolak. Halaman khusus admin.'];
        header('Location: ' . url('/login_admin.php'));
        exit;
    }
}

/**
 * Require member role
 */
function requireMember(): void {
    requireLogin();
    if ($_SESSION['role'] !== 'member') {
        $_SESSION['flash'] = ['type' => 'error', 'message' => 'Akses ditolak. Halaman khusus member.'];
        header('Location: ' . url('/login_member.php'));
        exit;
    }
}

/**
 * Set flash message
 */
function setFlash(string $type, string $message): void {
    $_SESSION['flash'] = ['type' => $type, 'message' => $message];
}

/**
 * Get and clear flash message
 */
function getFlash(): ?array {
    if (isset($_SESSION['flash'])) {
        $flash = $_SESSION['flash'];
        unset($_SESSION['flash']);
        return $flash;
    }
    return null;
}

/**
 * Get cart count for current user
 */
function getCartCount(PDO $pdo): int {
    if (!isLoggedIn()) return 0;
    $stmt = $pdo->prepare('SELECT COUNT(*) FROM keranjang WHERE user_id = ?');
    $stmt->execute([$_SESSION['user_id']]);
    return (int)$stmt->fetchColumn();
}
