<?php
declare(strict_types=1);

function op_flash(string $type, string $message): void {
  if (session_status() !== PHP_SESSION_ACTIVE) { @session_start(); }
  $_SESSION[$type] = $message;
}

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

function op_back(string $fallback='dashboard.php'): void {
  $ref = $_SERVER['HTTP_REFERER'] ?? '';
  if ($ref) {
    op_redirect($ref);
  }
  op_redirect($fallback);
}

function op_try(callable $fn, string $successRedirect, ?string $successMsg=null, string $fallbackRedirect='dashboard.php'): void {
  try {
    $fn();
    if ($successMsg) op_flash('success', $successMsg);
    op_redirect($successRedirect);
  } catch (Throwable $e) {
    op_flash('error', $e->getMessage());
    op_back($fallbackRedirect);
  }
}
