
<?php
require_once __DIR__ . '/../../includes/app_lib.php';
function admin_read_json(string $path, $default=[]) { return oldies_read_json($path, $default); }
function admin_write_json(string $path, $data): bool { return oldies_write_json($path, $data); }
function admin_h($s): string { return oldies_h($s); }
function admin_redirect_self(array $set = [], array $unset = []): void {
  $path = strtok($_SERVER['REQUEST_URI'], '?');
  $q = $_GET;
  foreach ($unset as $k) unset($q[$k]);
  foreach ($set as $k => $v) $q[$k] = $v;
  header('Location: ' . $path . ($q ? ('?' . http_build_query($q)) : ''));
  exit;
}
function admin_handle_upload(string $field, string $targetDir, array $allowedExt=['jpg','jpeg','png','gif','webp','svg','mp3','wav','ogg']): string {
  if (empty($_FILES[$field]) || !is_array($_FILES[$field])) return '';
  $f = $_FILES[$field];
  if (($f['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) return '';
  $ext = strtolower(pathinfo((string)($f['name'] ?? ''), PATHINFO_EXTENSION));
  if ($ext === '' || !in_array($ext, $allowedExt, true)) return '';
  if (!is_dir($targetDir)) @mkdir($targetDir, 0777, true);
  $base = preg_replace('/[^a-zA-Z0-9._-]+/', '-', pathinfo((string)$f['name'], PATHINFO_FILENAME));
  $base = trim($base, '-_.') ?: 'upload';
  $name = $base . '-' . date('Ymd-His') . '.' . $ext;
  $dest = rtrim($targetDir, '/\\') . DIRECTORY_SEPARATOR . $name;
  if (!move_uploaded_file($f['tmp_name'], $dest)) return '';
  return $name;
}
