
­­­­­­­­­­­­­­­­­­
<!DOCTYPE html>
<html>
<?php
declare(strict_types=1);

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

function redirect(string $url): void {
  header('Location: ' . $url);
  exit;
}

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

function base_url(array $config, string $path = ''): string {
  $b = rtrim($config['base_url'] ?? '', '/');
  $p = '/' . ltrim($path, '/');
  return $b . $p;
}

function normalize_mobile(string $mobile): string {
  $m = preg_replace('/\s+/', '', $mobile);
  $m = str_replace(['-','(',')'], '', $m);
  // keep digits only
  $m = preg_replace('/\D+/', '', $m);
  // remove leading 00
  $m = preg_replace('/^00/', '', $m);
  // remove leading 0 (common local entry)
  $m = preg_replace('/^0+/', '', $m);
  return $m ?? '';
}

function flash_set(string $type, string $msg): void {
  $_SESSION['_flash'][] = ['type' => $type, 'msg' => $msg];
}
function flash_get(): array {
  $f = $_SESSION['_flash'] ?? [];
  unset($_SESSION['_flash']);
  return $f;
}

function require_post(): void {
  if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo "Method Not Allowed";
    exit;
  }
}

function csrf_token(): string {
  if (empty($_SESSION['_csrf'])) $_SESSION['_csrf'] = bin2hex(random_bytes(16));
  return $_SESSION['_csrf'];
}
function csrf_check(): void {
  $t = $_POST['_csrf'] ?? '';
  if (!$t || !hash_equals($_SESSION['_csrf'] ?? '', $t)) {
    http_response_code(419);
    echo "CSRF token mismatch";
    exit;
  }
}

function csrf_field(): string
{
  $token = csrf_token();
  return '<input type="hidden" name="_csrf" value="' . htmlspecialchars($token, ENT_QUOTES, 'UTF-8') . '">';
}



