<?php

function esc($value) {
    return htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
}

function csrf_token() {
    if (empty($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    }
    return $_SESSION['csrf_token'];
}

function validate_csrf($token) {
    return !empty($_SESSION['csrf_token']) && hash_equals($_SESSION['csrf_token'], $token ?? '');
}

function set_flash($type, $message) {
    $_SESSION['flash'] = ['type' => $type, 'msg' => $message];
}

function get_flash() {
    if (isset($_SESSION['flash'])) {
        $flash = $_SESSION['flash'];
        unset($_SESSION['flash']);
        return $flash;
    }
    return null;
}

function format_date($date) {
    if (!$date) return '-';
    return date('d M Y', strtotime($date));
}

function format_datetime($date) {
    if (!$date) return '-';
    return date('d M Y H:i', strtotime($date));
}

function get_lang() {
    return $_SESSION['lang'] ?? 'id';
}

function set_lang($lang) {
    $_SESSION['lang'] = $lang;
}
