0 ? '?' . http_build_query($params) : ''; $url = strtok($_SERVER["REQUEST_URI"], '?') . $query; header("Location: $url"); exit; } $new_branch_id = (int)$new_branch_id; // Verify user has access to this branch (or is super_admin) if ($current_role === 'super_admin') { $stmt = db()->prepare("SELECT * FROM branches WHERE id = ?"); $stmt->execute([$new_branch_id]); } else { $stmt = db()->prepare("SELECT b.* FROM user_branches ub JOIN branches b ON ub.branch_id = b.id WHERE ub.user_id = ? AND ub.branch_id = ?"); $stmt->execute([$current_user_id, $new_branch_id]); } $branch = $stmt->fetch(); if ($branch) { $_SESSION['branch_id'] = $branch['id']; $_SESSION['branch_name'] = $lang === 'ar' ? ($branch['name_ar'] ?: $branch['name_en']) : $branch['name_en']; // Redirect back to same page without the switch_branch param but keeping others $params = $_GET; unset($params['switch_branch']); $query = count($params) > 0 ? '?' . http_build_query($params) : ''; $url = strtok($_SERVER["REQUEST_URI"], '?') . $query; header("Location: $url"); exit; } } // Fetch user branches $user_branches = []; if ($current_user_id) { if ($current_role === 'super_admin') { $user_branches = db()->query("SELECT * FROM branches")->fetchAll(); } else { $stmt = db()->prepare("SELECT b.* FROM user_branches ub JOIN branches b ON ub.branch_id = b.id WHERE ub.user_id = ?"); $stmt->execute([$current_user_id]); $user_branches = $stmt->fetchAll(); } } // Ensure branch_name is set if not already if (!isset($_SESSION['branch_name']) || empty($_SESSION['branch_name'])) { if (isset($_SESSION['branch_id'])) { if ($_SESSION['branch_id'] === 'all') { $_SESSION['branch_name'] = __('all_branches'); } else { $stmt = db()->prepare("SELECT * FROM branches WHERE id = ?"); $stmt->execute([$_SESSION['branch_id']]); $b = $stmt->fetch(); if ($b) { $_SESSION['branch_name'] = $lang === 'ar' ? ($b['name_ar'] ?: $b['name_en']) : $b['name_en']; } } } } // Fetch Global Company Info $stmt = db()->query("SELECT * FROM companies LIMIT 1"); $company_info = $stmt->fetch(); // Fetch Current User Info (for profile picture) $current_user_data = null; if ($current_user_id) { $stmt = db()->prepare("SELECT * FROM users WHERE id = ?"); $stmt->execute([$current_user_id]); $current_user_data = $stmt->fetch(); } // Global Permission Check for current page $current_page = basename($_SERVER['PHP_SELF']); if ($current_user_id && $current_page !== 'login.php' && $current_page !== 'logout.php') { if (!has_permission('view', $current_page)) { if ($current_page !== 'admin.php' && has_permission('view', 'admin.php')) { header('Location: admin.php'); exit; } elseif ($current_page !== 'profile.php' && has_permission('view', 'profile.php')) { header('Location: profile.php'); exit; } elseif ($current_page !== 'admin.php' && $current_page !== 'profile.php') { die('Access Denied. You do not have permission to view this page.'); } } } ?>