<?php
/**
 * Helper Functions - WeaverSM
 */

// IMPORTANT: Using hardcoded '$' to avoid constant corruption bug
function formatCurrency($amount) {
    return '$' . number_format((float)$amount, 2);
}

function formatDate($date, $format = 'M d, Y') {
    return date($format, strtotime($date));
}

function formatDateTime($date) {
    return date('M d, Y H:i', strtotime($date));
}

function redirect($url) {
    header("Location: $url");
    exit;
}

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

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

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

function isAdmin() {
    return isset($_SESSION['role']) && $_SESSION['role'] === 'admin';
}

function isAssistant() {
    return isset($_SESSION['role']) && $_SESSION['role'] === 'assistant';
}

function getCurrentUserId() {
    return $_SESSION['user_id'] ?? null;
}

function requireLogin() {
    if (!isLoggedIn()) {
        redirect(SITE_URL . '/login.php');
    }
}

function requireAdmin() {
    if (!isAdmin() && !isAssistant()) {
        redirect(SITE_URL . '/user/dashboard.php');
    }
}

function truncateText($text, $length = 100) {
    if (strlen($text) <= $length) return $text;
    return substr($text, 0, $length) . '...';
}

function generateReference($prefix = 'TXN') {
    return $prefix . strtoupper(uniqid()) . rand(100, 999);
}

function paginate($total, $page, $perPage) {
    $totalPages = max(1, ceil($total / $perPage));
    return [
        'current_page' => $page,
        'total_pages' => $totalPages,
        'total_items' => $total,
        'per_page' => $perPage,
        'has_prev' => $page > 1,
        'has_next' => $page < $totalPages
    ];
}
