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

function has_role(array $user, array $roles): bool {
  return in_array($user['role_code'] ?? '', $roles, true);
}

/**
 * Data-scope checks:
 * - leads: call center agents see assigned_to_user_id = self
 * - opportunities: branch agents see assigned_to_user_id = self; branch managers see branch_id = self.branch_id
 * - sales manager / gm / admin see all
 */
function can_view_lead(array $user, array $lead): bool {
  if (has_role($user, ['ADMIN','GM_SALES','SALES_MGR','MARKETING','CC_SUP'])) return true;
  if (has_role($user, ['CC_AGENT'])) return (int)$lead['assigned_to_user_id'] === (int)$user['id'];
  return false;
}

function can_assign_lead(array $user): bool {
  return has_role($user, ['ADMIN','CC_SUP']);
}

function can_update_lead(array $user, array $lead): bool {
  if (has_role($user, ['ADMIN','CC_SUP'])) return true;
  if (has_role($user, ['CC_AGENT'])) return (int)$lead['assigned_to_user_id'] === (int)$user['id'];
  return false;
}

function can_view_opp(array $user, array $opp): bool {
  if (has_role($user, ['ADMIN','GM_SALES','SALES_MGR'])) return true;
  if (has_role($user, ['BR_MGR'])) return (int)$opp['branch_id'] === (int)$user['branch_id'];
  if (has_role($user, ['BR_AGENT'])) return (int)$opp['assigned_to_user_id'] === (int)$user['id'];
  return false;
}

function can_assign_opp(array $user, array $opp): bool {
  if (has_role($user, ['ADMIN'])) return true;
  if (has_role($user, ['BR_MGR'])) return (int)$opp['branch_id'] === (int)$user['branch_id'];
  return false;
}
