<?php
declare(strict_types=1);

if (session_status() !== PHP_SESSION_ACTIVE) session_start();

$role = strtoupper((string)($_SESSION['role'] ?? 'STAFF'));

/* السماح فقط للـ OWNER أو ADMIN */
if (!in_array($role, ['OWNER','ADMIN'], true)) {
  http_response_code(403);
  die('غير مصرح');
}

$branch = (int)($_POST['branch_id'] ?? 1);
if (!in_array($branch, [1,2], true)) {
  $branch = 1;
}

$_SESSION['branch_id'] = $branch;

$return = (string)($_POST['return'] ?? 'dashboard.php');

if (
  $return === '' ||
  str_contains($return, '://') ||
  str_contains($return, "\n") ||
  str_contains($return, "\r")
) {
  $return = 'dashboard.php';
}

header("Location: $return");
exit;