<?php
namespace App\Helpers;

/**
 * Global Helper Functions
 */
class Helper
{
    public static function money(float $amount, string $currency = APP_CURRENCY_SYMBOL): string
    {
        return $currency . ' ' . number_format($amount, 0, '.', ',');
    }

    public static function date(string $date, string $format = 'd/m/Y'): string
    {
        if (!$date) return '-';
        return date($format, strtotime($date));
    }

    public static function datetime(string $datetime): string
    {
        if (!$datetime) return '-';
        return date('d/m/Y H:i', strtotime($datetime));
    }

    public static function slug(string $str): string
    {
        $str = strtolower(trim($str));
        $str = preg_replace('/[^a-z0-9-]/', '-', $str);
        return preg_replace('/-+/', '-', $str);
    }

    public static function generateCode(string $prefix, int $length = 6): string
    {
        return $prefix . '-' . str_pad(random_int(1, 999999), $length, '0', STR_PAD_LEFT);
    }

    public static function generateRef(string $prefix = 'REF'): string
    {
        return $prefix . '-' . date('Y') . '-' . strtoupper(substr(uniqid(), -6));
    }

    public static function sanitize(string $input): string
    {
        return htmlspecialchars(strip_tags(trim($input)), ENT_QUOTES, 'UTF-8');
    }

    public static function e(string|null $str): string
    {
        return htmlspecialchars((string)$str, ENT_QUOTES, 'UTF-8');
    }

    public static function uploadFile(array $file, string $destination, array $allowedTypes = []): string|false
    {
        if ($file['error'] !== UPLOAD_ERR_OK) return false;
        if ($file['size'] > MAX_FILE_SIZE) return false;
        if ($allowedTypes && !in_array($file['type'], $allowedTypes)) return false;

        $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
        $filename = uniqid() . '_' . time() . '.' . $ext;
        $destPath = UPLOADS_PATH . '/' . $destination;
        if (!is_dir($destPath)) mkdir($destPath, 0755, true);
        $fullPath = $destPath . '/' . $filename;
        if (move_uploaded_file($file['tmp_name'], $fullPath)) {
            return $destination . '/' . $filename;
        }
        return false;
    }

    public static function assetUrl(string $path): string
    {
        return APP_URL . '/assets/' . ltrim($path, '/');
    }

    public static function uploadUrl(string $path): string
    {
        return APP_URL . '/uploads/' . ltrim($path, '/');
    }

    public static function statusBadge(string $status): string
    {
        $badges = [
            'active'      => 'success',
            'inactive'    => 'secondary',
            'pending'     => 'warning',
            'approved'    => 'success',
            'rejected'    => 'danger',
            'cancelled'   => 'secondary',
            'completed'   => 'success',
            'in_progress' => 'info',
            'open'        => 'primary',
            'paid'        => 'success',
            'unpaid'      => 'danger',
            'partial'     => 'warning',
            'overdue'     => 'danger',
            'occupied'    => 'danger',
            'available'   => 'success',
            'maintenance' => 'warning',
            'expired'     => 'secondary',
            'terminated'  => 'danger',
            'emergency'   => 'danger',
            'high'        => 'warning',
            'medium'      => 'info',
            'low'         => 'secondary',
            'sent'        => 'success',
            'failed'      => 'danger',
        ];
        $color = $badges[$status] ?? 'secondary';
        $label = ucfirst(str_replace('_', ' ', $status));
        return "<span class='badge bg-{$color}'>{$label}</span>";
    }

    public static function paginator(array $pagination, string $baseUrl = ''): string
    {
        if ($pagination['totalPages'] <= 1) return '';
        $html = '<nav><ul class="pagination justify-content-center">';
        $page = $pagination['page'];
        $total = $pagination['totalPages'];
        $html .= '<li class="page-item ' . ($page <= 1 ? 'disabled' : '') . '">';
        $html .= '<a class="page-link" href="' . $baseUrl . '?page=' . ($page - 1) . '">Previous</a></li>';
        for ($i = max(1, $page - 2); $i <= min($total, $page + 2); $i++) {
            $html .= '<li class="page-item ' . ($i === $page ? 'active' : '') . '">';
            $html .= '<a class="page-link" href="' . $baseUrl . '?page=' . $i . '">' . $i . '</a></li>';
        }
        $html .= '<li class="page-item ' . ($page >= $total ? 'disabled' : '') . '">';
        $html .= '<a class="page-link" href="' . $baseUrl . '?page=' . ($page + 1) . '">Next</a></li>';
        $html .= '</ul></nav>';
        return $html;
    }

    public static function session(string $key, mixed $default = null): mixed
    {
        return $_SESSION[$key] ?? $default;
    }

    public static function setFlash(string $type, string $message): void
    {
        $_SESSION['flash'] = compact('type', 'message');
    }

    public static function getFlash(): array|null
    {
        if (isset($_SESSION['flash'])) {
            $flash = $_SESSION['flash'];
            unset($_SESSION['flash']);
            return $flash;
        }
        return null;
    }

    public static function csrf(): string
    {
        if (empty($_SESSION[CSRF_TOKEN_NAME])) {
            $_SESSION[CSRF_TOKEN_NAME] = bin2hex(random_bytes(32));
        }
        $token = $_SESSION[CSRF_TOKEN_NAME];
        return '<input type="hidden" name="' . CSRF_TOKEN_NAME . '" value="' . $token . '">';
    }

    public static function timeAgo(string $datetime): string
    {
        $time = time() - strtotime($datetime);
        if ($time < 60) return 'just now';
        if ($time < 3600) return floor($time / 60) . ' minutes ago';
        if ($time < 86400) return floor($time / 3600) . ' hours ago';
        if ($time < 2592000) return floor($time / 86400) . ' days ago';
        return date('d M Y', strtotime($datetime));
    }

    public static function qrCode(string $data): string
    {
        return 'https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=' . urlencode($data);
    }

    public static function phoneFormat(string $phone): string
    {
        $phone = preg_replace('/\D/', '', $phone);
        if (str_starts_with($phone, '0')) $phone = '255' . substr($phone, 1);
        if (!str_starts_with($phone, '+')) $phone = '+' . $phone;
        return $phone;
    }
}
