<?php

use CodeIgniter\I18n\Time;

if (!function_exists('convert_array_to_utc')) {
  function convert_array_to_utc(array $data): array {
    foreach ($data as $key => $value) {
      if (is_array($value)) {
        $data[$key] = convert_array_to_utc($value);
      } elseif (is_string($value) && is_datetime_string($value)) {
        if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $value)) {
          continue;
        }
        try {
          $data[$key] = Time::parse($value)->setTimezone('UTC')->toDateTimeString();
        } catch (\Exception $e) {
          // skip if not valid
        }
      }
    }
    return $data;
  }
}

if (!function_exists('is_datetime_string')) {
  function is_datetime_string(string $value): bool {
    return preg_match(
      '/^\d{4}-\d{2}-\d{2}(?:[T\s]\d{2}:\d{2}:\d{2}(?:\.\d{1,6})?(?:[\+\-]\d{2}:?\d{2}|Z)?)?$/',
      $value
    ) === 1;
  }
}

if (!function_exists('convert_array_to_utc_iso')) {
  function convert_array_to_utc_iso($data) {
    if (is_array($data)) {
      foreach ($data as $key => $value) {
        if (is_array($value)) {
          $data[$key] = convert_array_to_utc_iso($value);
        } elseif (is_string($value) && is_datetime_string($value)) {
          if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $value)) {
            continue;
          }
          try {
            $data[$key] = Time::parse($value, 'UTC')->format('Y-m-d\TH:i:s.v\Z');
          } catch (\Exception $e) {
            // skip
          }
        }
      }
    } elseif (is_object($data)) {
      foreach ($data as $key => $value) {
        $data->$key = convert_array_to_utc_iso($value);
      }
    }
    return $data;
  }
}
