<?php
// ============================================================
// admin-meters.php — RBE Utilities Admin Meter Management
// ============================================================

require_once __DIR__ . '/core/db_connect.php';

if (session_status() === PHP_SESSION_NONE) { session_start(); }

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

$flash_msg = $flash_err = "";

// ============================================================
// 🟢 Add IAMMETER Meter
// ============================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_iam_meter'])) {
    $serial = trim($_POST['meter_serial'] ?? '');
    $phases = intval($_POST['phases'] ?? 0);
    $property_id = intval($_POST['property_id'] ?? 0);
    $landlord_id = intval($_POST['landlord_id'] ?? 0);
    $tenant_id = intval($_POST['tenant_id'] ?? 0);

    if ($serial && $phases && $property_id && $landlord_id && $tenant_id) {
        $stmt = $conn_rbe->prepare("
            INSERT INTO smart_meters (serial, phases, property_id, landlord_id, tenant_id, source_type, meter_type)
            VALUES (?, ?, ?, ?, ?, 'IAMMETER', 'electricity')
        ");
        $stmt->execute([$serial, $phases, $property_id, $landlord_id, $tenant_id]);
        $flash_msg = "✅ IAMMETER meter added successfully!";
    } else {
        $flash_err = "❌ Please complete all fields before submitting.";
    }
}

// ============================================================
// 🔌 Add FLECTO Meter
// ============================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_flecto_meter'])) {
    $serial = trim($_POST['serial_number'] ?? '');
    $desc = trim($_POST['description'] ?? '');
    $property_id = intval($_POST['property_id'] ?? 0);
    $landlord_id = intval($_POST['landlord_id'] ?? 0);
    $tenant_id = intval($_POST['tenant_id'] ?? 0);

    if ($serial && $desc && $property_id && $landlord_id && $tenant_id) {
        $stmt = $conn_rbe->prepare("
            INSERT INTO flecto_meters (serial_number, description, property_id, landlord_id, tenant_id, is_active)
            VALUES (?, ?, ?, ?, ?, 1)
        ");
        $stmt->execute([$serial, $desc, $property_id, $landlord_id, $tenant_id]);
        $flash_msg = "✅ FLECTO meter added successfully!";
    } else {
        $flash_err = "❌ Please fill in all required fields.";
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Meter Management</title>
<link rel="stylesheet" href="/assets/css/theme.css">
<link rel="stylesheet" href="/assets/css/admin.css">
<style>
.wrap { padding:30px; margin-left:260px; }
h1 { margin-bottom:10px; }

.card {
  background:#0b2333;
  border-radius:14px;
  padding:20px;
  margin-bottom:25px;
  box-shadow:0 0 12px rgba(0,0,0,0.35);
}

.card h3 { margin-top:0; color:var(--accent2); }

.form-grid {
  display:grid;
  grid-template-columns:repeat(auto-fit,minmax(180px,1fr));
  gap:12px;
  margin-bottom:16px;
}

input, select {
  padding:10px;
  border-radius:6px;
  border:none;
  background:rgba(255,255,255,0.05);
  color:#fff;
}

.btn-primary {
  background:var(--accent2);
  padding:10px 18px;
  border:none;
  border-radius:6px;
  cursor:pointer;
  font-weight:600;
  color:#000;
}
.btn-primary:hover { background:var(--accent); }

.alert {
  padding:10px 15px;
  border-radius:6px;
  margin-bottom:15px;
}
.alert.ok { background:#0f3b2a; color:#b6ffd0; }
.alert.err { background:#3b0f0f; color:#ffd7d7; }

.back-btn {
  display:inline-block;
  margin-bottom:20px;
  background:var(--accent2);
  padding:8px 16px;
  border-radius:6px;
  color:#000;
  text-decoration:none;
  font-weight:600;
}
.back-btn:hover { background:var(--accent); }
</style>
</head>
<body>

<div class="wrap">

  <!-- Back button to meters list -->
  <a href="admin-meters-list.php" class="back-btn">⬅ Back to Meters List</a>

  <h1>⚙️ Meter Management</h1>

  <?php if ($flash_msg): ?>
      <div class="alert ok"><?= htmlspecialchars($flash_msg) ?></div>
  <?php elseif ($flash_err): ?>
      <div class="alert err"><?= htmlspecialchars($flash_err) ?></div>
  <?php endif; ?>

  <!-- IAMMETER -->
  <div class="card">
    <h3>⚡ Add IAMMETER Meter</h3>
    <form method="POST">
      <div class="form-grid">
        <input type="text" name="meter_serial" placeholder="Meter Serial" required>
        <input type="number" name="phases" placeholder="Phases (1 or 3)" required>
        <select name="property_id" required>
          <option value="">Assign to Property</option>
          <?php
          $stmt = $conn_rbe->query("SELECT id, property_number FROM properties ORDER BY property_number ASC");
          while ($p = $stmt->fetch()) echo "<option value='{$p['id']}'>{$p['property_number']}</option>";
          ?>
        </select>
        <select name="landlord_id" required>
          <option value="">Assign to Landlord</option>
          <?php
          $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'
          ");
          while ($ll = $stmt->fetch()) echo "<option value='{$ll['id']}'>{$ll['fullname']}</option>";
          ?>
        </select>
        <select name="tenant_id" required>
          <option value="">Assign to Tenant</option>
          <?php
          $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 = 'tenant'
          ");
          while ($t = $stmt->fetch()) echo "<option value='{$t['id']}'>{$t['fullname']}</option>";
          ?>
        </select>
      </div>
      <button type="submit" name="add_iam_meter" class="btn-primary">Add IAMMETER Meter</button>
    </form>
  </div>

  <!-- WATER -->
  <div class="card">
    <h3>💧 Add WATER Meter</h3>
    <form method="POST" action="add_water_meter.php">
      <div class="form-grid">
        <input type="text" name="serial_number" placeholder="Water Meter Serial" required>
        <input type="text" name="description" placeholder="Description">
        <select name="property_id" required>
          <option value="">Assign to Property</option>
          <?php
          $stmt = $conn_rbe->query("SELECT id, property_number FROM properties");
          while ($p = $stmt->fetch()) echo "<option value='{$p['id']}'>{$p['property_number']}</option>";
          ?>
        </select>
        <select name="landlord_id" required>
          <option value="">Assign to Landlord</option>
          <?php
          $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'
          ");
          while ($ll = $stmt->fetch()) echo "<option value='{$ll['id']}'>{$ll['fullname']}</option>";
          ?>
        </select>
        <select name="tenant_id" required>
          <option value="">Assign to Tenant</option>
          <?php
          $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 = 'tenant'
          ");
          while ($t = $stmt->fetch()) echo "<option value='{$t['id']}'>{$t['fullname']}</option>";
          ?>
        </select>
      </div>
      <button type="submit" class="btn-primary">Add WATER Meter</button>
    </form>
  </div>

  <!-- FLECTO -->
  <div class="card">
    <h3>🔌 Add FLECTO Meter</h3>
    <form method="POST">
      <div class="form-grid">
        <input type="text" name="serial_number" placeholder="Flecto Serial" required>
        <input type="text" name="description" placeholder="Description" required>
        <select name="property_id" required>
          <option value="">Assign to Property</option>
          <?php
          $stmt = $conn_rbe->query("SELECT id, property_number FROM properties");
          while ($p = $stmt->fetch()) echo "<option value='{$p['id']}'>{$p['property_number']}</option>";
          ?>
        </select>
        <select name="landlord_id" required>
          <option value="">Assign to Landlord</option>
          <?php
          $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'
          ");
          while ($ll = $stmt->fetch()) echo "<option value='{$ll['id']}'>{$ll['fullname']}</option>";
          ?>
        </select>
        <select name="tenant_id" required>
          <option value="">Assign to Tenant</option>
          <?php
          $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 = 'tenant'
          ");
          while ($t = $stmt->fetch()) echo "<option value='{$t['id']}'>{$t['fullname']}</option>";
          ?>
        </select>
      </div>
      <button type="submit" name="add_flecto_meter" class="btn-primary">Add FLECTO Meter</button>
    </form>
  </div>

</div>
</body>
</html>
