<?php

function json_response($data, int $status = 200): void {
  http_response_code($status);
  header('Content-Type: application/json; charset=utf-8');
  echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
  exit;
}

function require_method(string $method): void {
  if (strtoupper($_SERVER['REQUEST_METHOD'] ?? '') !== strtoupper($method)) {
    json_response(['ok' => false, 'error' => 'Método inválido.'], 405);
  }
}

function get_json_body(): array {
  $raw = file_get_contents('php://input');
  if (!$raw) return [];
  $data = json_decode($raw, true);
  return is_array($data) ? $data : [];
}

function post_str(string $key, string $default = ''): string {
  $v = $_POST[$key] ?? $default;
  return is_string($v) ? trim($v) : $default;
}

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

function app_config_get(PDO $pdo, string $chave, string $default = ''): string {
  $st = $pdo->prepare('SELECT valor FROM app_config WHERE chave=? LIMIT 1');
  $st->execute([$chave]);
  $row = $st->fetch();
  if (!$row) return $default;
  return (string)$row['valor'];
}

function app_config_set(PDO $pdo, string $chave, string $valor): void {
  $st = $pdo->prepare('INSERT INTO app_config (chave, valor) VALUES (?, ?) ON DUPLICATE KEY UPDATE valor=VALUES(valor)');
  $st->execute([$chave, $valor]);
}

function uuid16(): string {
  return bin2hex(random_bytes(8));
}

function now_sql(): string {
  return date('Y-m-d H:i:s');
}

// ---- Formatação pt-BR (UI) ----
function br_date(?string $ymd): string {
  $s = trim((string)$ymd);
  if ($s === '') return '';
  // aceita YYYY-MM-DD ou YYYY-MM-DD HH:MM:SS
  $d = substr($s, 0, 10);
  if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $d)) return $s;
  [$y, $m, $day] = explode('-', $d);
  return sprintf('%02d/%02d/%04d', (int)$day, (int)$m, (int)$y);
}

function br_datetime(?string $dt): string {
  $s = trim((string)$dt);
  if ($s === '') return '';
  $d = substr($s, 0, 10);
  if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $d)) return $s;
  $time = '';
  if (strlen($s) >= 19) {
    $time = substr($s, 11, 5); // HH:MM
  }
  $out = br_date($d);
  return $time ? ($out . ' ' . $time) : $out;
}

function ensure_dir(string $path): void {
  if (!is_dir($path)) {
    mkdir($path, 0775, true);
  }
}

function safe_filename(string $name): string {
  $name = preg_replace('/[^a-zA-Z0-9._-]+/', '-', $name);
  $name = trim($name, '-');
  return $name ?: 'file';
}

/**
 * Retorna o "prefixo" do projeto quando ele está em subpasta.
 * Ex.: SCRIPT_NAME=/frame_maker/api/x.php => base=/frame_maker
 * Ex.: SCRIPT_NAME=/index.php => base=""
 */
function app_base_path(): string {
  $script = (string)($_SERVER['SCRIPT_NAME'] ?? '');
  if ($script === '') return '';

  foreach (['/api/', '/admin/'] as $marker) {
    $pos = strpos($script, $marker);
    if ($pos !== false) {
      $base = substr($script, 0, $pos);
      $base = rtrim($base, '/');
      return ($base === '/' || $base === '.') ? '' : $base;
    }
  }

  $base = rtrim(dirname($script), '/');
  return ($base === '/' || $base === '.' ) ? '' : $base;
}

/**
 * Converte um path relativo (ex.: /storage/assets/x.png) para um path
 * respeitando subpasta (ex.: /frame_maker/storage/assets/x.png)
 */
function build_url_path(string $relative_path): string {
  $rel = trim($relative_path);
  if ($rel === '') return app_base_path();
  if ($rel[0] !== '/') $rel = '/' . $rel;
  $base = app_base_path();
  return ($base === '') ? $rel : ($base . $rel);
}

function build_public_url(string $relative_path): string {
  $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
  $host = $_SERVER['HTTP_HOST'] ?? 'localhost';
  return $scheme . '://' . $host . build_url_path($relative_path);
}

