<?php
// billing.php — RBE Billing Settings (landlord-scoped)
// - Extra Utility Fees with 5 "Other" pairs (name+amount)
// - Fee Distribution Modes (sewage/refuse/rates/other) per landlord
// - Tariff Blocks (existing modal remains)
// REQUIREMENT: See ALTER TABLE at top of chat to add other_fee_* 2..5 columns.

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

session_start();
require_once 'db_connect.php';

if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit;
}

$user_id = (int)$_SESSION['user_id'];

// Role & landlord scoping
$stmt = $conn_rbe->prepare("SELECT role FROM rbe_roles WHERE user_id = ? LIMIT 1");
$stmt->execute([$user_id]);
$role = $stmt->fetchColumn();

if (!in_array($role, ['admin', 'landlord'])) {
    exit('❌ Access denied.');
}

$is_admin    = ($role === 'admin');
$landlord_id = $is_admin ? (int)($_GET['landlord_id'] ?? 0) : $user_id;

if (!$landlord_id) {
    exit("⚠️ Landlord ID is required.");
}

// Tenants for this landlord
$stmt = $conn_rbe->prepare("
    SELECT tlm.tenant_id, ru.fullname
    FROM tenant_landlord_map tlm
    JOIN rbe_users ru ON tlm.tenant_id = ru.id
    WHERE tlm.landlord_id = ?
");
$stmt->execute([$landlord_id]);
$tenants = $stmt->fetchAll(PDO::FETCH_ASSOC);
$tenantsAssoc = [];
foreach ($tenants as $t) { $tenantsAssoc[$t['tenant_id']] = $t['fullname']; }

// -------------------------------
// Helpers
// -------------------------------
function esc($v){ return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8'); }

// Upsert a single mode row in billing_fee_modes
function upsert_fee_mode(PDO $pdo, int $landlord_id, string $fee_type, string $mode): void {
    // Try update first
    $upd = $pdo->prepare("UPDATE billing_fee_modes SET mode = ? WHERE landlord_id = ? AND fee_type = ?");
    $upd->execute([$mode, $landlord_id, $fee_type]);
    if ($upd->rowCount() === 0) {
        // Fallback insert
        $ins = $pdo->prepare("INSERT INTO billing_fee_modes (landlord_id, fee_type, mode, created_at) VALUES (?, ?, ?, NOW())");
        $ins->execute([$landlord_id, $fee_type, $mode]);
    }
}

// -------------------------------
// Load Fee Modes (current values)
// -------------------------------
$stmt = $conn_rbe->prepare("SELECT fee_type, mode FROM billing_fee_modes WHERE landlord_id = ?");
$stmt->execute([$landlord_id]);
$fee_modes = ['sewage'=>null,'refuse'=>null,'rates'=>null,'other'=>null];
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $m) {
    $t = strtolower($m['fee_type']);
    if (isset($fee_modes[$t])) $fee_modes[$t] = $m['mode'];
}

// -------------------------------
// Handle EDIT click: load entry into Extra Fees form
// -------------------------------
$editingEntry = null;
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['edit_entry_id'])) {
    $editId = (int)$_POST['edit_entry_id'];
    $stmt = $conn_rbe->prepare("SELECT * FROM billing_settings WHERE id = ? AND landlord_id = ?");
    $stmt->execute([$editId, $landlord_id]);
    $editingEntry = $stmt->fetch(PDO::FETCH_ASSOC) ?: null;
}

// -------------------------------
// Handle Extra Fees UPDATE (existing row)
// -------------------------------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_fee_id'])) {
    $updateId = (int)$_POST['update_fee_id'];
    $tenant_id = ($_POST['tenant_id'] !== '') ? (int)$_POST['tenant_id'] : null;

    $stmt = $conn_rbe->prepare("
        UPDATE billing_settings
           SET tenant_id = ?,
               sewage_fee = ?,
               refuse_removal_fee = ?,
               rates_and_taxes = ?,
               other_fee = ?,         other_fee_name = ?,
               other_fee_2 = ?,       other_fee_name_2 = ?,
               other_fee_3 = ?,       other_fee_name_3 = ?,
               other_fee_4 = ?,       other_fee_name_4 = ?,
               other_fee_5 = ?,       other_fee_name_5 = ?
         WHERE id = ? AND landlord_id = ?
    ");
    $stmt->execute([
        $tenant_id,
        (float)($_POST['sewage_fee'] ?? 0),
        (float)($_POST['refuse_removal_fee'] ?? 0),
        (float)($_POST['rates_and_taxes'] ?? 0),
        (float)($_POST['other_fee'] ?? 0),
        trim($_POST['other_fee_name'] ?? ''),
        (float)($_POST['other_fee_2'] ?? 0),
        trim($_POST['other_fee_name_2'] ?? ''),
        (float)($_POST['other_fee_3'] ?? 0),
        trim($_POST['other_fee_name_3'] ?? ''),
        (float)($_POST['other_fee_4'] ?? 0),
        trim($_POST['other_fee_name_4'] ?? ''),
        (float)($_POST['other_fee_5'] ?? 0),
        trim($_POST['other_fee_name_5'] ?? ''),
        $updateId,
        $landlord_id
    ]);
    header("Location: billing.php?updated=1&landlord_id=" . $landlord_id);
    exit;
}

// -------------------------------
// Handle Extra Fees INSERT (new row)
// -------------------------------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_fees']) && !isset($_POST['update_fee_id'])) {
    $tenant_id = ($_POST['tenant_id'] !== '') ? (int)$_POST['tenant_id'] : null;
    $stmt = $conn_rbe->prepare("
        INSERT INTO billing_settings
            (landlord_id, tenant_id,
             sewage_fee, refuse_removal_fee, rates_and_taxes,
             other_fee, other_fee_name,
             other_fee_2, other_fee_name_2,
             other_fee_3, other_fee_name_3,
             other_fee_4, other_fee_name_4,
             other_fee_5, other_fee_name_5)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    ");
    $stmt->execute([
        $landlord_id,
        $tenant_id,
        (float)($_POST['sewage_fee'] ?? 0),
        (float)($_POST['refuse_removal_fee'] ?? 0),
        (float)($_POST['rates_and_taxes'] ?? 0),
        (float)($_POST['other_fee'] ?? 0),
        trim($_POST['other_fee_name'] ?? ''),
        (float)($_POST['other_fee_2'] ?? 0),
        trim($_POST['other_fee_name_2'] ?? ''),
        (float)($_POST['other_fee_3'] ?? 0),
        trim($_POST['other_fee_name_3'] ?? ''),
        (float)($_POST['other_fee_4'] ?? 0),
        trim($_POST['other_fee_name_4'] ?? ''),
        (float)($_POST['other_fee_5'] ?? 0),
        trim($_POST['other_fee_name_5'] ?? '')
    ]);
    header("Location: billing.php?saved=1&landlord_id=" . $landlord_id);
    exit;
}

// -------------------------------
// Handle Fee Mode SAVE
// -------------------------------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_fee_modes'])) {
    $valid_modes = ['flat','equal','proportional'];
    $input_modes = [
        'sewage' => strtolower($_POST['mode_sewage'] ?? ''),
        'refuse' => strtolower($_POST['mode_refuse'] ?? ''),
        'rates'  => strtolower($_POST['mode_rates'] ?? ''),
        'other'  => strtolower($_POST['mode_other'] ?? '')
    ];
    foreach ($input_modes as $type => $mode) {
        if (!in_array($mode, $valid_modes, true)) continue;
        upsert_fee_mode($conn_rbe, $landlord_id, $type, $mode);
        $fee_modes[$type] = $mode; // reflect in UI
    }
    header("Location: billing.php?modes=1&landlord_id=" . $landlord_id);
    exit;
}

// -------------------------------
// Handle Tariff Block SAVE
// -------------------------------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_tier'])) {
    $type = $_POST['type'] ?? 'electricity';
    $tenant_id = ($_POST['tenant_id'] === '') ? null : (int)$_POST['tenant_id'];

    $block_names = $_POST['block_name'] ?? [];
    $tier_from   = $_POST['tier_from'] ?? [];
    $tier_to     = $_POST['tier_to'] ?? [];
    $rates       = $_POST['rate'] ?? [];
    $cons_pct    = $_POST['consumption_pct'] ?? [];
    $valid_from  = $_POST['valid_from'] ?? [];
    $valid_to    = $_POST['valid_to'] ?? [];
    $existing_id = $_POST['existing_tier_id'] ?? [];

    for ($i = 0; $i < count($block_names); $i++) {
        $block_name = trim($block_names[$i]);
        $from = (float)$tier_from[$i];
        $to   = ($tier_to[$i] === '' ? null : (float)$tier_to[$i]);
        $rate = (float)$rates[$i];
        $pct  = (float)$cons_pct[$i];
        $vf   = $valid_from[$i] ?: null;
        $vt   = $valid_to[$i]   ?: null;

        if (!empty($existing_id[$i])) {
            $stmt = $conn_rbe->prepare("
                UPDATE billing_tiers
                   SET block_name=?, tier_from=?, tier_to=?, rate=?, consumption_pct=?, valid_from=?, valid_to=?
                 WHERE id=? AND landlord_id=?
            ");
            $stmt->execute([$block_name,$from,$to,$rate,$pct,$vf,$vt,(int)$existing_id[$i],$landlord_id]);
        } else {
            $stmt = $conn_rbe->prepare("
                INSERT INTO billing_tiers
                    (landlord_id, tenant_id, type, block_name, tier_from, tier_to, rate, consumption_pct, valid_from, valid_to)
                VALUES (?,?,?,?,?,?,?,?,?,?)
            ");
            $stmt->execute([$landlord_id,$tenant_id,$type,$block_name,$from,$to,$rate,$pct,$vf,$vt]);
        }
    }

    header("Location: billing.php?tariffsaved=1&landlord_id=" . $landlord_id);
    exit;
}

// -------------------------------
// Handle Tariff Block DELETE
// -------------------------------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_tier_id'])) {
    $deleteId = (int)$_POST['delete_tier_id'];
    $stmt = $conn_rbe->prepare("DELETE FROM billing_tiers WHERE id = ? AND landlord_id = ?");
    $stmt->execute([$deleteId, $landlord_id]);
    header("Location: billing.php?tierdeleted=1&landlord_id=" . $landlord_id);
    exit;
}

// -------------------------------
// Load settings and tiers for display
// -------------------------------
$stmt = $conn_rbe->prepare("
    SELECT bs.*, ru.fullname AS tenant_name
    FROM billing_settings bs
    LEFT JOIN rbe_users ru ON bs.tenant_id = ru.id
    WHERE bs.landlord_id = ?
    ORDER BY bs.tenant_id IS NULL DESC, ru.fullname ASC
");
$stmt->execute([$landlord_id]);
$billing_settings = $stmt->fetchAll(PDO::FETCH_ASSOC);

$global_billing = null;
foreach ($billing_settings as $row) {
    if (empty($row['tenant_id'])) { $global_billing = $row; break; }
}

$stmt = $conn_rbe->prepare("SELECT * FROM billing_tiers WHERE landlord_id = ? ORDER BY tenant_id, type, tier_from");
$stmt->execute([$landlord_id]);
$billing_tiers = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>RBE Billing Settings</title>
  <link href="https://fonts.googleapis.com/css2?family=Segoe+UI&display=swap" rel="stylesheet">
  <style>
    body { font-family: 'Segoe UI', sans-serif; background: #051a25; color: #fff; margin: 0; padding: 20px; }
    h1, h2, h3 { color: #7ed957; }
    .card { background: #122c4c; padding: 20px; border-radius: 12px; max-width: 100%; margin: auto; box-shadow: 0 0 20px rgba(0,0,0,0.4); }
    button { margin-top: 15px; padding: 10px 20px; background: #7ed957; color: black; border: none; border-radius: 8px; font-weight: bold; cursor: pointer; }
    table { width: 100%; margin-top: 20px; border-collapse: collapse; background: #0b1f33; color: white; }
    th, td { padding: 10px; border: 1px solid #7ed957; }
    th { background: #1b3a4d; }
    .nav-btn { background: #7ed957; color: #000; padding: 10px 20px; border-radius: 8px; text-decoration: none; font-weight: bold; display: inline-block; margin-bottom: 20px; }
    .property-section { background: #0b1f33; padding: 15px 20px; border-radius: 10px; margin-top: 30px; box-shadow: 0 2px 8px rgba(0,0,0,0.3); }
    .fee-grid { display: flex; flex-wrap: wrap; gap: 20px; margin-top: 20px; }
    .fee-grid .property-section { flex: 1 1 calc(33.333% - 20px); background: #0b1f33; padding: 15px 20px; border-radius: 10px; box-shadow: 0 2px 8px rgba(0,0,0,0.3); min-width: 260px; }
    .list-style { list-style: none; padding-left: 0; color: #eee; }
    .row-pair { display:flex; gap:10px; }
    .row-pair > div { flex:1; min-width: 160px; }
    .lbl { display:block; color:#7ed957; margin-bottom:5px; }
    .inp { width:100%; padding:10px; border-radius:6px; border:1px solid #7ed957; background:#0b1f33; color:white; }
    .tag { display:inline-block; padding:2px 8px; border-radius:999px; border:1px solid #7ed957; color:#7ed957; font-size:12px; background:#0b1f33; }
    .inline-form { display:inline; }
  </style>
</head>
<body>
  <a href="<?= ($role === 'landlord') ? 'landlord-dashboard.php' : 'admin-dashboard.php' ?>" class="nav-btn">Back to Dashboard</a>

  <div class="card">
    <h2>🏷️ Extra Utility Fees</h2>

    <form method="POST" style="background:#0e2238; padding:20px; border-radius:12px; box-shadow:0 0 10px rgba(0,0,0,0.3); max-width: 720px;">
      <input type="hidden" name="update_fees" value="1">
      <?php if ($editingEntry): ?>
        <input type="hidden" name="update_fee_id" value="<?= (int)$editingEntry['id'] ?>">
      <?php endif; ?>

      <div style="margin-bottom: 15px;">
        <label class="lbl">Tenant:</label>
        <select name="tenant_id" class="inp">
          <option value="">🌐 Global</option>
          <?php foreach ($tenants as $t): ?>
            <option value="<?= (int)$t['tenant_id'] ?>" <?= $editingEntry && $editingEntry['tenant_id'] == $t['tenant_id'] ? 'selected' : '' ?>>
              <?= esc($t['fullname']) ?>
            </option>
          <?php endforeach; ?>
        </select>
      </div>

      <div style="margin-bottom: 15px;">
        <label class="lbl">Sewage Fee (R):</label>
        <input class="inp" type="number" step="0.01" name="sewage_fee" value="<?= esc($editingEntry['sewage_fee'] ?? '') ?>">
      </div>

      <div style="margin-bottom: 15px;">
        <label class="lbl">Refuse Removal Fee (R):</label>
        <input class="inp" type="number" step="0.01" name="refuse_removal_fee" value="<?= esc($editingEntry['refuse_removal_fee'] ?? '') ?>">
      </div>

      <div style="margin-bottom: 15px;">
        <label class="lbl">Rates &amp; Taxes (R):</label>
        <input class="inp" type="number" step="0.01" name="rates_and_taxes" value="<?= esc($editingEntry['rates_and_taxes'] ?? '') ?>">
      </div>

      <!-- Other fee pair #1 (existing) -->
      <div class="row-pair" style="margin-bottom:15px;">
        <div>
          <label class="lbl">Other Fee Name 1:</label>
          <input class="inp" type="text" name="other_fee_name" placeholder="e.g. Admin Charge" value="<?= esc($editingEntry['other_fee_name'] ?? '') ?>">
        </div>
        <div>
          <label class="lbl">Other Fee Amount 1 (R):</label>
          <input class="inp" type="number" step="0.01" name="other_fee" value="<?= esc($editingEntry['other_fee'] ?? '') ?>">
        </div>
      </div>

      <!-- Other fee pairs #2..#5 -->
      <?php
        $pairs = [
          ['n'=>2,'name'=>'other_fee_name_2','amt'=>'other_fee_2'],
          ['n'=>3,'name'=>'other_fee_name_3','amt'=>'other_fee_3'],
          ['n'=>4,'name'=>'other_fee_name_4','amt'=>'other_fee_4'],
          ['n'=>5,'name'=>'other_fee_name_5','amt'=>'other_fee_5'],
        ];
        foreach ($pairs as $p):
      ?>
        <div class="row-pair" style="margin-bottom:15px;">
          <div>
            <label class="lbl">Other Fee Name <?= $p['n'] ?>:</label>
            <input class="inp" type="text" name="<?= $p['name'] ?>" value="<?= esc($editingEntry[$p['name']] ?? '') ?>">
          </div>
          <div>
            <label class="lbl">Other Fee Amount <?= $p['n'] ?> (R):</label>
            <input class="inp" type="number" step="0.01" name="<?= $p['amt'] ?>" value="<?= esc($editingEntry[$p['amt']] ?? '') ?>">
          </div>
        </div>
      <?php endforeach; ?>

      <button type="submit" style="background:#7ed957; color:#000; font-weight:bold; padding:10px 20px; border-radius:8px; border:none; cursor:pointer;">
        💾 Save Extra Fees
      </button>
    </form>
  </div>

  <!-- Fee Modes -->
  <div class="card" style="margin-top:20px;">
    <h2>⚖️ Fee Distribution Modes</h2>
    <p class="tag">Landlord-wide rule per fee type (applied by your billing calc):</p>
    <form method="POST" style="margin-top:12px;">
      <input type="hidden" name="save_fee_modes" value="1">
      <?php
        $opts = ['flat'=>'Flat','equal'=>'Equal Split','proportional'=>'Proportional'];
        $types = ['sewage'=>'Sewage','refuse'=>'Refuse Removal','rates'=>'Rates & Taxes','other'=>'Other (sum of all “Other” lines)'];
        foreach ($types as $tkey=>$label):
          $curr = $fee_modes[$tkey] ?? '';
      ?>
        <div style="display:flex; align-items:center; gap:10px; margin-bottom:8px;">
          <div style="width:220px;"><strong><?= esc($label) ?>:</strong></div>
          <select name="mode_<?= esc($tkey) ?>" class="inp" style="max-width:240px;">
            <?php foreach ($opts as $v=>$txt): ?>
              <option value="<?= $v ?>" <?= ($curr===$v?'selected':'') ?>><?= $txt ?></option>
            <?php endforeach; ?>
          </select>
        </div>
      <?php endforeach; ?>
      <button type="submit">💾 Save Modes</button>
    </form>
  </div>

  <h2 style="color:#ffc107; margin-top: 28px;">📦 Saved Extra Utility Fees</h2>
  <div class="fee-grid">
    <?php
      // Group by tenant (Global first)
      $groupedSettings = [];
      foreach ($billing_settings as $row) {
        $tid = $row['tenant_id'] ?? null;
        $tname = $tid ? ($row['tenant_name'] ?: "🧑 Tenant #$tid") : '🌐 Global';
        $groupedSettings[$tid]['name'] = $tname;
        $groupedSettings[$tid]['entries'][] = $row;
      }

      foreach ($groupedSettings as $tid => $group) {
        echo "<div class='property-section'>";
        echo "<h3 style='color:#7ed957; font-size: 18px; margin-bottom: 10px;'>🧾 ".esc($group['name'])."</h3>";
        echo "<ul class='list-style'>";

        foreach ($group['entries'] as $entry) {
          echo "<li style='margin-bottom:12px; position:relative; padding-right:40px;'>";

          // Edit button
          echo "<form method='POST' class='inline-form' style='position:absolute; top:0; right:0;'>";
          echo "<input type='hidden' name='edit_entry_id' value='".(int)$entry['id']."'>";
          echo "<button type='submit' title='Edit' style='background:none; border:none; color:#7ed957; font-size:14px; cursor:pointer;'>✏️</button>";
          echo "</form>";

          if ($entry['sewage_fee'] !== null) {
            echo "🚽 Sewage: <strong>R" . number_format((float)$entry['sewage_fee'], 2) . "</strong><br>";
          }
          if ($entry['refuse_removal_fee'] !== null) {
            echo "🗑️ Refuse: <strong>R" . number_format((float)$entry['refuse_removal_fee'], 2) . "</strong><br>";
          }
          if ($entry['rates_and_taxes'] !== null) {
            echo "🏛️ Rates: <strong>R" . number_format((float)$entry['rates_and_taxes'], 2) . "</strong><br>";
          }

          // Show “Other” lines 1..5 only when > 0
          $others = [
            ['name'=>$entry['other_fee_name']    ?? '', 'amt'=>$entry['other_fee']    ?? 0],
            ['name'=>$entry['other_fee_name_2'] ?? '', 'amt'=>$entry['other_fee_2'] ?? 0],
            ['name'=>$entry['other_fee_name_3'] ?? '', 'amt'=>$entry['other_fee_3'] ?? 0],
            ['name'=>$entry['other_fee_name_4'] ?? '', 'amt'=>$entry['other_fee_4'] ?? 0],
            ['name'=>$entry['other_fee_name_5'] ?? '', 'amt'=>$entry['other_fee_5'] ?? 0],
          ];
          $idx = 1;
          foreach ($others as $o) {
            $amt = (float)$o['amt'];
            if ($amt > 0) {
              $label = trim((string)$o['name']) !== '' ? esc($o['name']) : ('Other '.$idx);
              echo "➕ {$label}: <strong>R" . number_format($amt, 2) . "</strong><br>";
            }
            $idx++;
          }

          echo "</li>";
        }

        echo "</ul></div>";
      }
    ?>
  </div>

  <div style="text-align:right; margin-top: 16px;">
    <button onclick="openNewTierModal('electricity','global')">⚙️ Add Tariffs</button>
  </div>

  <h2>📋 Saved Tariff Blocks</h2>
  <div id="savedTariffsContainer"></div>

  <?php
    // Group tariff blocks by tenant + type
    $grouped = [];
    foreach ($billing_tiers as $tier) {
      $tenantId = $tier['tenant_id'] ?? null;
      $type = trim($tier['type']);
      if (!$type) continue;

      $tenantName = $tenantId ? ($tenantsAssoc[$tenantId] ?? "🧑 Tenant #$tenantId") : '🌐 Global';
      $grouped[$tenantId]['_name'] = $tenantName;
      $grouped[$tenantId][$type][] = $tier;
    }

    foreach ($grouped as $tenantId => $types) {
      $tenantName = $types['_name'] ?? "Unknown";
      unset($types['_name']);

      foreach ($types as $type => $tiers) {
        echo "<div class='property-section'>";
        echo "<h3 style='display:flex; justify-content:space-between; align-items:center;'>";
        echo "<span>🔹 " . strtoupper(esc($type)) . " — <span style='color:#00ccff;'>".esc($tenantName)."</span></span>";
        echo "<button onclick=\"openNewTierModal('".esc($type)."', '".esc($tenantId === null ? 'global' : $tenantId)."')\" style='background:#7ed957; color:#000; border:none; padding:6px 14px; font-weight:bold; border-radius:8px; cursor:pointer;'>⚙️ Edit Tariffs</button>";
        echo "</h3><ul class='list-style'>";

        foreach ($tiers as $t) {
          $range = number_format((float)$t['tier_from'], 2) . ' – ' . ($t['tier_to'] !== null ? number_format((float)$t['tier_to'], 2) : '∞');
          $rate  = number_format((float)$t['rate'], 2);
          $name  = $t['block_name'] ? "<strong>" . esc($t['block_name']) . "</strong>: " : "";
          $from  = $t['valid_from'] ?? '—';
          $to    = $t['valid_to'] ?? '∞';

          echo "<li style='display:flex; justify-content:space-between; align-items:center; gap:8px;'>";
          echo "<span>$name$range @ R$rate <span style='color:#ccc;'>($from → $to)</span></span>";

          echo "<form method='POST' onsubmit=\"return confirm('Delete this tier?')\" class='inline-form'>";
          echo "<input type='hidden' name='delete_tier_id' value='".(int)$t['id']."'>";
          echo "<button type='submit' style='background:none;border:none;color:#f66;font-size:16px;cursor:pointer;'>🗑️</button>";
          echo "</form>";

          echo "</li>";
        }

        echo "</ul></div>";
      }
    }
  ?>

  <!-- Tariff Modal -->
  <div id="tariffModal" style="display:none; position: fixed; top:0; left:0; width:100%; height:100%; background-color: rgba(0,0,0,0.75); z-index:9999; overflow:auto;">
    <div class="modal-content" style="background:#122c4c; padding:30px; border-radius:12px; width:90%; max-width:1000px; margin:60px auto; position:relative; max-height:90%; overflow-y:auto;">
      <span class="close-btn" style="position:absolute; top:10px; right:15px; cursor:pointer; font-size:20px; color:#7ed957;" onclick="document.getElementById('tariffModal').style.display='none'">&times;</span>
      <h2>📈 Manage Tariff Blocks</h2>
      <form method="POST">
        <input type="hidden" name="add_tier" value="1">
        <label>Type</label>
        <select name="type" id="tierType" class="inp" style="margin-bottom:8px;">
          <option value="electricity">Electricity</option>
          <option value="water">Water</option>
        </select>
        <label>Tenant</label>
        <select name="tenant_id" id="tierTenant" class="inp" style="margin-bottom:8px;">
          <option value="">🌐 Global</option>
          <?php foreach ($tenants as $t): ?>
            <option value="<?= (int)$t['tenant_id'] ?>"><?= esc($t['fullname']) ?></option>
          <?php endforeach; ?>
        </select>

        <table id="tierRows">
          <thead>
            <tr>
              <th>Block Name</th>
              <th>From</th>
              <th>To</th>
              <th>Rate (R)</th>
              <th>%</th>
              <th>From Date</th>
              <th>To Date</th>
              <th></th>
            </tr>
          </thead>
          <tbody></tbody>
        </table>

        <button type="button" onclick="addRow()">➕ Add Row</button>

        <div class="modal-footer" style="text-align:right; margin-top:20px;">
          <button type="submit">💾 Save All</button>
        </div>
      </form>
    </div>
  </div>

  <template id="tierTemplate">
    <tr>
      <td><input name="block_name[]" type="text" class="inp"></td>
      <td><input name="tier_from[]" type="number" step="0.01" class="inp"></td>
      <td><input name="tier_to[]" type="number" step="0.01" class="inp"></td>
      <td><input name="rate[]" type="number" step="0.01" class="inp"></td>
      <td><input name="consumption_pct[]" type="number" step="0.01" class="inp"></td>
      <td><input name="valid_from[]" type="date" class="inp"></td>
      <td><input name="valid_to[]" type="date" class="inp"></td>
      <td><button type="button" onclick="removeRow(this)">❌</button></td>
    </tr>
  </template>

<script>
  const billingTiersData = <?= json_encode($billing_tiers) ?>;

  function openNewTierModal(type, tenantId) {
    const modal = document.getElementById("tariffModal");
    modal.style.display = "block";

    // Set type + tenant dropdowns
    document.getElementById("tierType").value = type;
    document.getElementById("tierTenant").value = tenantId === 'global' ? '' : tenantId;

    // Clear old rows
    const tbody = document.querySelector("#tierRows tbody");
    tbody.innerHTML = "";

    // Pre-fill rows if editing
    const tiers = billingTiersData.filter(t => {
      return t.type === type && 
             ((tenantId === 'global' && !t.tenant_id) || t.tenant_id == tenantId);
    });

    if (tiers.length > 0) {
      tiers.forEach(t => addRow({
        block_name: t.block_name,
        tier_from: t.tier_from,
        tier_to: t.tier_to,
        rate: t.rate,
        consumption_pct: t.consumption_pct,
        valid_from: t.valid_from,
        valid_to: t.valid_to,
        existing_tier_id: t.id
      }));
    } else {
      // Start with one empty row if none exist
      addRow();
    }
  }

  function addRow(prefill = {}) {
    const tbody = document.querySelector("#tierRows tbody");
    const row = document.querySelector("#tierTemplate").content.cloneNode(true);

    row.querySelector("input[name='block_name[]']").value = prefill.block_name || '';
    row.querySelector("input[name='tier_from[]']").value = prefill.tier_from || '';
    row.querySelector("input[name='tier_to[]']").value = prefill.tier_to || '';
    row.querySelector("input[name='rate[]']").value = prefill.rate || '';
    row.querySelector("input[name='consumption_pct[]']").value = prefill.consumption_pct || '';
    row.querySelector("input[name='valid_from[]']").value = prefill.valid_from || '';
    row.querySelector("input[name='valid_to[]']").value = prefill.valid_to || '';

    // Hidden field for update vs insert
    if (prefill.existing_tier_id) {
      const hidden = document.createElement("input");
      hidden.type = "hidden";
      hidden.name = "existing_tier_id[]";
      hidden.value = prefill.existing_tier_id;
      row.querySelector("tr").appendChild(hidden);
    }

    tbody.appendChild(row);
  }

  function removeRow(btn) {
    btn.closest("tr").remove();
  }
</script>

