<?php
// admin/subscriber_upload_lib.php
// Stage 16: one upload handler for subscriber identity attachments.

if (!function_exists('subscriber_identity_upload')) {
  function subscriber_identity_upload(string $key, string $prefix): ?string {
    if (empty($_FILES[$key]) || ($_FILES[$key]['error'] ?? UPLOAD_ERR_NO_FILE) === UPLOAD_ERR_NO_FILE) return null;
    if (($_FILES[$key]['error'] ?? 0) !== UPLOAD_ERR_OK) return null;

    $tmp = (string)($_FILES[$key]['tmp_name'] ?? '');
    $name = (string)($_FILES[$key]['name'] ?? '');
    if ($tmp === '' || !is_uploaded_file($tmp)) return null;

    $size = (int)($_FILES[$key]['size'] ?? 0);
    if ($size <= 0 || $size > 10 * 1024 * 1024) return null;

    $ext = strtolower(pathinfo($name, PATHINFO_EXTENSION));
    if (!in_array($ext, ['jpg','jpeg','png','pdf','webp'], true)) return null;

    if (function_exists('finfo_open')) {
      $fi = @finfo_open(FILEINFO_MIME_TYPE);
      if ($fi) {
        $mime = (string)@finfo_file($fi, $tmp);
        @finfo_close($fi);
        if ($mime !== '' && !in_array($mime, ['image/jpeg','image/png','application/pdf','image/webp'], true)) return null;
      }
    }

    $uploadDir = __DIR__ . '/assets/id_cards';
    if (!is_dir($uploadDir)) @mkdir($uploadDir, 0775, true);

    try { $rand = bin2hex(random_bytes(4)); }
    catch (Throwable $e) { $rand = substr(md5(uniqid('', true)), 0, 8); }

    $safePrefix = preg_replace('/[^a-z0-9_-]+/i', '_', $prefix) ?: 'file';
    $file = $safePrefix . '_' . date('Ymd_His') . '_' . $rand . '.' . $ext;
    $dest = rtrim($uploadDir, '/\\') . '/' . $file;

    if (@move_uploaded_file($tmp, $dest)) return 'assets/id_cards/' . $file;
    return null;
  }
}
