<?php
require_once __DIR__ . '/../config.php';

function sanitize($data) {
    return htmlspecialchars(strip_tags(trim($data)), ENT_QUOTES, 'UTF-8');
}

function e($text) {
    echo htmlspecialchars($text, ENT_QUOTES, 'UTF-8');
}

function is_active($page) {
    global $current_page;
    return basename($current_page) === $page ? 'active' : '';
}

function asset($path) {
    return 'assets/' . ltrim($path, '/');
}

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

function verify_csrf($token) {
    return isset($_SESSION['csrf_token']) && hash_equals($_SESSION['csrf_token'], $token);
}

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

function time_ago($timestamp) {
    $time = strtotime($timestamp);
    $diff = time() - $time;
    if ($diff < 60) return 'Just now';
    if ($diff < 3600) return floor($diff / 60) . ' min ago';
    if ($diff < 86400) return floor($diff / 3600) . ' hours ago';
    if ($diff < 604800) return floor($diff / 86400) . ' days ago';
    return date('j M Y', $time);
}

function truncate($text, $chars = 120) {
    if (strlen($text) <= $chars) return $text;
    return substr($text, 0, $chars) . '...';
}

function is_admin_logged_in() {
    return isset($_SESSION['admin_id']) && !empty($_SESSION['admin_id']);
}

function require_admin() {
    if (!is_admin_logged_in()) {
        redirect('login.php');
    }
}
