<?php
require_once dirname(__DIR__) . '/core/currency.php';

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

function redirect(string $url) {
  header("Location: $url");
  exit;
}

function is_post(): bool {
  return ($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST';
}

/**
 * Load app config safely (ONLY config.php, never database.php)
 */
function app_config(): array {
  static $cfg = null;

  if ($cfg === null) {
    $path = __DIR__ . '/../config/config.php';

    if (!file_exists($path)) {
      die('Config file missing: app/config/config.php');
    }

    $cfg = require $path;

    if (!is_array($cfg)) {
      die('Config file must return an array');
    }
  }

  return $cfg;
}


function profile_completion(array $u): int {
  $fields = [
    !empty($u['full_name']),
    !empty($u['phone']),
    !empty($u['photo']),
    $u['kyc_status'] === 'verified'
  ];
  return (int)(array_sum($fields) / count($fields) * 100);
}

/**
 * Start session safely
 */
function session_boot() {
  if (session_status() === PHP_SESSION_NONE) {
    $config = app_config();
    session_name($config['session_name'] ?? 'PHPSESSID');
    session_start();
  }
}

function flash(string $key, ?string $value = null) {
  session_boot();

  if ($value === null) {
    $v = $_SESSION['flash'][$key] ?? null;
    unset($_SESSION['flash'][$key]);
    return $v;
  }

  $_SESSION['flash'][$key] = $value;
}

function now_ref(string $prefix='ABK'): string {
  return $prefix . '-' . gmdate('YmdHis') . '-' . random_int(1000, 9999);
}

function client_ip(): ?string {
  return $_SERVER['REMOTE_ADDR'] ?? null;
}

function require_keys(array $arr, array $keys) {
  foreach ($keys as $k) {
    if (!isset($arr[$k]) || $arr[$k] === '') {
      throw new Exception("Missing field: $k");
    }
  }
}

function money(float $amount): string {
  return number_format($amount, 2);
}
