<?php
// ============================================================
// properties.php — RBE Utilities Admin Property Management (v2.0)
// ------------------------------------------------------------
// Features:
//  - List, add, edit, and delete properties
//  - Enforces admin-only access
//  - Displays landlord and property details
//  - Supports area (m²) tracking for proportional billing
// ============================================================

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

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

// ------------------------------------------------------------
// 🛡️ Access Validation
// ------------------------------------------------------------
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'], true)) {
  exit('Access denied.');
}

// Sidebar per role
if ($role === 'admin') { include 'admin-nav.php'; } else { include 'landlord-nav.php'; }

// ------------------------------------------------------------
// ✏️ Add or Edit Property
// ------------------------------------------------------------
$message = "";

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $landlord_id = ($role === 'landlord') ? $user_id : (int)($_POST['landlord_id'] ?? 0);
  $property_number = trim($_POST['property_number'] ?? '');
  $address = trim($_POST['address'] ?? '');
  $square_meters = (float)($_POST['square_meters'] ?? 0);

  if (!$landlord_id || !$property_number || !$address) {
    $message = "❌ All fields are required.";
  } else {
    if (isset($_POST['add_property'])) {
      $stmt = $conn_rbe->prepare("
        INSERT INTO properties (landlord_id, property_number, address, square_meters)
        VALUES (?, ?, ?, ?)
      ");
      $stmt->execute([$landlord_id, $property_number, $address, $square_meters]);
      $message = "✅ Property added successfully.";
    }

    if (isset($_POST['edit_property'])) {
      $id = (int)$_POST['prop_id'];
      if ($role === 'landlord') {
        $stmt = $conn_rbe->prepare("UPDATE properties SET landlord_id=?, property_number=?, address=?, square_meters=? WHERE id=? AND landlord_id=?");
        $stmt->execute([$landlord_id, $property_number, $address, $square_meters, $id, $user_id]);
      } else {
        $stmt = $conn_rbe->prepare("UPDATE properties SET landlord_id=?, property_number=?, address=?, square_meters=? WHERE id=?");
        $stmt->execute([$landlord_id, $property_number, $address, $square_meters, $id]);
      }
      $message = "✅ Property updated successfully.";
    }
  }
}

// ------------------------------------------------------------
// 🧹 Delete Property
// ------------------------------------------------------------
if (isset($_GET['delete'])) {
  $id = (int)$_GET['delete'];

  // Clean up linked data (safe nulling)
  $conn_rbe->prepare("UPDATE smart_meters SET property_id=NULL WHERE property_id=?")->execute([$id]);
  $conn_rbe->prepare("UPDATE flecto_meters SET property_id=NULL WHERE property_id=?")->execute([$id]);
  $conn_rbe->prepare("UPDATE water_meters SET property_id=NULL WHERE property_id=?")->execute([$id]);

  $conn_rbe->prepare("DELETE FROM properties WHERE id=?")->execute([$id]);
  $message = "🗑️ Property deleted successfully.";
}

// ------------------------------------------------------------
// 📊 Fetch Data
// ------------------------------------------------------------
$landlords = $conn_rbe->query("
  SELECT u.id, u.fullname, u.email
  FROM rbe_users u
  JOIN rbe_roles r ON u.id=r.user_id
  WHERE r.role='landlord'
  ORDER BY u.fullname ASC
")->fetchAll(PDO::FETCH_ASSOC);

$properties = $conn_rbe->query("
  SELECT 
    p.id, 
    p.property_number,
    p.address,
    p.square_meters,
    p.created_at,
    u.fullname AS landlord_name,
    u.email AS landlord_email
  FROM properties p
  LEFT JOIN rbe_users u ON u.id=p.landlord_id
  ORDER BY p.created_at DESC
")->fetchAll(PDO::FETCH_ASSOC);

if ($role === 'landlord') {
  $stmt = $conn_rbe->prepare("SELECT p.id, p.property_number, p.address, p.square_meters, p.created_at, u.fullname AS landlord_name, u.email AS landlord_email FROM properties p LEFT JOIN rbe_users u ON u.id=p.landlord_id WHERE p.landlord_id=? ORDER BY p.created_at DESC");
  $stmt->execute([$user_id]);
  $properties = $stmt->fetchAll(PDO::FETCH_ASSOC);
}

// Edit mode
$edit_property = null;
if (isset($_GET['edit_id'])) {
  $stmt = $conn_rbe->prepare("SELECT * FROM properties WHERE id=?");
  $stmt->execute([(int)$_GET['edit_id']]);
  $edit_property = $stmt->fetch(PDO::FETCH_ASSOC);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Manage Properties — RBE Utilities</title>
<link rel="stylesheet" href="/assets/css/theme.css">
<link rel="stylesheet" href="modules/billing/billing.css">
<style>
.container { margin-left: 240px; padding: 40px; }
.sidebar-collapsed .container { margin-left: 72px; }
@media (max-width:900px){ .container{ margin-left:0; padding:20px; } }
.card { margin-bottom: 30px;
  max-width: 1100px;}
input, select { width: 100%; margin-bottom: 12px; }
.table-wrap { overflow-x: auto; }
.actions a { text-decoration: none; color: var(--accent2); margin-right: 10px; }
.actions a:hover { color: var(--accent); }
</style>
</head>
<body>

<div class="container">
  <h1>🏠 Manage Properties</h1>

  <?php if ($message): ?>
    <div class="status"><?= $message ?></div>
  <?php endif; ?>

  <div class="card">
    <?php if ($edit_property): ?>
      <h2>✏️ Edit Property #<?= htmlspecialchars($edit_property['id']) ?></h2>
      <form method="post">
        <input type="hidden" name="prop_id" value="<?= $edit_property['id'] ?>">

        <?php if ($role === 'admin'): ?>
          <label>Landlord</label>
          <select name="landlord_id" required>
            <option value="">Select landlord</option>
            <?php foreach ($landlords as $l): ?>
              <option value="<?= $l['id'] ?>" <?= $l['id']==$edit_property['landlord_id']?'selected':'' ?>>
                <?= htmlspecialchars($l['fullname']) ?> (<?= htmlspecialchars($l['email']) ?>)
              </option>
            <?php endforeach; ?>
          </select>
        <?php else: ?>
          <input type="hidden" name="landlord_id" value="<?= (int)$user_id ?>">
          <div class="muted">Landlord: You</div>
        <?php endif; ?>

        <label>Property Number</label>
        <input type="text" name="property_number" value="<?= htmlspecialchars($edit_property['property_number']) ?>" required>

        <label>Address</label>
        <input type="text" name="address" value="<?= htmlspecialchars($edit_property['address']) ?>" required>

        <label>Total Area (m²)</label>
        <input type="number" name="square_meters" step="0.01" value="<?= htmlspecialchars($edit_property['square_meters']) ?>" required>

        <button type="submit" name="edit_property">💾 Save Changes</button>
        <a href="properties.php" class="btn secondary" style="margin-top:10px;">Cancel</a>
      </form>
    <?php else: ?>
      <h2>➕ Add New Property</h2>
      <form method="post">
        <?php if ($role === 'admin'): ?>
          <label>Landlord</label>
          <select name="landlord_id" required>
            <option value="">Select landlord</option>
            <?php foreach ($landlords as $l): ?>
              <option value="<?= $l['id'] ?>"><?= htmlspecialchars($l['fullname']) ?> (<?= htmlspecialchars($l['email']) ?>)</option>
            <?php endforeach; ?>
          </select>
        <?php else: ?>
          <input type="hidden" name="landlord_id" value="<?= (int)$user_id ?>">
          <div class="muted">Landlord: You</div>
        <?php endif; ?>

        <label>Property Number</label>
        <input type="text" name="property_number" placeholder="e.g. Shop 12" required>

        <label>Address</label>
        <input type="text" name="address" placeholder="Full property address" required>

        <label>Total Area (m²)</label>
        <input type="number" name="square_meters" step="0.01" placeholder="e.g. 120.5">

        <button type="submit" name="add_property">Add Property</button>
      </form>
    <?php endif; ?>
  </div>

  <div class="card">
    <h2>🏢 Existing Properties</h2>
    <div class="table-wrap">
      <table>
        <thead>
          <tr>
            <th>ID</th>
            <th>Property</th>
            <th>Address</th>
            <th>Landlord</th>
            <th>Area (m²)</th>
            <th>Created</th>
            <th>Actions</th>
          </tr>
        </thead>
        <tbody>
          <?php if ($properties): ?>
            <?php foreach ($properties as $p): ?>
              <tr>
                <td><?= $p['id'] ?></td>
                <td><?= htmlspecialchars($p['property_number']) ?></td>
                <td><?= htmlspecialchars($p['address']) ?></td>
                <td><?= htmlspecialchars($p['landlord_name'] ?? '—') ?></td>
                <td><?= rtrim(rtrim($p['square_meters'], '0'), '.') ?></td>
                <td><?= $p['created_at'] ?></td>
                <td class="actions">
                  <a href="?edit_id=<?= $p['id'] ?>">✏️ Edit</a>
                  <a href="?delete=<?= $p['id'] ?>" style="color:var(--danger)" onclick="return confirm('Delete this property?')">🗑️ Delete</a>
                </td>
              </tr>
            <?php endforeach; ?>
          <?php else: ?>
            <tr><td colspan="7" style="text-align:center;color:var(--muted)">No properties found.</td></tr>
          <?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

</body>
</html>
