<?php
/**
 * includes/functions.php — Shared utility functions
 */

// ── Output helpers ────────────────────────────────────────────────────────────

/** Safely echo a value, HTML-encoded */
function e(string $value): string {
    return htmlspecialchars($value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}

/** Build a URL relative to the portal root */
function base_url(string $path = ''): string {
    $script = $_SERVER['SCRIPT_NAME'] ?? '';
    // Walk up to find the portal root (the ces-portal directory)
    $root = str_repeat('../', substr_count($script, '/') - 2);
    return $root . ltrim($path, '/');
}

// ── Flash messages ────────────────────────────────────────────────────────────

function set_flash(string $type, string $message): void {
    start_session();
    $_SESSION['flash'][$type] = $message;
}

function get_flash(): array {
    start_session();
    $flash = $_SESSION['flash'] ?? [];
    unset($_SESSION['flash']);
    return $flash;
}

/**
 * Render flash messages as Bootstrap alerts.
 * Types: success, error, warning, info
 */
function render_flash(): void {
    $map = [
        'success' => 'alert-success',
        'error'   => 'alert-danger',
        'warning' => 'alert-warning',
        'info'    => 'alert-info',
    ];
    foreach (get_flash() as $type => $message) {
        $cls = $map[$type] ?? 'alert-info';
        echo '<div class="alert ' . $cls . ' alert-dismissible fade show" role="alert">';
        echo '<span>' . e($message) . '</span>';
        echo '<button type="button" class="close" data-dismiss="alert">'
           . '<span>&times;</span></button>';
        echo '</div>';
    }
}

// ── Redirect ──────────────────────────────────────────────────────────────────

function redirect(string $url): void {
    header('Location: ' . $url);
    exit;
}

function redirect_back(string $fallback = ''): void {
    $ref = $_SERVER['HTTP_REFERER'] ?? $fallback;
    redirect($ref ?: base_url('pages/dashboard.php'));
}

// ── Date formatting ───────────────────────────────────────────────────────────

function fmt_date(?string $dt, string $format = 'M d, Y'): string {
    if (!$dt) return '—';
    return date($format, strtotime($dt));
}

function fmt_datetime(?string $dt): string {
    return fmt_date($dt, 'M d, Y g:i A');
}

// ── Pagination ────────────────────────────────────────────────────────────────

function paginate(int $total, int $per_page, int $current_page): array {
    $total_pages = (int) ceil($total / $per_page);
    $offset      = ($current_page - 1) * $per_page;
    return [
        'total'       => $total,
        'per_page'    => $per_page,
        'current'     => $current_page,
        'total_pages' => $total_pages,
        'offset'      => $offset,
        'has_prev'    => $current_page > 1,
        'has_next'    => $current_page < $total_pages,
    ];
}

// ── Misc ──────────────────────────────────────────────────────────────────────

function active_if(bool $condition): string {
    return $condition ? 'active' : '';
}

function badge_active(int $active): string {
    return $active
        ? '<span class="badge badge-success">Active</span>'
        : '<span class="badge badge-danger">Inactive</span>';
}

function badge_passed(int $passed): string {
    return $passed
        ? '<span class="badge badge-success">Passed</span>'
        : '<span class="badge badge-warning">In Progress</span>';
}

function get_current_page(): int {
    return max(1, (int) ($_GET['page'] ?? 1));
}

function get_search(): string {
    return trim($_GET['q'] ?? '');
}
