<?php
// ============================================================
// billing-front.php — RBE Utilities Billing Frontend View (v9)
// ------------------------------------------------------------
// Split UI used by wrapper billing.php
// Adds landlord scoping and full settings fields
// ============================================================

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

if (session_status() === PHP_SESSION_NONE) session_start();
require_once __DIR__ . '/../../core/db_connect.php';

$user_id = $_SESSION['user_id'] ?? null;
if (!$user_id) {
  echo "<div style='padding:24px;color:#ff5b5b;font-family:sans-serif;'>Not logged in</div>";
  return;
}

$stmt = $conn_rbe->prepare("SELECT role FROM rbe_roles WHERE user_id=? LIMIT 1");
$stmt->execute([(int)$user_id]);
$role = $stmt->fetchColumn();
$is_admin = ($role === 'admin');

// For admin, fetch landlords for dropdown
$landlords = [];
if ($is_admin) {
  $q = $conn_rbe->query("SELECT u.id, u.fullname FROM rbe_users u JOIN rbe_roles r ON r.user_id=u.id AND r.role='landlord' ORDER BY u.fullname");
  $landlords = $q->fetchAll(PDO::FETCH_ASSOC);
}
?>
<div class="navbar">
  <h1>RBE Utilities Billing Settings</h1>
  <div style="display:flex;gap:12px;align-items:center;">
    <?php if ($is_admin): ?>
      <label for="landlordSelect" style="font-size:12px;color:#8aaec5;">Landlord</label>
      <select id="landlordSelect">
        <option value="">-- Select Landlord --</option>
        <?php foreach ($landlords as $l): ?>
          <option value="<?= (int)$l['id'] ?>"><?= htmlspecialchars($l['fullname']) ?></option>
        <?php endforeach; ?>
      </select>
    <?php endif; ?>
    <a href="<?= ($role === 'landlord') ? '/landlord-dashboard.php' : '/admin-dashboard.php' ?>">
      <button class="btn secondary">Back</button>
    </a>
  </div>
  </div>

<div class="tabs">
  <div class="tab active" data-tab="fees">Extra Fees</div>
  <div class="tab" data-tab="tiers">Tiered Tariffs</div>
  <div class="tab" data-tab="modes">Fee Modes</div>
  <div class="tab" data-tab="settings">Live Billing Settings</div>
  <div class="tab" data-tab="history">History</div>
  </div>

<!-- 1) EXTRA FEES -->
<section id="fees" class="section active">
  <div class="card">
    <h2>Extra Utility Fees</h2>

    <div class="card" style="margin-bottom:25px;">
      <h3 style="color:var(--accent2);margin-top:0;">Add / Edit Fee</h3>
      <form id="feeForm">
        <input type="hidden" name="action" value="save_fee">

        <label>Tenant</label>
        <select name="tenant_id" id="tenantSelect"></select>

        <label>Fee Type</label>
        <select name="fee_type">
          <option value="AIRCON">Aircon</option>
          <option value="GENERATOR">Generator</option>
          <option value="ELEC_AVAILABILITY">Electricity Availability</option>
          <option value="ELEC_BASIC">Electricity Basic</option>
          <option value="WATER_AVAILABILITY">Water Availability</option>
          <option value="WATER_BASIC">Water Basic</option>
          <option value="CUSTOM" selected>Custom</option>
        </select>

        <label>Custom Label</label>
        <input name="custom_label" type="text" placeholder="Optional label">

        <label>Amount (R)</label>
        <input name="amount" type="number" step="0.01" required>

        <button type="submit" class="btn" style="margin-top:12px;">Save Fee</button>
      </form>
    </div>

    <h3 style="color:var(--accent2);margin-top:0;">Saved Fees</h3>
    <div id="feeList" class="fee-list"></div>
  </div>
  </section>

<!-- 2) TIERED TARIFFS -->
<section id="tiers" class="section">
  <div class="card">
    <h2>Tiered Tariffs</h2>

    <!-- Filter Tabs -->
    <div class="tabs" id="tierTypeTabs" style="margin-bottom:15px;">
      <div class="tab tier-filter active" data-type="">All</div>
      <div class="tab tier-filter" data-type="electricity">Electricity</div>
      <div class="tab tier-filter" data-type="water">Water</div>
    </div>

    <button class="btn cta" onclick="openTierModal()">+ Add Tier</button>
    <div id="tierList" class="tier-list" style="margin-top:20px;"></div>
  </div>
  </section>

<!-- 3) FEE MODES -->
<section id="modes" class="section">
  <div class="card">
    <h2>Fee Distribution Modes</h2>
    <form id="modeForm">
      <input type="hidden" name="action" value="save_fee_modes">
      <div id="modeRows"></div>
      <button type="submit" style="margin-top:12px;">Save Modes</button>
    </form>
    <div class="card" style="margin-top:16px;">
      <h3 style="margin-top:0;color:var(--accent2)">Preview Distribution</h3>
      <div class="grid" style="display:grid;grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:10px;">
        <div>
          <label>Amount (R)</label>
          <input id="previewAmount" type="number" step="0.01">
        </div>
        <div>
          <label>Mode</label>
          <select id="previewMode">
            <option value="flat">Flat</option>
            <option value="equal">Equal</option>
            <option value="proportional">Proportional (sqm)</option>
          </select>
        </div>
        <div>
          <label>Property (optional)</label>
          <select id="previewProperty">
            <option value="">All</option>
          </select>
        </div>
      </div>
      <button class="btn" style="margin-top:10px;" onclick="previewDistribution()">Preview</button>
      <div id="previewResult" style="margin-top:10px;"></div>
    </div>
  </div>
  </section>

<!-- 4) BILLING SETTINGS -->
<section id="settings" class="section">
  <div class="card">
    <h2>Live Billing Settings</h2>
    <form id="settingsForm">
      <input type="hidden" name="action" value="save_settings">
      <label>Tenant</label>
      <select name="tenant_id" id="settingsTenant">
        <option value="">Global</option>
      </select>

      <div class="grid" style="display:grid;grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:10px;">
        <div><label>Buy Rate (R/kWh)</label><input name="buy_rate" type="number" step="0.01"></div>
        <div><label>Sell Rate (R/kWh)</label><input name="sell_rate" type="number" step="0.01"></div>
        <div><label>KVA Cost (R)</label><input name="kva_cost" type="number" step="0.01"></div>
        <div><label>KVA Sell (R)</label><input name="kva_sell" type="number" step="0.01"></div>
        <div><label>Water Rate (R/kl)</label><input name="water_rate" type="number" step="0.01"></div>
        <div><label>Sewage Fee (R)</label><input name="sewage_fee" type="number" step="0.01"></div>
        <div><label>Refuse Removal Fee (R)</label><input name="refuse_removal_fee" type="number" step="0.01"></div>
        <div><label>Rates & Taxes (R)</label><input name="rates_and_taxes" type="number" step="0.01"></div>
        <div>
          <label>Display Mode</label>
          <select name="display_mode">
            <option value="accumulated">Accumulated</option>
            <option value="separate">Separate</option>
          </select>
        </div>

        <div><label>Other Fee Name 1</label><input name="other_fee_name" type="text"></div>
        <div><label>Other Fee 1 (R)</label><input name="other_fee" type="number" step="0.01"></div>
        <div><label>Other Fee Name 2</label><input name="other_fee_name_2" type="text"></div>
        <div><label>Other Fee 2 (R)</label><input name="other_fee_2" type="number" step="0.01"></div>
        <div><label>Other Fee Name 3</label><input name="other_fee_name_3" type="text"></div>
        <div><label>Other Fee 3 (R)</label><input name="other_fee_3" type="number" step="0.01"></div>
        <div><label>Other Fee Name 4</label><input name="other_fee_name_4" type="text"></div>
        <div><label>Other Fee 4 (R)</label><input name="other_fee_4" type="number" step="0.01"></div>
        <div><label>Other Fee Name 5</label><input name="other_fee_name_5" type="text"></div>
        <div><label>Other Fee 5 (R)</label><input name="other_fee_5" type="number" step="0.01"></div>
      </div>

      <button type="submit" style="margin-top:15px;">Save Settings</button>
    </form>

    <div class="card" style="margin-top:16px;">
      <h3 style="margin-top:0;color:var(--accent2)">Preview Per-Tenant Allocation</h3>
      <div class="grid" style="display:grid;grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:10px;">
        <div>
          <label>Property (optional)</label>
          <select id="settingsPreviewProperty">
            <option value="">All</option>
          </select>
        </div>
      </div>
      <button class="btn" style="margin-top:10px;" onclick="previewSettingsDistribution()">Preview Settings</button>
      <div id="settingsPreviewResult" style="margin-top:10px;"></div>
      <small style="color:#8aaec5;">Uses current values above and fee modes to simulate distribution before saving.</small>
    </div>
  </div>
  </section>

<!-- 5) HISTORY -->
<section id="history" class="section">
  <div class="card">
    <h2>Billing History</h2>
    <div id="historyList"></div>
  </div>
  </section>

<!-- TIER MODAL -->
<div id="tierModal" class="modal">
  <div class="modal-content">
    <div class="modal-header">
      <h3>Add Tier</h3>
      <span class="close" onclick="closeTierModal()">&times;</span>
    </div>
    <div class="modal-body">
      <form id="tierForm" style="grid-column: 1/-1;">
        <input type="hidden" name="action" value="save_tiers">
        <input type="hidden" name="tier_id" id="tier_id">

        <label>Type</label>
        <select name="type">
          <option value="electricity">Electricity</option>
          <option value="water">Water</option>
          <option value="generator">Generator</option>
          <option value="solar">Solar</option>
        </select>

        <label>Tenant</label>
        <select name="tenant_id" id="tierTenant">
          <option value="">Global</option>
        </select>

        <label>Block Name</label><input name="block_name" type="text">
        <label>From</label><input name="tier_from" type="number" step="0.01">
        <label>To</label><input name="tier_to" type="number" step="0.01">
        <label>Rate (R)</label><input name="rate" type="number" step="0.01">
        <label>Valid From</label><input name="valid_from" type="date">
        <label>Valid To</label><input name="valid_to" type="date">

        <button type="submit" class="btn" style="margin-top:12px;">Save Tier</button>
      </form>
    </div>
  </div>
</div>

<!-- Landlord scoping + API endpoint used by billing.js -->
<script>
const landlord_id = <?= $is_admin ? 'null' : (isset($_GET['landlord_id']) ? (int)$_GET['landlord_id'] : ($user_id ? (int)$user_id : 'null')) ?>;
const api = "billing-back.php";

<?php if ($is_admin): ?>
document.addEventListener('DOMContentLoaded', () => {
  const sel = document.getElementById('landlordSelect');
  if (!sel) return;
  sel.addEventListener('change', e => {
    const id = e.target.value;
    if (!id) return;
    window.landlord_id = parseInt(id, 10);
    if (typeof loadTenants === 'function') {
      loadTenants();
      loadFees();
      loadTiers();
      loadModes();
      loadSettings();
      loadHistory();
    }
    loadProperties();
  });
});
<?php endif; ?>

async function loadProperties(){
  try {
    if (!window.landlord_id) return;
    const res = await fetch(`${api}?action=get_properties&landlord_id=${window.landlord_id}`);
    const j = await res.json();
    if (j.status !== 'success' || !Array.isArray(j.data)) return;
    const sels = [document.getElementById('previewProperty'), document.getElementById('settingsPreviewProperty')];
    sels.forEach(sel => {
      if (!sel) return;
      sel.innerHTML = '<option value="">All</option>';
      j.data.forEach(p => {
        const o = document.createElement('option');
        o.value = p.id; o.textContent = p.property_number || (`Property #${p.id}`);
        sel.appendChild(o);
      });
    });
  } catch (e) {}
}

document.addEventListener('DOMContentLoaded', loadProperties);

async function previewDistribution(){
  const amtEl = document.getElementById('previewAmount');
  const modeEl = document.getElementById('previewMode');
  const propEl = document.getElementById('previewProperty');
  const amt = parseFloat(amtEl.value || '0');
  const mode = modeEl.value;
  const prop = propEl.value;
  if (!window.landlord_id) { alert('Select landlord first'); return; }
  if (!(amt > 0)) { alert('Enter amount'); return; }
  const q = new URLSearchParams({ action:'preview_distribution', amount:String(amt), mode, property_id: prop });
  q.set('landlord_id', window.landlord_id);
  const res = await fetch(`${api}?${q.toString()}`);
  const j = await res.json();
  const box = document.getElementById('previewResult');
  if (j.status !== 'success') { box.textContent = j.message || 'Error'; return; }
  if (!j.data || !j.data.length) { box.textContent = 'No tenants in scope.'; return; }
  let html = '<table><thead><tr><th>Tenant</th><th>Amount (R)</th></tr></thead><tbody>';
  j.data.forEach(r => { html += `<tr><td>${(r.tenant_name||('Tenant '+r.tenant_id))}</td><td>${Number(r.amount).toFixed(2)}</td></tr>`; });
  html += '</tbody></table>';
  box.innerHTML = html;
}

async function getFeeModes(){
  const res = await fetch(`${api}?action=get_fee_modes&landlord_id=${window.landlord_id||''}`);
  const j = await res.json();
  const modes = { sewage:'flat', refuse:'flat', rates:'flat', other:'flat' };
  if (j.status==='success' && Array.isArray(j.data)) {
    j.data.forEach(m => { modes[(m.fee_type||'').toLowerCase()] = m.mode; });
  }
  return modes;
}

async function previewSettingsDistribution(){
  if (!window.landlord_id) { alert('Select landlord first'); return; }
  const f = document.getElementById('settingsForm');
  const tenantSel = document.getElementById('settingsTenant');
  const tenantId = tenantSel?.value || '';
  const propId = document.getElementById('settingsPreviewProperty').value;
  const vals = Object.fromEntries(new FormData(f).entries());
  const fees = [
    { key:'sewage_fee', label:'Sewage Fee', modeKey:'sewage' },
    { key:'refuse_removal_fee', label:'Refuse Removal Fee', modeKey:'refuse' },
    { key:'rates_and_taxes', label:'Rates & Taxes', modeKey:'rates' },
    { key:'other_fee_1', label: (vals['other_fee_name_1']||'Other Fee 1'), modeKey:'other' },
    { key:'other_fee_2', label: (vals['other_fee_name_2']||'Other Fee 2'), modeKey:'other' },
    { key:'other_fee_3', label: (vals['other_fee_name_3']||'Other Fee 3'), modeKey:'other' },
    { key:'other_fee_4', label: (vals['other_fee_name_4']||'Other Fee 4'), modeKey:'other' },
    { key:'other_fee_5', label: (vals['other_fee_name_5']||'Other Fee 5'), modeKey:'other' },
  ];

  const resultBox = document.getElementById('settingsPreviewResult');
  resultBox.textContent = 'Calculating...';

  const allocations = {}; // tenant_id => { name, sewage, refuse, rates, other, total }

  // If tenant override selected, just show direct amounts to that tenant
  if (tenantId) {
    const tId = parseInt(tenantId,10);
    const tName = (window.tenants||[]).find(t => String(t.tenant_id)===String(tId))?.fullname || ('Tenant '+tId);
    allocations[tId] = { name: tName, sewage:0, refuse:0, rates:0, other:0, total:0 };
    fees.forEach(fee => {
      const amt = parseFloat(vals[fee.key]||'0')||0;
      if (amt>0) {
        const bucket = (fee.modeKey==='sewage')?'sewage':(fee.modeKey==='refuse')?'refuse':(fee.modeKey==='rates')?'rates':'other';
        allocations[tId][bucket] += amt;
        allocations[tId].total += amt;
      }
    });
  } else {
    // Global: distribute by modes
    const modes = await getFeeModes();
    for (const fee of fees) {
      const amt = parseFloat(vals[fee.key]||'0')||0;
      if (!(amt>0)) continue;
      const mode = modes[fee.modeKey] || 'flat';
      const q = new URLSearchParams({ action:'preview_distribution', amount:String(amt), mode, property_id: propId||'' });
      q.set('landlord_id', window.landlord_id);
      const res = await fetch(`${api}?${q.toString()}`);
      const j = await res.json();
      if (j.status!=='success' || !Array.isArray(j.data)) continue;
      j.data.forEach(row => {
        const tid = parseInt(row.tenant_id,10);
        if (!allocations[tid]) allocations[tid] = { name: row.tenant_name||('Tenant '+tid), sewage:0, refuse:0, rates:0, other:0, total:0 };
        const bucket = (fee.modeKey==='sewage')?'sewage':(fee.modeKey==='refuse')?'refuse':(fee.modeKey==='rates')?'rates':'other';
        allocations[tid][bucket] += parseFloat(row.amount)||0;
        allocations[tid].total += parseFloat(row.amount)||0;
      });
    }
  }

  // Render table
  const rows = Object.entries(allocations).sort((a,b)=>a[1].name.localeCompare(b[1].name));
  if (!rows.length) { resultBox.textContent = 'No fees to preview.'; return; }
  let html = '<table><thead><tr><th>Tenant</th><th>Sewage</th><th>Refuse</th><th>Rates</th><th>Other</th><th>Total</th></tr></thead><tbody>';
  rows.forEach(([tid, r]) => {
    html += `<tr><td>${r.name}</td><td>${r.sewage.toFixed(2)}</td><td>${r.refuse.toFixed(2)}</td><td>${r.rates.toFixed(2)}</td><td>${r.other.toFixed(2)}</td><td><b>${r.total.toFixed(2)}</b></td></tr>`;
  });
  html += '</tbody></table>';
  resultBox.innerHTML = html;
}
</script>
