<?php

/**
 * Custom helpers for QR Profile CMS.
 */

if (! function_exists('slugify')) {
    /**
     * Convert any Unicode string to a URL-safe slug.
     * Preserves Unicode letters and numbers.
     */
    function slugify(string $text): string
    {
        $text = mb_strtolower(trim($text), 'UTF-8');
        $text = preg_replace('/[\s\-]+/u', '-', $text);
        $text = preg_replace('/[^\p{L}\p{N}\-]/u', '', $text);
        return trim($text, '-') ?: 'item-' . time();
    }
}

if (! function_exists('app_locale')) {
    /**
     * Return current UI locale from session, falling back to app default.
     */
    function app_locale(): string
    {
        $locale    = session()->get('locale') ?? config('App')->defaultLocale;
        $supported = config('App')->supportedLocales;
        return in_array($locale, $supported, true) ? $locale : 'en';
    }
}

if (! function_exists('human_filesize')) {
    /**
     * Convert bytes to human-readable size.
     */
    function human_filesize(int $bytes, int $decimals = 1): string
    {
        $units = ['B', 'KB', 'MB', 'GB', 'TB'];
        $i = 0;
        while ($bytes >= 1024 && $i < 4) {
            $bytes /= 1024;
            $i++;
        }
        return round($bytes, $decimals) . ' ' . $units[$i];
    }
}

if (! function_exists('upload_url')) {
    /**
     * Return public URL for an uploaded file.
     * Files are served via a dedicated route.
     */
    function upload_url(string $relativePath): string
    {
        return base_url('uploads/' . ltrim($relativePath, '/'));
    }
}

if (! function_exists('profile_photo_url')) {
    /**
     * Return URL for profile photo, with fallback to placeholder.
     */
    function profile_photo_url(?string $path): string
    {
        if ($path && file_exists(FCPATH . 'uploads/' . ltrim($path, '/'))) {
            return base_url('uploads/' . ltrim($path, '/'));
        }
        return base_url('assets/images/avatar_placeholder.svg');
    }
}

if (! function_exists('company_logo_url')) {
    /**
     * Return URL for company logo, with fallback to a generic company placeholder.
     */
    function company_logo_url(?string $path): string
    {
        if ($path && file_exists(FCPATH . 'uploads/' . ltrim($path, '/'))) {
            return base_url('uploads/' . ltrim($path, '/'));
        }
        return base_url('assets/images/logo_placeholder.svg');
    }
}

if (! function_exists('active_nav')) {
    /**
     * Returns 'active' CSS class if the current URI matches the given segment.
     */
    function active_nav(string $segment): string
    {
        return str_contains(current_url(), $segment) ? 'active' : '';
    }
}

if (! function_exists('csrf_field_html')) {
    /**
     * Render a hidden CSRF input field.
     */
    function csrf_field_html(): string
    {
        return '<input type="hidden" name="' . csrf_token() . '" value="' . csrf_hash() . '">';
    }
}

if (! function_exists('log_icon')) {
    /**
     * Bootstrap icon class for a log action.
     */
    function log_icon(string $action): string
    {
        $map = [
            'create'   => 'bi-plus-circle',
            'update'   => 'bi-pencil',
            'delete'   => 'bi-trash',
            'login'    => 'bi-box-arrow-in-right',
            'logout'   => 'bi-box-arrow-right',
            'generate' => 'bi-qr-code',
            'toggle'   => 'bi-toggle-on',
        ];
        return $map[$action] ?? 'bi-activity';
    }
}

if (! function_exists('log_icon_class')) {
    /**
     * Background/text CSS classes for a log action.
     */
    function log_icon_class(string $action): string
    {
        $map = [
            'create'   => 'bg-success-subtle text-success',
            'update'   => 'bg-primary-subtle text-primary',
            'delete'   => 'bg-danger-subtle text-danger',
            'login'    => 'bg-info-subtle text-info',
            'logout'   => 'bg-secondary-subtle text-secondary',
            'generate' => 'bg-warning-subtle text-warning',
        ];
        return $map[$action] ?? 'bg-light text-muted';
    }
}

if (! function_exists('log_badge_class')) {
    /**
     * Badge CSS class for log action.
     */
    function log_badge_class(string $action): string
    {
        $map = [
            'create'   => 'bg-success',
            'update'   => 'bg-primary',
            'delete'   => 'bg-danger',
            'login'    => 'bg-info',
            'logout'   => 'bg-secondary',
            'generate' => 'bg-warning text-dark',
        ];
        return $map[$action] ?? 'bg-light text-dark';
    }
}

if (! function_exists('time_ago')) {
    /**
     * Human-readable "time ago" string.
     */
    function time_ago(?string $datetime): string
    {
        if (empty($datetime)) return '';
        $diff = time() - strtotime($datetime);
        if ($diff < 60)    return $diff . 's ago';
        if ($diff < 3600)  return floor($diff / 60) . 'm ago';
        if ($diff < 86400) return floor($diff / 3600) . 'h ago';
        return floor($diff / 86400) . 'd ago';
    }
}

if (! function_exists('truncate_text')) {
    /**
     * Truncate Unicode-safe string.
     */
    function truncate_text(string $text, int $length = 60, string $suffix = '…'): string
    {
        $text = strip_tags($text);
        if (mb_strlen($text, 'UTF-8') <= $length) {
            return $text;
        }
        return mb_substr($text, 0, $length, 'UTF-8') . $suffix;
    }
}
