<?php
if (session_status() === PHP_SESSION_NONE) { session_start(); }
function e($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }
function base_url($path=''){
  $cfg = require __DIR__ . '/config.php';
  $base = rtrim($cfg['APP_URL'] ?: ( (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS']==='on'?'https':'http') . '://' . $_SERVER['HTTP_HOST'] . rtrim(dirname($_SERVER['SCRIPT_NAME']),'/') ), '/');
  return $base . '/' . ltrim($path,'/');
}
function is_post(){ return ($_SERVER['REQUEST_METHOD'] ?? '') === 'POST'; }
function flash($key,$val=null){ if($val===null){ $v=$_SESSION['__fl'][$key]??null; unset($_SESSION['__fl'][$key]); return $v; } $_SESSION['__fl'][$key]=$val; }
function require_login(){ if(empty($_SESSION['user'])){ header('Location: login.php'); exit; } }
function csrf_token(){ if(empty($_SESSION['csrf'])) $_SESSION['csrf']=bin2hex(random_bytes(16)); return $_SESSION['csrf']; }
function csrf_check(){ if(!isset($_POST['csrf']) || $_POST['csrf']!==($_SESSION['csrf']??'')){ http_response_code(400); exit('Invalid CSRF'); } }


