<?php
// ============================================================
// billing.php — RBE Utilities Billing Console (v9)
// ------------------------------------------------------------
// Role: Admin + Landlord
// Backend: billing-back.php (v9)
// Frontend logic: billing.js
// Theme: Inline RBE Utilities dark design
// ============================================================

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

session_start();
require_once __DIR__ . '/../../core/db_connect.php';

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

$user_id = (int)$_SESSION['user_id'];
$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'])) {
    echo "<div style='padding:40px;color:red;font-family:sans-serif;'>Access denied.</div>";
    exit;
}

$is_admin = ($role === 'admin');

// Sidebar
if ($is_admin) {
    @include __DIR__ . '/../../admin-nav.php';
} else {
    @include __DIR__ . '/../../landlord-nav.php';
}

// Fetch landlord list for admin dropdown
$landlords = [];
if ($is_admin) {
    $stmt = $conn_rbe->query("
        SELECT u.id, u.fullname 
        FROM rbe_users u 
        JOIN rbe_roles r ON u.id=r.user_id 
        WHERE r.role='landlord'
        ORDER BY u.fullname ASC
    ");
    $landlords = $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.0">
<title>RBE Utilities — Billing Console</title>
<link rel="stylesheet" href="/assets/css/theme.css">

<style>
/* ==========================================================
   RBE Utilities Unified Inline Theme (v9)
   ========================================================== */
:root {
  --bg: linear-gradient(180deg,#041622 0%,#071b2c 100%);
  --bg-light: #0c2536;
  --card: #0f2e44;
  --accent: #7ed957;
  --accent2: #00ccff;
  --text: #e6f5ff;
  --muted: #8aaec5;
  --danger: #ff5b5b;
  --radius: 12px;
  --shadow: 0 0 14px rgba(0,0,0,0.35);
  --transition: 0.25s ease;
  --font: 'Inter','Segoe UI',sans-serif;
}

body {
  margin:0;
  font-family:var(--font);
  background:var(--bg);
  color:var(--text);
  min-height:100vh;
  /* Offset for fixed sidebar */
  margin-left: 240px;
}

/* Collapse + responsive adjustments for sidebar */
@media (max-width: 900px) {
  body { margin-left: 0; }
}
body.sidebar-collapsed { margin-left: 72px; }
@media (max-width: 900px) {
  body.sidebar-collapsed { margin-left: 0; }
}

/* Navbar */
.navbar {
  display:flex;
  justify-content:space-between;
  align-items:center;
  background:linear-gradient(90deg,#062235,#08314d);
  padding:16px 28px;
  box-shadow:var(--shadow);
}
.navbar h1 {
  font-size:18px;
  color:var(--accent2);
  margin:0;
}
.navbar select {
  padding:8px 12px;
  border-radius:8px;
  border:1px solid var(--accent2);
  background:#0c2536;
  color:var(--text);
}

/* Tabs */
.tabs {
  display:flex;
  justify-content:center;
  flex-wrap:wrap;
  border-bottom:1px solid rgba(255,255,255,0.08);
  gap:8px;
  margin:24px 0;
}
.tab {
  padding:10px 18px;
  cursor:pointer;
  color:var(--muted);
  font-weight:600;
  border-radius:30px;
  transition:var(--transition);
}
.tab.active {
  background:rgba(0,255,255,0.1);
  color:var(--accent);
  border:1px solid rgba(126,217,87,0.25);
}

/* Card Layout */
.card {
  background:var(--card);
  border-radius:var(--radius);
  padding:22px 28px;
  box-shadow:var(--shadow);
  margin:0 auto 25px auto;
  max-width:1100px;
  transition:var(--transition);
}
.card h2 {
  color:var(--accent2);
  margin-top:0;
}
.card:hover { box-shadow:0 0 18px rgba(0,255,255,0.12); }

/* Buttons */
button, .btn {
  background:linear-gradient(90deg,#7ed957 0%,#9eff6d 100%);
  color:#0a1b25;
  font-weight:600;
  border:none;
  border-radius:30px;
  padding:10px 22px;
  cursor:pointer;
  transition:var(--transition);
}
button:hover, .btn:hover { transform:translateY(-1px); box-shadow:0 0 10px rgba(126,217,87,0.4); }
.btn.secondary {
  background:transparent;
  color:var(--accent2);
  border:1px solid var(--accent2);
}
.btn.secondary:hover { background:rgba(0,255,255,0.1); }

/* Tables */
table {
  width:100%;
  border-collapse:collapse;
  color:var(--text);
  margin-top:10px;
}
th,td {
  padding:8px 10px;
  border-bottom:1px solid rgba(255,255,255,0.08);
  text-align:left;
}
th { background:#123a4f; color:var(--accent); }

/* Loader Overlay */
#loader {
  display:none;
  position:fixed;
  top:0; left:0;
  width:100%; height:100%;
  background:rgba(0,0,0,0.6);
  z-index:999;
  justify-content:center;
  align-items:center;
  color:var(--accent2);
  font-size:18px;
  font-weight:600;
  letter-spacing:0.5px;
}

/* Modal */
.modal {
  display:none;
  position:fixed;
  top:0; left:0;
  width:100%; height:100%;
  background:rgba(0,0,0,0.75);
  justify-content:center;
  align-items:center;
  z-index:1000;
}
.modal-content {
  background:#10283f;
  border-radius:16px;
  padding:24px 26px 22px;
  width:95%;
  max-width:720px;
  color:var(--text);
  box-shadow:0 0 24px rgba(0,255,255,0.22);
  border:1px solid rgba(255,255,255,0.06);
}
.modal-header {
  display:flex;
  align-items:center;
  justify-content:space-between;
  margin-bottom:14px;
}
.modal-header h2 {
  margin:0;
  font-size:18px;
  color:var(--accent2);
}
.close {
  background:transparent;
  border:none;
  cursor:pointer;
  color:var(--accent2);
  font-size:22px;
  padding:2px 6px;
  line-height:1;
}
.close:hover {
  color:var(--accent);
  transform:scale(1.05);
}
.modal-body {
  display:grid;
  gap:14px 16px;
  grid-template-columns:repeat(auto-fit,minmax(220px,1fr));
  margin-bottom:16px;
}
.modal-field {
  display:flex;
  flex-direction:column;
}
.modal-field label {
  font-size:13px;
  color:var(--muted);
  margin-bottom:4px;
}
.modal-field input,
.modal-field select {
  width:100%;
  padding:8px 10px;
  border-radius:8px;
  border:1px solid rgba(126,217,87,0.25);
  background:#0b2234;
  color:var(--text);
  font-size:14px;
}
.modal-field input:focus,
.modal-field select:focus {
  outline:none;
  border-color:var(--accent);
  box-shadow:0 0 5px rgba(126,217,87,0.4);
}
.modal-actions {
  display:flex;
  justify-content:flex-end;
}

.section { display:none; max-width:1100px; margin:0 auto; padding:20px; }
.section.active { display:block; }

</style>
</head>
<body>

<div class="navbar">
  <h1>RBE Utilities — Billing Console</h1>
  <?php if ($is_admin): ?>
    <div>
      <label for="landlordSelect" style="margin-right:8px;">Select Landlord:</label>
      <select id="landlordSelect">
        <option value="">-- Select Landlord --</option>
        <?php foreach ($landlords as $l): ?>
          <option value="<?= htmlspecialchars($l['id']) ?>"><?= htmlspecialchars($l['fullname']) ?></option>
        <?php endforeach; ?>
      </select>
    </div>
  <?php endif; ?>
</div>

<div class="tabs">
  <div class="tab active" data-tab="fees">Extra Utility 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">Billing Settings</div>
  <div class="tab" data-tab="history">Version History</div>
</div>

<div id="loader">Loading Data...</div>

<!-- ==========================
     FEES TAB
=========================== -->
<div id="fees" class="section active">
  <div class="card">
    <h2>Extra Utility Fees</h2>
    <form id="feeForm">
      <div style="display:grid;gap:12px;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));">
        <select name="tenant_id" id="tenantSelect" required>
          <option value="">Select Tenant</option>
        </select>
        <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 Charge</option>
          <option value="WATER_AVAILABILITY">Water Availability</option>
          <option value="WATER_BASIC">Water Basic Charge</option>
          <option value="CUSTOM">Custom</option>
        </select>
        <input name="custom_label" placeholder="Custom Label (optional)">
        <input type="number" step="0.01" name="amount" placeholder="Amount (R)" required>
        <button type="submit">Save Fee</button>
      </div>
    </form>
    <div id="feeList" class="fee-list" style="margin-top:20px;"></div>
  </div>
</div>

<!-- ==========================
     TIERS TAB
=========================== -->
<div id="tiers" class="section">
  <div class="card">
    <h2>Tiered Tariffs</h2>
    <div style="margin-bottom:15px;">
      <button onclick="openTierModal()">+ Add Tier</button>
    </div>
    <div style="display:flex;gap:8px;justify-content:center;margin-bottom:20px;">
      <button class="btn secondary tier-filter active" data-type="">All</button>
      <button class="btn secondary tier-filter" data-type="electricity">Electricity</button>
      <button class="btn secondary tier-filter" data-type="water">Water</button>
      <button class="btn secondary tier-filter" data-type="generator">Generator</button>
      <button class="btn secondary tier-filter" data-type="solar">Solar</button>
    </div>
    <div id="tierList"></div>
  </div>
</div>

<!-- ==========================
     MODES TAB
=========================== -->
<div id="modes" class="section">
  <div class="card">
    <h2>Fee Distribution Modes</h2>
    <form id="modeForm">
      <div id="modeRows" style="display:grid;gap:12px;"></div>
      <button type="submit" style="margin-top:16px;">Save Modes</button>
    </form>
  </div>
</div>

<!-- ==========================
     SETTINGS TAB
=========================== -->
<div id="settings" class="section">
  <div class="card">
    <h2>Billing Settings</h2>
    <p style="font-size:13px; color:var(--muted); margin:4px 0 14px;">
      Electricity Buy/Sell apply to <strong>municipal grid</strong> energy. KVA fields are for demand charges.
      Water Rate is per kL. Sewage / Refuse / Rates &amp; Taxes are <strong>monthly fixed fees</strong> per tenant.
      “Other Fee Name” + “Other Fee” lets you add one extra fixed utility fee (e.g. metering or admin).
      Use the tenant dropdown to switch between a <strong>Global</strong> default and per-tenant overrides.
    </p>
    <form id="settingsForm">
      <div style="display:grid;gap:12px;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));">
        <select id="settingsTenant" name="tenant_id">
          <option value="">Global (All Tenants)</option>
        </select>
        <input type="number" name="buy_rate" step="0.01" placeholder="Electricity Buy Rate (R/kWh)">
        <input type="number" name="sell_rate" step="0.01" placeholder="Electricity Sell Rate (R/kWh)">
        <input type="number" name="kva_cost" step="0.01" placeholder="KVA Cost (R)">
        <input type="number" name="kva_sell" step="0.01" placeholder="KVA Sell (R)">
        <input type="number" name="water_rate" step="0.01" placeholder="Water Rate (R/kl)">
        <input type="number" name="sewage_fee" step="0.01" placeholder="Sewage Fee (R)">
        <input type="number" name="refuse_removal_fee" step="0.01" placeholder="Refuse Removal (R)">
        <input type="number" name="rates_and_taxes" step="0.01" placeholder="Rates & Taxes (R)">
        <input name="other_fee_name" placeholder="Other Fee Name (e.g. Metering)">
        <input type="number" name="other_fee" step="0.01" placeholder="Other Fee (R/month)">
      </div>
      <button type="submit" style="margin-top:20px;">Save Settings</button>
    </form>
  </div>
</div>

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

<!-- ==========================
     TIER MODAL
=========================== -->
<div id="tierModal" class="modal">
  <div class="modal-content">
    <div class="modal-header">
      <h2 id="tierModalTitle">Add Tier</h2>
      <button type="button" class="close" onclick="closeTierModal()">&times;</button>
    </div>
    <form id="tierForm">
      <input type="hidden" name="tier_id" id="tierId">
      <div class="modal-body">
        <div class="modal-field">
          <label for="tierTenant">Tenant Scope</label>
          <select name="tenant_id" id="tierTenant">
            <option value="">Global (All Tenants)</option>
          </select>
        </div>
        <div class="modal-field">
          <label for="tierType">Utility Type</label>
          <select name="type" id="tierType">
            <option value="electricity">Electricity</option>
            <option value="water">Water</option>
            <option value="generator">Generator</option>
            <option value="solar">Solar</option>
          </select>
        </div>
        <div class="modal-field">
          <label for="tierBlock">Block Name</label>
          <input id="tierBlock" name="block_name" placeholder="e.g. Tier 1 (0–50 kWh)">
        </div>
        <div class="modal-field">
          <label for="tierFrom">From</label>
          <input id="tierFrom" type="number" step="0.01" name="tier_from" placeholder="From (kWh/kl)">
        </div>
        <div class="modal-field">
          <label for="tierTo">To</label>
          <input id="tierTo" type="number" step="0.01" name="tier_to" placeholder="To (kWh/kl)">
        </div>
        <div class="modal-field">
          <label for="tierRate">Rate</label>
          <input id="tierRate" type="number" step="0.01" name="rate" placeholder="Rate (R)">
        </div>
      </div>
      <div class="modal-actions">
        <button type="submit">Save Tier</button>
      </div>
    </form>
  </div>
</div>

<!-- ==========================
     SCRIPT LINKS
=========================== -->
<script>
  const api = "billing-back.php";
  // Current landlord scope:
  // - For landlords: their own user/landlord id
  // - For admins: null until a landlord is selected from the dropdown
  var landlord_id = <?= $is_admin ? 'null' : (int)$user_id ?>;
  window.landlord_id = landlord_id;

  // Loader toggles
  function showLoader() { document.getElementById('loader').style.display = 'flex'; }
  function hideLoader() { document.getElementById('loader').style.display = 'none'; }

  // Hook landlord selector (admin)
  <?php if ($is_admin): ?>
  document.addEventListener("DOMContentLoaded", () => {
    const sel = document.getElementById('landlordSelect');
    if (!sel) return;
    sel.addEventListener('change', e => {
      const id = e.target.value ? parseInt(e.target.value, 10) : null;
      if (!id) return;
      // keep both the global variable and window-scoped id in sync
      landlord_id = window.landlord_id = id;
      showLoader();
      setTimeout(() => {
        hideLoader();
        loadTenants();
        loadFees();
        loadTiers();
        loadModes();
        loadSettings();
        loadHistory();
      }, 300);
    });
  });
  <?php else: ?>
  // Ensure window.landlord_id is set when a landlord user opens the page
  document.addEventListener("DOMContentLoaded", () => {
    window.landlord_id = landlord_id;
  });
  <?php endif; ?>
</script>
<script src="billing.js?v=9"></script>
</body>
</html>
