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

$user_id = $_SESSION['user_id'] ?? 0;
$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
$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) ?: [];

// Commission rate per meter (Rand)
$rate = $agent['commission_rate'] ?? 0;

// Count all meters for this agent
$smart  = $conn_rbe->query("SELECT COUNT(*) FROM smart_meters WHERE agent_id=$user_id")->fetchColumn();
$flecto = $conn_rbe->query("SELECT COUNT(*) FROM flecto_meters WHERE agent_id=$user_id")->fetchColumn();
$water  = $conn_rbe->query("SELECT COUNT(*) FROM water_meters WHERE agent_id=$user_id")->fetchColumn();
$total_meters = $smart + $flecto + $water;

$commission = $total_meters * $rate;

// Fetch commission history
$history = $conn_rbe->prepare("
    SELECT period, meters, rate, amount, paid, created_at
    FROM commission_history
    WHERE agent_id=?
    ORDER BY created_at DESC
    LIMIT 12
");
$history->execute([$user_id]);
$history = $history->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; }

table { width:100%; background:#1b3a4d; color:white; border-collapse:collapse; margin-top:15px; }
table th, table td { padding:10px; text-align:center; }
table th { background:#0f2536; color:#7ed957; }
.status-paid { color:#7ed957; font-weight:bold; }
.status-pending { color:#f39c12; font-weight:bold; }
</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">My Clients</a>
  <a href="/agents/commissions.php" class="active">Commissions</a>
  <a href="/agents/profile.php">Profile</a>
  <a href="/logout.php">Logout</a>
</nav>

<section class="section">
  <h2>My Commission Overview</h2>
  <p>Rate per Meter: <b>R<?=$rate?></b></p>
  <p>Meters Onboarded: <b><?=$total_meters?></b> 
    (IAMMETER: <?=$smart?> | Flecto: <?=$flecto?> | Water: <?=$water?>)
  </p>
  <p><b>Estimated Commission: R<?=$commission?></b></p>
</section>

<section class="section">
  <h2>Commission History</h2>
  <?php if ($history): ?>
    <table>
      <tr>
        <th>Period</th>
        <th>Meters</th>
        <th>Rate</th>
        <th>Amount</th>
        <th>Status</th>
        <th>Date</th>
      </tr>
      <?php foreach($history as $h): ?>
      <tr>
        <td><?=htmlspecialchars($h['period'])?></td>
        <td><?=$h['meters']?></td>
        <td>R<?=$h['rate']?></td>
        <td>R<?=$h['amount']?></td>
        <td class="<?=$h['paid'] ? 'status-paid':'status-pending'?>">
          <?=$h['paid'] ? 'Paid' : 'Pending'?>
        </td>
        <td><?=date("Y-m-d", strtotime($h['created_at']))?></td>
      </tr>
      <?php endforeach; ?>
    </table>
  <?php else: ?>
    <p>No commission history yet.</p>
  <?php endif; ?>
</section>

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