<?php

// Calculate tiered cost for a given amount using tier blocks
function calculate_tiered_cost(float $amount, array $tiers): float {
  $cost = 0.0; $remaining = $amount;
  foreach ($tiers as $tier) {
    $from = isset($tier['tier_from']) ? (float)$tier['tier_from'] : 0.0;
    $to   = (isset($tier['tier_to']) && $tier['tier_to'] !== null && $tier['tier_to'] !== '') ? (float)$tier['tier_to'] : INF;
    $rate = isset($tier['rate']) ? (float)$tier['rate'] : 0.0;
    if ($remaining <= 0) break;
    $block_volume = max(0.0, min($remaining, $to - $from + 1));
    $cost += $block_volume * $rate;
    $remaining -= $block_volume;
  }
  return round($cost, 2);
}

// Distribute a fee across tenants based on mode
// mode: flat | equal | proportional (by property square_meters)
// returns associative array tenant_id => allocated_amount
function distribute_fee(PDO $conn, int $landlord_id, float $fee_amount, string $mode, ?int $property_id = null): array {
  $mode = strtolower(trim($mode));
  if ($fee_amount <= 0) return [];

  // Get tenants in scope
  if ($property_id) {
    $stmt = $conn->prepare('SELECT tenant_id, property_id FROM tenant_landlord_map WHERE landlord_id=? AND property_id=?');
    $stmt->execute([$landlord_id, $property_id]);
  } else {
    $stmt = $conn->prepare('SELECT tenant_id, property_id FROM tenant_landlord_map WHERE landlord_id=?');
    $stmt->execute([$landlord_id]);
  }
  $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
  if (!$rows) return [];

  $tenants = array_column($rows, 'tenant_id');
  $count = count($tenants);
  $alloc = [];

  if ($mode === 'flat') {
    foreach ($tenants as $tid) $alloc[(int)$tid] = round($fee_amount, 2);
    return $alloc;
  }

  if ($mode === 'equal' || $count === 0) {
    $per = round($fee_amount / max(1, $count), 2);
    foreach ($tenants as $tid) $alloc[(int)$tid] = $per;
    return $alloc;
  }

  // proportional by square meters
  $in = implode(',', array_fill(0, $count, '?'));
  $q = $conn->prepare("SELECT t.tenant_id, p.square_meters FROM tenant_landlord_map t JOIN properties p ON p.id=t.property_id WHERE t.tenant_id IN ($in)");
  $q->execute($tenants);
  $weights = [];
  $sum = 0.0;
  foreach ($q->fetchAll(PDO::FETCH_ASSOC) as $r) {
    $sqm = max(0.0, (float)($r['square_meters'] ?? 0));
    $weights[(int)$r['tenant_id']] = $sqm;
    $sum += $sqm;
  }
  if ($sum <= 0) {
    // fallback to equal
    $per = round($fee_amount / max(1, $count), 2);
    foreach ($tenants as $tid) $alloc[(int)$tid] = $per;
    return $alloc;
  }
  foreach ($tenants as $tid) {
    $w = $weights[(int)$tid] ?? 0.0;
    $alloc[(int)$tid] = round(($w / $sum) * $fee_amount, 2);
  }
  return $alloc;
}

?>
