<?php
function smurf_read_json(string $path, $default) {
  if (!file_exists($path)) return $default;
  $raw = file_get_contents($path);
  $data = json_decode($raw, true);
  return is_null($data) ? $default : $data;
}

function smurf_write_json(string $path, $data): bool {
  $json = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
  if ($json === false) return false;
  if (file_exists($path)) @copy($path, $path . ".bak");
  return file_put_contents($path, $json . "
") !== false;
}

function smurf_parse_blocks(string $path): array {
  if (!file_exists($path)) return [];
  $raw = trim((string)file_get_contents($path));
  if ($raw === '') return [];
  $chunks = preg_split("/
---\s*
/", $raw);
  $out = [];
  foreach ($chunks as $chunk) {
    $chunk = trim($chunk);
    if ($chunk === '') continue;
    $lines = preg_split("/\R/", $chunk);
    $entry = ['_raw' => $chunk];
    foreach ($lines as $line) {
      if (strpos($line, ':') === false) continue;
      [$k,$v] = explode(':', $line, 2);
      $k = trim($k);
      $v = trim($v);
      if ($k !== '') $entry[$k] = $v;
    }
    $out[] = $entry;
  }
  return array_reverse($out);
}

function smurf_delete_block(string $path, int $index_from_newest): bool {
  if (!file_exists($path)) return false;
  $raw = trim((string)file_get_contents($path));
  if ($raw === '') return false;
  $chunks = preg_split("/
---\s*
/", $raw);
  $chunks = array_values(array_filter(array_map('trim',$chunks), fn($c)=>$c!==''));
  $count = count($chunks);
  if ($count === 0) return false;
  $index_from_oldest = ($count - 1) - $index_from_newest;
  if ($index_from_oldest < 0 || $index_from_oldest >= $count) return false;
  array_splice($chunks, $index_from_oldest, 1);
  $newRaw = $chunks ? implode("
---
", $chunks) . "
---
" : "";
  if (file_exists($path)) @copy($path, $path . ".bak");
  return file_put_contents($path, $newRaw) !== false;
}

function smurf_clear_file(string $path): bool {
  if (file_exists($path)) @copy($path, $path . ".bak");
  return file_put_contents($path, "") !== false;
}

function smurf_h(string $s): string { return htmlspecialchars($s, ENT_QUOTES, 'UTF-8'); }

function smurf_public_asset_url(string $path, string $fallbackDir = ''): string {
  $path = trim($path);
  if ($path === '') return '';
  if (preg_match('#^(https?:)?//#i', $path) || str_starts_with($path, 'data:')) return $path;
  $path = str_replace('\\', '/', $path);
  $path = ltrim($path, '/');
  if ($fallbackDir !== '' && strpos($path, '/') === false) {
    $fallbackDir = trim(str_replace('\\', '/', $fallbackDir), '/');
    if ($fallbackDir !== '') $path = $fallbackDir . '/' . $path;
  }
  return '/' . $path;
}

function smurf_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; }
  $qs = http_build_query($q);
  header('Location: ' . $path . ($qs ? ('?' . $qs) : ''));
  exit;
}

function smurf_update_block(string $path, int $index_from_newest, string $newRaw): bool {
  if (!file_exists($path)) return false;
  $raw = (string)file_get_contents($path);
  $chunks = preg_split("/
---\s*
/", trim($raw));
  $chunks = array_values(array_filter(array_map('trim', $chunks), fn($c) => $c !== ''));
  if (empty($chunks)) return false;
  $fileIndex = (count($chunks) - 1) - $index_from_newest;
  if ($fileIndex < 0 || $fileIndex >= count($chunks)) return false;
  $chunks[$fileIndex] = trim($newRaw);
  $out = implode("
---
", $chunks);
  $out = trim($out) . "
";
  file_put_contents($path, $out);
  return true;
}

function smurf_load_settings(string $path): array {
  $defaults = ['comments_enabled' => true];
  $s = smurf_read_json($path, []);
  if (!is_array($s)) $s = [];
  return array_merge($defaults, $s);
}

function smurf_save_settings(string $path, array $settings): void { smurf_write_json($path, $settings); }

function smurf_upload_error_message(int $error): string {
  return match ($error) {
    UPLOAD_ERR_INI_SIZE, UPLOAD_ERR_FORM_SIZE => 'The uploaded file is too large.',
    UPLOAD_ERR_PARTIAL => 'The uploaded file did not finish uploading.',
    UPLOAD_ERR_NO_TMP_DIR => 'The server is missing a temporary upload folder.',
    UPLOAD_ERR_CANT_WRITE => 'The server could not save the uploaded file.',
    UPLOAD_ERR_EXTENSION => 'The upload was blocked by a PHP extension.',
    default => 'The upload could not be processed.',
  };
}

function smurf_handle_upload(string $field, string $targetDir, array $allowedExt = ['jpg','jpeg','png','gif','webp'], int $maxBytes = 8388608): string {
  if (empty($_FILES[$field]) || !is_array($_FILES[$field])) return '';
  $f = $_FILES[$field];
  $error = (int)($f['error'] ?? UPLOAD_ERR_NO_FILE);
  if ($error === UPLOAD_ERR_NO_FILE) return '';
  if ($error !== UPLOAD_ERR_OK) {
    $GLOBALS['SMURF_UPLOAD_ERROR'] = smurf_upload_error_message($error);
    return '';
  }
  $orig = (string)($f['name'] ?? '');
  $ext = strtolower(pathinfo($orig, PATHINFO_EXTENSION));
  if ($ext === '' || !in_array($ext, $allowedExt, true)) {
    $GLOBALS['SMURF_UPLOAD_ERROR'] = 'That file type is not allowed.';
    return '';
  }
  $size = (int)($f['size'] ?? 0);
  if ($size <= 0 || $size > $maxBytes) {
    $GLOBALS['SMURF_UPLOAD_ERROR'] = 'The file is empty or too large.';
    return '';
  }
  $tmp = (string)($f['tmp_name'] ?? '');
  if ($tmp === '' || !is_uploaded_file($tmp)) {
    $GLOBALS['SMURF_UPLOAD_ERROR'] = 'The uploaded file could not be verified.';
    return '';
  }
  $finfo = function_exists('finfo_open') ? finfo_open(FILEINFO_MIME_TYPE) : false;
  $mime = $finfo ? (string)finfo_file($finfo, $tmp) : '';
  if ($finfo) finfo_close($finfo);
  $allowedMime = [
    'jpg' => ['image/jpeg'],
    'jpeg' => ['image/jpeg'],
    'png' => ['image/png'],
    'gif' => ['image/gif'],
    'webp' => ['image/webp'],
  ];
  if ($mime !== '' && isset($allowedMime[$ext]) && !in_array($mime, $allowedMime[$ext], true)) {
    $GLOBALS['SMURF_UPLOAD_ERROR'] = 'The uploaded file did not look like a valid image.';
    return '';
  }
  if (!is_dir($targetDir)) @mkdir($targetDir, 0777, true);
  $safe = preg_replace('/[^a-zA-Z0-9._-]+/', '-', pathinfo($orig, PATHINFO_FILENAME));
  $safe = trim($safe, '-_.') ?: 'upload';
  $name = $safe . '-' . date('Ymd-His') . '.' . $ext;
  $dest = rtrim($targetDir, '/\\') . DIRECTORY_SEPARATOR . $name;
  if (!move_uploaded_file($tmp, $dest)) {
    $GLOBALS['SMURF_UPLOAD_ERROR'] = 'The uploaded file could not be moved into place.';
    return '';
  }
  @chmod($dest, 0644);
  return $name;
}

function smurf_q(string $key, string $default = ''): string {
  return trim((string)($_GET[$key] ?? $default));
}

function smurf_match_text(string $haystack, string $needle): bool {
  if ($needle === '') return true;
  return stripos($haystack, $needle) !== false;
}

function smurf_admin_denied(string $msg = 'You do not have permission to use that tool right now.'): void {
  if (!headers_sent()) {
    $path = '/admin/index.php';
    header('Location: ' . $path . '?denied=' . urlencode($msg));
  }
  exit;
}
