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

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

// Ensure user is agent
$stmt = $conn_rbe->prepare("SELECT role FROM rbe_roles WHERE user_id=? LIMIT 1");
$stmt->execute([$user_id]);
if ($stmt->fetchColumn() !== 'agent') {
    header("Location: /login.php");
    exit();
}

// Agent details
$agent = $conn_rbe->prepare("
  SELECT u.fullname, u.email, u.company, cs.rate AS commission_rate
  FROM rbe_users u
  LEFT JOIN commission_settings cs ON cs.agent_id=u.id
  WHERE u.id=?
");
$agent->execute([$user_id]);
$agent = $agent->fetch(PDO::FETCH_ASSOC) ?: [];

// Quick stats
$stats = [];

// Distinct landlords linked via properties
$q = $conn_rbe->prepare("
    SELECT COUNT(DISTINCT landlord_id) 
    FROM properties 
    WHERE agent_id=? AND landlord_id IS NOT NULL
");
$q->execute([$user_id]);
$stats['landlords'] = (int)$q->fetchColumn();

// Properties
$q = $conn_rbe->prepare("SELECT COUNT(*) FROM properties WHERE agent_id=?");
$q->execute([$user_id]);
$stats['properties'] = (int)$q->fetchColumn();

// Meters (smart + flecto + water)
$q = $conn_rbe->prepare("SELECT COUNT(*) FROM smart_meters WHERE agent_id=?");
$q->execute([$user_id]);
$smart_count = (int)$q->fetchColumn();

$q = $conn_rbe->prepare("SELECT COUNT(*) FROM flecto_meters WHERE agent_id=?");
$q->execute([$user_id]);
$flecto_count = (int)$q->fetchColumn();

$q = $conn_rbe->prepare("SELECT COUNT(*) FROM water_meters WHERE agent_id=?");
$q->execute([$user_id]);
$water_count = (int)$q->fetchColumn();

$stats['meters'] = $smart_count + $flecto_count + $water_count;

// Tenants
$q = $conn_rbe->prepare("
    SELECT COUNT(*)
    FROM tenants t 
    JOIN properties p ON t.property_id=p.id 
    WHERE p.agent_id=?
");
$q->execute([$user_id]);
$stats['tenants'] = (int)$q->fetchColumn();

// Commission rate (from commission_settings)
$stats['rate'] = $agent['commission_rate'] ?? 0;

// Recent properties
$recent_properties = $conn_rbe->prepare("
    SELECT p.id, p.property_number, p.address, p.created_at,
           u.fullname AS landlord_name
    FROM properties p
    LEFT JOIN rbe_users u ON u.id = p.landlord_id
    WHERE p.agent_id=? 
    ORDER BY p.created_at DESC 
    LIMIT 5
");
$recent_properties->execute([$user_id]);
$recent_properties = $recent_properties->fetchAll(PDO::FETCH_ASSOC);

// Recent meters (union of all types)
$recent_meters = $conn_rbe->prepare("
    (SELECT 'IAMMETER' AS source, s.serial AS serial, s.created_at
     FROM smart_meters s WHERE agent_id=?)
    UNION ALL
    (SELECT 'FLECTO' AS source, f.serial_number AS serial, f.created_at
     FROM flecto_meters f WHERE agent_id=?)
    UNION ALL
    (SELECT 'WATER' AS source, w.serial_number AS serial, w.created_at
     FROM water_meters w WHERE agent_id=?)
    ORDER BY created_at DESC
    LIMIT 5
");
$recent_meters->execute([$user_id, $user_id, $user_id]);
$recent_meters = $recent_meters->fetchAll(PDO::FETCH_ASSOC);
?>

<link rel="stylesheet" href="/agents/includes/styles.css">
<style>
header {
  background: linear-gradient(180deg, #061423, #0b2238);
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 25px;
  padding: 20px;
  border-bottom: 3px solid #0f2536;
  box-shadow: 0 4px 12px rgba(0,0,0,.4);
}
header img.logo { width: 140px; height: auto; }
header .title-group h1 { color: #7ed957; font-size: 1.8em; margin: 0; }
header .title-group h2 { color: #fff; font-size: 1.4em; margin: 5px 0; }
header .title-group p { margin: 2px 0; color: #aaa; font-size: 0.9em; }
</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" class="active">Dashboard</a>
  <a href="/agents/manage.php">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>Quick Stats</h2>
  <div class="quick-stats">
    <div class="stat-card"><h4>Properties</h4><p><?=$stats['properties']?></p></div>
    <div class="stat-card"><h4>Landlords</h4><p><?=$stats['landlords']?></p></div>
    <div class="stat-card"><h4>Meters</h4><p><?=$stats['meters']?></p></div>
    <div class="stat-card"><h4>Tenants</h4><p><?=$stats['tenants']?></p></div>
    <div class="stat-card1"><h4>Commission Rate</h4><p>R<?=$stats['rate']?> / meter</p></div>
  </div>
</section>

<section class="section">
  <h2>Recent Properties</h2>
  <table>
    <tr><th>ID</th><th>Property</th><th>Address</th><th>Landlord</th><th>Date</th></tr>
    <?php if ($recent_properties): ?>
      <?php foreach($recent_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><?=date("Y-m-d", strtotime($p['created_at']))?></td>
        </tr>
      <?php endforeach; ?>
    <?php else: ?>
      <tr><td colspan="5">No properties yet.</td></tr>
    <?php endif; ?>
  </table>
</section>

<section class="section">
  <h2>Recent Meters</h2>
  <table>
    <tr><th>Serial</th><th>Type</th><th>Added</th></tr>
    <?php if ($recent_meters): ?>
      <?php foreach($recent_meters as $m): ?>
        <tr>
          <td><?=htmlspecialchars($m['serial'])?></td>
          <td><?=$m['source']?></td>
          <td><?=date("Y-m-d", strtotime($m['created_at']))?></td>
        </tr>
      <?php endforeach; ?>
    <?php else: ?>
      <tr><td colspan="3">No meters onboarded yet.</td></tr>
    <?php endif; ?>
  </table>
</section>

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