<?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;
  // simple backup
  if (file_exists($path)) @copy($path, $path . ".bak");
  return file_put_contents($path, $json . "\n") !== false;
}

/**
 * Parse blocks like:
 *   Key: value
 *   Key2: value
 *   ---
 */
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("/\n---\s*\n/", $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;
  }
  // newest first (because we append to file)
  return array_reverse($out);
}

function smurf_delete_block(string $path, int $index_from_newest): bool {
  // We parse newest-first, but file is oldest-first, so we need to map index.
  if (!file_exists($path)) return false;
  $raw = trim((string)file_get_contents($path));
  if ($raw === '') return false;

  $chunks = preg_split("/\n---\s*\n/", $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("\n---\n", $chunks) . "\n---\n" : "";
  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');
}


/**
 * Post/Redirect/Get helper:
 * Redirects back to the current page (same path) with merged query params.
 */
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 {
  // Update a single block (index counted from newest, same as smurf_parse_blocks)
  if (!file_exists($path)) return false;
  $raw = (string)file_get_contents($path);
  $chunks = preg_split("/\n---\s*\n/", trim($raw));
  $chunks = array_values(array_filter(array_map('trim', $chunks), fn($c) => $c !== ''));
  if (empty($chunks)) return false;

  // chunks are oldest-first in file; index_from_newest refers to reversed order
  $fileIndex = (count($chunks) - 1) - $index_from_newest;
  if ($fileIndex < 0 || $fileIndex >= count($chunks)) return false;

  $chunks[$fileIndex] = trim($newRaw);
  $out = implode("\n---\n", $chunks);
  $out = trim($out) . "\n";
  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_handle_upload(string $field, string $targetDir, array $allowedExt = ['jpg','jpeg','png','gif','webp']): string {
  if (empty($_FILES[$field]) || !is_array($_FILES[$field])) return '';
  $f = $_FILES[$field];
  if (($f['error'] ?? UPLOAD_ERR_NO_FILE) !== UPLOAD_ERR_OK) return '';
  $orig = (string)($f['name'] ?? '');
  $ext = strtolower(pathinfo($orig, PATHINFO_EXTENSION));
  if ($ext === '' || !in_array($ext, $allowedExt, true)) 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($f['tmp_name'], $dest)) return '';
  return $name;
}


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;
}
