<?php
/**
 * Utility Class for common operations
 * Contains optimized helper methods
 */
class Utils {
    // Clean and sanitize input data
    public static function sanitizeInput($data) {
        if (is_array($data)) {
            foreach ($data as $key => $value) {
                $data[$key] = self::sanitizeInput($value);
            }
        } else {
            $data = htmlspecialchars(trim($data), ENT_QUOTES, 'UTF-8');
        }
        return $data;
    }

    // Validate and clean email
    public static function validateEmail($email) {
        $email = filter_var(trim($email), FILTER_SANITIZE_EMAIL);
        if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
            return $email;
        }
        return false;
    }

    // Generate pagination with optimization
    public static function generatePagination($currentPage, $totalPages, $url = '?page=') {
        if ($totalPages <= 1) {
            return '';
        }

        $output = '<div class="pagination">';

        // Previous button
        if ($currentPage > 1) {
            $output .= '<a href="' . $url . ($currentPage - 1) . '" class="pagination-item">&laquo; Previous</a>';
        } else {
            $output .= '<span class="pagination-item disabled">&laquo; Previous</span>';
        }

        // First page
        $output .= '<a href="' . $url . '1" class="pagination-item' . ($currentPage == 1 ? ' active' : '') . '">1</a>';

        // Add ellipsis if needed
        if ($currentPage > 3) {
            $output .= '<span class="pagination-ellipsis">...</span>';
        }

        // Pages before current
        for ($i = max(2, $currentPage - 1); $i < $currentPage; $i++) {
            if ($i <= $totalPages) {
                $output .= '<a href="' . $url . $i . '" class="pagination-item">' . $i . '</a>';
            }
        }

        // Current page (if not first or last)
        if ($currentPage != 1 && $currentPage != $totalPages) {
            $output .= '<a href="' . $url . $currentPage . '" class="pagination-item active">' . $currentPage . '</a>';
        }

        // Pages after current
        for ($i = $currentPage + 1; $i < min($totalPages, $currentPage + 2); $i++) {
            $output .= '<a href="' . $url . $i . '" class="pagination-item">' . $i . '</a>';
        }

        // Add ellipsis if needed
        if ($currentPage < $totalPages - 2) {
            $output .= '<span class="pagination-ellipsis">...</span>';
        }

        // Last page (if not first)
        if ($totalPages > 1) {
            $output .= '<a href="' . $url . $totalPages . '" class="pagination-item' . ($currentPage == $totalPages ? ' active' : '') . '">' . $totalPages . '</a>';
        }

        // Next button
        if ($currentPage < $totalPages) {
            $output .= '<a href="' . $url . ($currentPage + 1) . '" class="pagination-item">Next &raquo;</a>';
        } else {
            $output .= '<span class="pagination-item disabled">Next &raquo;</span>';
        }

        $output .= '</div>';

        return $output;
    }

    // Format date for display
    public static function formatDate($timestamp, $format = 'Y-m-d H:i:s') {
        return date($format, strtotime($timestamp));
    }

    // Create slug from string
    public static function createSlug($string) {
        $slug = strtolower(trim(preg_replace('/[^a-zA-Z0-9-]+/', '-', $string), '-'));
        return $slug;
    }

    // Truncate string to specific length
    public static function truncateString($string, $length = 100, $append = '...') {
        if (strlen($string) > $length) {
            $string = substr($string, 0, $length) . $append;
        }
        return $string;
    }

    // Generate CSRF token
    public static function generateCSRFToken() {
        if (!isset($_SESSION['csrf_token']) || empty($_SESSION['csrf_token'])) {
            $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
        }
        return $_SESSION['csrf_token'];
    }

    // Validate CSRF token
    public static function validateCSRFToken($token) {
        if (isset($_SESSION['csrf_token']) && !empty($_SESSION['csrf_token']) && $_SESSION['csrf_token'] === $token) {
            return true;
        }
        return false;
    }

    // Log system activities (with file rotation for optimization)
    public static function logActivity($userId, $action, $details = '') {
        $logDir = __DIR__ . '/../logs';

        // Create logs directory if not exists
        if (!file_exists($logDir)) {
            mkdir($logDir, 0755, true);
        }

        $date = date('Y-m-d');
        $time = date('H:i:s');
        $logFile = $logDir . '/activity_' . date('Ym') . '.log';

        // Implement log rotation (monthly)
        $logEntry = "[{$date} {$time}] User ID: {$userId} | Action: {$action} | Details: {$details}" . PHP_EOL;

        // Append to log file
        file_put_contents($logFile, $logEntry, FILE_APPEND);
    }

    // Convert bytes to human-readable format
    public static function formatBytes($bytes, $precision = 2) {
        $units = array('B', 'KB', 'MB', 'GB', 'TB');

        $bytes = max($bytes, 0);
        $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
        $pow = min($pow, count($units) - 1);

        $bytes /= pow(1024, $pow);

        return round($bytes, $precision) . ' ' . $units[$pow];
    }
}
