<?php
require_once __DIR__ . '/../db_connect.php';
session_start();

$user_id = $_SESSION['user_id'] ?? 0;

// Role check
$role = $conn_rbe->prepare("SELECT role FROM rbe_roles WHERE user_id=?");
$role->execute([$user_id]);
if ($role->fetchColumn() !== 'agent') die("Access denied");

// Agent details (pull company/phone from rbe_users for consistency)
$agent = $conn_rbe->prepare("
  SELECT u.fullname, u.email, u.company, u.phone, r.commission_rate
  FROM rbe_users u
  LEFT JOIN rbe_agents r ON r.user_id=u.id
  WHERE u.id=?
");
$agent->execute([$user_id]);
$agent = $agent->fetch(PDO::FETCH_ASSOC) ?: [];

// Flash messages from redirects
$flash_ok = '';
if (isset($_GET['added']) && $_GET['added'] == 1) {
    $flash_ok = "Property added successfully.";
}
if (isset($_GET['landlord']) && $_GET['landlord'] == 1) {
    $flash_ok = "Landlord added successfully.";
}
if (isset($_GET['meter'])) {
    $flash_ok = strtoupper($_GET['meter']) . " meter added successfully.";
}

/* ---------- Data fetch ---------- */

// Properties managed by this agent (landlord may be NULL)
$q = $conn_rbe->prepare("
    SELECT p.id, p.property_number, p.address, 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.agent_id=?
    ORDER BY p.created_at DESC
");
$q->execute([$user_id]);
$properties = $q->fetchAll(PDO::FETCH_ASSOC);

// Landlords connected via this agent’s properties (skip NULL)
$q = $conn_rbe->prepare("
    SELECT DISTINCT u.id, u.fullname, u.email, u.phone
    FROM properties p
    JOIN rbe_users u ON u.id = p.landlord_id
    WHERE p.agent_id=? AND p.landlord_id IS NOT NULL
    ORDER BY u.fullname
");
$q->execute([$user_id]);
$landlords = $q->fetchAll(PDO::FETCH_ASSOC);

// Smart Meters
$q = $conn_rbe->prepare("
    SELECT s.id, s.serial, s.meter_type, s.meter_units, s.property_id,
           p.property_number, u.fullname AS landlord_name
    FROM smart_meters s
    LEFT JOIN properties p ON p.id=s.property_id
    LEFT JOIN rbe_users u ON u.id=s.landlord_id
    WHERE s.agent_id=?
    ORDER BY s.created_at DESC
");
$q->execute([$user_id]);
$smart_meters = $q->fetchAll(PDO::FETCH_ASSOC);

// Flecto Meters
$q = $conn_rbe->prepare("
    SELECT f.id, f.serial_number, f.description, f.property_id,
           p.property_number, u.fullname AS landlord_name
    FROM flecto_meters f
    LEFT JOIN properties p ON p.id=f.property_id
    LEFT JOIN rbe_users u ON u.id=f.landlord_id
    WHERE f.agent_id=?
    ORDER BY f.created_at DESC
");
$q->execute([$user_id]);
$flecto_meters = $q->fetchAll(PDO::FETCH_ASSOC);

// Water Meters
$q = $conn_rbe->prepare("
    SELECT w.id, w.serial_number, w.description, w.property_id,
           p.property_number, u.fullname AS landlord_name
    FROM water_meters w
    LEFT JOIN properties p ON p.id=w.property_id
    LEFT JOIN rbe_users u ON u.id=w.landlord_id
    WHERE w.agent_id=?
    ORDER BY w.created_at DESC
");
$q->execute([$user_id]);
$water_meters = $q->fetchAll(PDO::FETCH_ASSOC);
?>

<link rel="stylesheet" href="/agents/includes/styles.css">
<style>
.btn {
  display:inline-block;
  margin:8px 0;
  padding:8px 14px;
  background:#7ed957;
  color:#fff;
  font-weight:600;
  border-radius:6px;
  text-decoration:none;
}
.btn:hover { background:#5cbf47; }
.success {color:green;font-weight:600; margin:10px 0;}

/* Action buttons */
.btn-action {
  display:inline-block;
  padding:6px 12px;
  margin:2px;
  font-size:0.85em;
  font-weight:600;
  border-radius:6px;
  text-decoration:none;
  color:#fff;
  transition:background 0.2s ease, transform 0.1s ease;
}
.btn-action:hover { transform:translateY(-1px); }

.btn-view { background:#3498db; }
.btn-view:hover { background:#2176b5; }

.btn-edit { background:#e67e22; }
.btn-edit:hover { background:#ca650f; }

.btn-delete { background:#c0392b; }
.btn-delete:hover { background:#962d22; }
</style>

<header>
  <img src="https://rbelectrical.enterprises/wp-content/uploads/2024/07/RBE-Electrical-Logo-clear2-250x125.png" class="logo" alt="Logo">
  <div class="title-group">
    <h1>Welcome</h1>
    <h2><?=htmlspecialchars($agent['fullname'] ?? 'Unknown Agent')?></h2>
    <?php if (!empty($agent['company'])): ?>
      <p><?=htmlspecialchars($agent['company'])?></p>
    <?php endif; ?>
    <p><?=htmlspecialchars($agent['email'] ?? '')?></p>
  </div>
</header>

<nav class="nav">
  <a href="/agents/dashboard.php">Dashboard</a>
  <a href="/agents/manage.php" class="active">My Clients</a>
  <a href="/agents/commissions.php">Commissions</a>
  <a href="/agents/profile.php">Profile</a>
  <a href="/logout.php">Logout</a>
</nav>

<section class="section">
  <h2>My Properties</h2>
  <a class="btn" href="/agents/add-property.php">➕ Add Property</a>
  <?php if ($flash_ok): ?><p class="success"><?=$flash_ok?></p><?php endif; ?>
  <?php if ($properties): ?>
    <table>
      <tr><th>ID</th><th>Property</th><th>Address</th><th>Landlord</th><th>Email</th><th>Date Added</th><th>Actions</th></tr>
      <?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><?=htmlspecialchars($p['landlord_email'] ?? '—')?></td>
        <td><?=date("Y-m-d", strtotime($p['created_at']))?></td>
        <td>
          <a href="/property-details.php?id=<?=$p['id']?>" class="btn-action btn-view">View</a>
          <a href="/agents/edit-property.php?id=<?=$p['id']?>" class="btn-action btn-edit">Edit</a>
        </td>
      </tr>
      <?php endforeach; ?>
    </table>
  <?php else: ?><p>No properties assigned.</p><?php endif; ?>
</section>

<section class="section">
  <h2>My Landlords</h2>
  <a class="btn" href="/agents/add-landlord.php">➕ Add Landlord</a>
  <?php if ($landlords): ?>
    <table>
      <tr><th>ID</th><th>Name</th><th>Email</th><th>Phone</th><th>Actions</th></tr>
      <?php foreach($landlords as $l): ?>
      <tr>
        <td><?=$l['id']?></td>
        <td><?=htmlspecialchars($l['fullname'])?></td>
        <td><?=htmlspecialchars($l['email'])?></td>
        <td><?=htmlspecialchars($l['phone'] ?? '-')?></td>
        <td>
          <a href="/landlord-dashboard.php?id=<?=$l['id']?>" class="btn-action btn-view">View</a>
          <a href="/edit-landlord.php?id=<?=$l['id']?>" class="btn-action btn-edit">Edit</a>
        </td>
      </tr>
      <?php endforeach; ?>
    </table>
  <?php else: ?><p>No landlords assigned.</p><?php endif; ?>
</section>

<section class="section">
  <h2>My Smart Meters (IAMMETER)</h2>
  <a class="btn" href="/agents/add-meter.php?type=smart">➕ Add Smart Meter</a>
  <?php if ($smart_meters): ?>
    <table>
      <tr><th>ID</th><th>Serial</th><th>Type</th><th>Property</th><th>Landlord</th><th>Actions</th></tr>
      <?php foreach($smart_meters as $m): ?>
      <tr>
        <td><?=$m['id']?></td>
        <td><?=htmlspecialchars($m['serial'])?></td>
        <td><?=htmlspecialchars($m['meter_type']." (".$m['meter_units'].")")?></td>
        <td><?=htmlspecialchars($m['property_number'] ?? '-')?></td>
        <td><?=htmlspecialchars($m['landlord_name'] ?? '-')?></td>
        <td>
          <a href="/meter-details.php?id=<?=$m['id']?>" class="btn-action btn-view">View</a>
        </td>
      </tr>
      <?php endforeach; ?>
    </table>
  <?php else: ?><p>No IAMMETER meters assigned.</p><?php endif; ?>
</section>

<section class="section">
  <h2>My Flecto Meters</h2>
  <a class="btn" href="/agents/add-meter.php?type=flecto">➕ Add Flecto Meter</a>
  <?php if ($flecto_meters): ?>
    <table>
      <tr><th>ID</th><th>Serial</th><th>Description</th><th>Property</th><th>Landlord</th><th>Actions</th></tr>
      <?php foreach($flecto_meters as $m): ?>
      <tr>
        <td><?=$m['id']?></td>
        <td><?=htmlspecialchars($m['serial_number'])?></td>
        <td><?=htmlspecialchars($m['description'] ?? '-')?></td>
        <td><?=htmlspecialchars($m['property_number'] ?? '-')?></td>
        <td><?=htmlspecialchars($m['landlord_name'] ?? '-')?></td>
        <td>
          <a href="/meter-details.php?type=flecto&id=<?=$m['id']?>" class="btn-action btn-view">View</a>
        </td>
      </tr>
      <?php endforeach; ?>
    </table>
  <?php else: ?><p>No Flecto meters assigned.</p><?php endif; ?>
</section>

<section class="section">
  <h2>My Water Meters</h2>
  <a class="btn" href="/agents/add-meter.php?type=water">➕ Add Water Meter</a>
  <?php if ($water_meters): ?>
    <table>
      <tr><th>ID</th><th>Serial</th><th>Description</th><th>Property</th><th>Landlord</th><th>Actions</th></tr>
      <?php foreach($water_meters as $m): ?>
      <tr>
        <td><?=$m['id']?></td>
        <td><?=htmlspecialchars($m['serial_number'])?></td>
        <td><?=htmlspecialchars($m['description'] ?? '-')?></td>
        <td><?=htmlspecialchars($m['property_number'] ?? '-')?></td>
        <td><?=htmlspecialchars($m['landlord_name'] ?? '-')?></td>
        <td>
          <a href="/meter-details.php?type=water&id=<?=$m['id']?>" class="btn-action btn-view">View</a>
        </td>
      </tr>
      <?php endforeach; ?>
    </table>
  <?php else: ?><p>No water meters assigned.</p><?php endif; ?>
</section>

<?php include __DIR__.'/includes/footer.php'; ?>
