<?php

class Security {
    /**
     * Escape HTML output to protect against XSS
     */
    public static function e($data): string {
        return htmlspecialchars((string)($data ?? ''), ENT_QUOTES, 'UTF-8');
    }

    /**
     * Sanitize user input string
     */
    public static function sanitizeString(?string $string): string {
        return trim(filter_var($string ?? '', FILTER_SANITIZE_FULL_SPECIAL_CHARS));
    }

    /**
     * Sanitize email
     */
    public static function sanitizeEmail(?string $email): string {
        return filter_var(trim($email ?? ''), FILTER_SANITIZE_EMAIL);
    }

    /**
     * Hash password securely using BCrypt
     */
    public static function hashPassword(string $password): string {
        return password_hash($password, PASSWORD_BCRYPT);
    }

    /**
     * Verify password hash
     */
    public static function verifyPassword(string $password, string $hash): bool {
        return password_verify($password, $hash);
    }

    /**
     * Generate URL slug from title/name
     * Safe for hosting environments where iconv //TRANSLIT may be unavailable
     */
    public static function slugify(string $text): string {
        // Strip Thai and other non-Latin multi-byte characters first
        $text = preg_replace('/[^\x00-\x7F]+/', '-', $text);

        // Replace non letter or digits by -
        $text = preg_replace('~[^\w\d]+~', '-', $text);

        // Trim leading/trailing dashes
        $text = trim($text, '-');

        // Remove duplicate dashes
        $text = preg_replace('~-+~', '-', $text);

        // Lowercase
        $text = strtolower($text);

        // If empty after stripping (e.g. pure Thai text), generate a safe fallback
        if (empty($text) || $text === '-') {
            return 'product-' . uniqid();
        }

        return $text;
    }
}
