<?php
/**
 * BOAFO Helper Functions
 * Global utility functions available throughout the application
 */

/**
 * Redirect to URL
 */
function redirect(string $url): never {
    header("Location: {$url}");
    exit;
}

/**
 * Generate URL
 */
function url(string $path = ''): string {
    return APP_URL . '/' . ltrim($path, '/');
}

/**
 * Sanitize output for HTML context
 */
function e(mixed $value): string {
    return htmlspecialchars((string) $value, ENT_QUOTES, 'UTF-8');
}

/**
 * Get flash message
 */
function flash(string $key): mixed {
    $val = $_SESSION['flash'][$key] ?? null;
    unset($_SESSION['flash'][$key]);
    return $val;
}

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

/**
 * CSRF field HTML
 */
function csrf_field(): string {
    return CSRF::field();
}

/**
 * Format date
 */
function formatDate(string $date, string $format = 'M d, Y'): string {
    if (empty($date) || $date === '0000-00-00') return 'N/A';
    return date($format, strtotime($date));
}

/**
 * Format date with time
 */
function formatDateTime(string $date, string $format = 'M d, Y g:i A'): string {
    if (empty($date)) return 'N/A';
    return date($format, strtotime($date));
}

/**
 * Time ago
 */
function timeAgo(string $datetime): string {
    $time = strtotime($datetime);
    $diff = time() - $time;

    if ($diff < 60)         return 'just now';
    if ($diff < 3600)       return floor($diff/60) . 'm ago';
    if ($diff < 86400)      return floor($diff/3600) . 'h ago';
    if ($diff < 604800)     return floor($diff/86400) . 'd ago';
    return date('M d, Y', $time);
}

/**
 * Format currency
 */
function formatMoney(float $amount, string $currency = 'GHS'): string {
    return $currency . ' ' . number_format($amount, 2);
}

/**
 * Truncate text
 */
function truncate(string $text, int $length = 150, string $ellipsis = '...'): string {
    if (strlen($text) <= $length) return $text;
    return substr($text, 0, $length) . $ellipsis;
}

/**
 * Generate slug
 */
function slugify(string $text): string {
    $text = strtolower($text);
    $text = preg_replace('/[^a-z0-9\s-]/', '', $text);
    $text = preg_replace('/[\s-]+/', '-', trim($text));
    return $text;
}

/**
 * Generate UUID v4
 */
function generateUUID(): string {
    $data = random_bytes(16);
    $data[6] = chr(ord($data[6]) & 0x0f | 0x40);
    $data[8] = chr(ord($data[8]) & 0x3f | 0x80);
    return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
}

/**
 * WASSCE grade to point
 */
function gradeToPoint(string $grade): int {
    return WASSCE_GRADES[$grade] ?? 9;
}

/**
 * Calculate WASSCE aggregate (sum of best 6)
 */
function calculateAggregate(array $grades): int {
    $points = array_map('gradeToPoint', $grades);
    sort($points);
    return array_sum(array_slice($points, 0, 6));
}

/**
 * Get avatar URL
 */
function avatarUrl(?string $avatar, string $name = ''): string {
    if ($avatar && file_exists(UPLOAD_PATH . '/avatars/' . $avatar)) {
        return UPLOAD_URL . '/avatars/' . $avatar;
    }
    // DiceBear initials fallback
    $initials = urlencode($name);
    return "https://api.dicebear.com/7.x/initials/svg?seed={$initials}&backgroundColor=1a2940";
}

/**
 * Get university logo URL
 */
function logoUrl(?string $logo): string {
    if ($logo && file_exists(UPLOAD_PATH . '/logos/' . $logo)) {
        return UPLOAD_URL . '/logos/' . $logo;
    }
    return APP_URL . '/assets/images/uni-placeholder.png';
}

/**
 * Pagination HTML
 */
function paginationLinks(array $pagination, string $baseUrl): string {
    if ($pagination['total_pages'] <= 1) return '';

    $html = '<nav aria-label="Page navigation"><ul class="pagination justify-content-center">';

    if ($pagination['has_prev']) {
        $html .= '<li class="page-item"><a class="page-link" href="' . $baseUrl . '?page=' . ($pagination['current_page'] - 1) . '">‹ Prev</a></li>';
    }

    for ($i = max(1, $pagination['current_page'] - 2); $i <= min($pagination['total_pages'], $pagination['current_page'] + 2); $i++) {
        $active = $i === $pagination['current_page'] ? 'active' : '';
        $html .= "<li class=\"page-item {$active}\"><a class=\"page-link\" href=\"{$baseUrl}?page={$i}\">{$i}</a></li>";
    }

    if ($pagination['has_next']) {
        $html .= '<li class="page-item"><a class="page-link" href="' . $baseUrl . '?page=' . ($pagination['current_page'] + 1) . '">Next ›</a></li>';
    }

    $html .= '</ul></nav>';
    return $html;
}

/**
 * Badge HTML for status
 */
function statusBadge(string $status): string {
    // All mapped to Blue (primary) or Orange (accent) palette only
    $classes = [
        'active'    => 'bg-primary text-white',
        'inactive'  => 'bg-info text-white',
        'pending'   => 'bg-warning text-dark',
        'suspended' => 'bg-danger text-white',
        'open'      => 'bg-primary text-white',
        'closed'    => 'bg-danger text-white',
        'upcoming'  => 'bg-info text-white',
        'accepted'  => 'bg-primary text-white',
        'declined'  => 'bg-danger text-white',
        'completed' => 'bg-primary text-white',
        'cancelled' => 'bg-warning text-dark',
        'confirmed' => 'bg-primary text-white',
        'verified'  => 'bg-primary text-white',
        'unverified'=> 'bg-warning text-dark',
    ];
    $class = $classes[$status] ?? 'bg-info text-white';
    return "<span class=\"badge {$class}\">" . ucfirst($status) . "</span>";
}

/**
 * Star rating HTML
 */
function starRating(float $rating, int $max = 5): string {
    $html = '';
    for ($i = 1; $i <= $max; $i++) {
        if ($i <= $rating) {
            $html .= '<i class="fas fa-star text-accent" style="color:var(--accent);"></i>';
        } elseif ($i - 0.5 <= $rating) {
            $html .= '<i class="fas fa-star-half-alt text-accent" style="color:var(--accent);"></i>';
        } else {
            $html .= '<i class="far fa-star" style="color:var(--border);"></i>';
        }
    }
    return $html;
}

/**
 * Handle file upload
 */
function uploadFile(array $file, string $folder, array $allowedTypes = []): string|false {
    if ($file['error'] !== UPLOAD_ERR_OK) return false;
    if ($file['size'] > MAX_FILE_SIZE) return false;

    $mime = mime_content_type($file['tmp_name']);
    $allowed = $allowedTypes ?: ALLOWED_IMAGE_TYPES;
    if (!in_array($mime, $allowed)) return false;

    $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
    $filename = uniqid('', true) . '.' . strtolower($ext);
    $dir = UPLOAD_PATH . '/' . $folder;

    if (!is_dir($dir)) mkdir($dir, 0755, true);

    if (move_uploaded_file($file['tmp_name'], $dir . '/' . $filename)) {
        return $filename;
    }
    return false;
}

/**
 * Probability color
 */
function probabilityColor(float $score): string {
    // Blue for high, Orange-light for moderate, Orange-dark for low
    if ($score >= 70) return 'primary';  // Blue
    if ($score >= 40) return 'warning';  // Orange-light (overridden to orange)
    return 'danger';                     // Orange-dark (overridden to dark orange)
}

/**
 * Probability label
 */
function probabilityLabel(float $score): string {
    if ($score >= 70) return 'High Chance';
    if ($score >= 40) return 'Moderate Chance';
    return 'Low Chance';
}

/**
 * Check if the current route path is active
 */
function is_active_route(string $routePath): bool {
    $uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
    $basePath = '/BOAFO/public';
    if (str_starts_with($uri, $basePath)) {
        $uri = substr($uri, strlen($basePath));
    }
    $uri = '/' . trim($uri, '/');
    if ($uri === '/') {
        return $routePath === '/';
    }
    if ($routePath === '/') {
        return $uri === '/';
    }
    return str_starts_with($uri, $routePath);
}

