<?php

class SchemaUtils {
  public static function encodeDate($timestamp) {
    $date = DateTime::createFromFormat('U', $timestamp);
    if ($date === false) {
      // If the timestamp is invalid, return a default value.
      $date = DateTime::createFromFormat('U', 0);
    }
    return $date
      ->setTimezone(new \DateTimeZone('UTC'))
      ->format('Y-m-d\TH:i:s\Z');
      // Note that the ATOM constant produces a format that is not allowed by
      // the JSON API parser at notifications service (Go library).
  }

  /**
   * Fix encoding issues by detecting and converting to UTF-8.
   * 
   * @param mixed $value The value to fix encoding for
   * @return mixed The value with proper UTF-8 encoding
   */
  public static function fixEncoding($value) {
    if (!is_string($value)) {
      return $value;
    }
    
    // Check if already valid UTF-8
    if (mb_check_encoding($value, 'UTF-8')) {
      return $value;
    }
    
    // Try to detect encoding and convert
    $detected = mb_detect_encoding($value, ['UTF-8', 'ISO-8859-1', 'ISO-8859-15', 'Windows-1252'], true);
    if ($detected && $detected !== 'UTF-8') {
      return mb_convert_encoding($value, 'UTF-8', $detected);
    }
    
    // Fallback: assume ISO-8859-1 and convert
    return mb_convert_encoding($value, 'UTF-8', 'ISO-8859-1');
  }
}
