<?php
// utils.php — helper JSON + URL publik + UUID

function db_path() {
  return __DIR__ . '/database.json';
}

function ensure_db_exists() {
  $file = db_path();
  if (!file_exists($file)) {
    file_put_contents($file, json_encode([], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
  }
}

function read_db() {
  ensure_db_exists();
  $file = db_path();
  $fp = fopen($file, 'r');
  if (!$fp) return [];
  flock($fp, LOCK_SH);
  $content = stream_get_contents($fp);
  flock($fp, LOCK_UN);
  fclose($fp);
  $data = json_decode($content, true);
  return is_array($data) ? $data : [];
}

function write_db($data) {
  $file = db_path();
  $fp = fopen($file, 'c+');
  if (!$fp) return false;
  flock($fp, LOCK_EX);
  ftruncate($fp, 0);
  $ok = fwrite($fp, json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
  fflush($fp);
  flock($fp, LOCK_UN);
  fclose($fp);
  return $ok !== false;
}

function make_uuid() {
  $data = random_bytes(16);
  $data[6] = chr((ord($data[6]) & 0x0f) | 0x40);
  $data[8] = chr((ord($data[8]) & 0x3f) | 0x80);
  return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
}

// URL publik absolut dari path (relatif / absolut) → https://domain/...
function file_public_url($path) {
  // Jika diberi absolut filesystem, konversi ke relatif dari DOCUMENT_ROOT
  $abs = $path;
  if ($path[0] !== '/' && !preg_match('#^[A-Za-z]:[\\\\/]#', $path)) {
    $abs = realpath(__DIR__ . '/' . ltrim($path, '/'));
  }
  if (!$abs) {
    // fallback pakai path relatif URL
    $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
    $host = $_SERVER['HTTP_HOST'] ?? 'localhost';
    return $scheme . '://' . $host . '/' . ltrim($path, '/');
  }
  $docRoot = realpath($_SERVER['DOCUMENT_ROOT'] ?? __DIR__);
  $rel = str_replace('\\', '/', substr($abs, strlen($docRoot)));
  if ($rel === false || $rel === '') $rel = basename($abs);
  $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
  $host = $_SERVER['HTTP_HOST'] ?? 'localhost';
  return rtrim($scheme . '://' . $host, '/') . '/' . ltrim($rel, '/');
}

// URL embed Office viewer
function office_embed_url($fileUrl) {
  return "https://view.officeapps.live.com/op/embed.aspx?src=" . rawurlencode($fileUrl);
}