<?php
// ============================================================
// manage-agents.php — RBE Utilities Admin Agent Management (v2.0)
// ------------------------------------------------------------
// Features:
//  - List, add, and remove agents
//  - Enforces admin-only access
//  - Syncs with rbe_users and rbe_roles
//  - Auto-links commission_rate and agent_mappings if available
//  - Clean, unified design with modular dashboard style
// ============================================================

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

session_start();
require_once __DIR__ . '/core/db_connect.php';
include 'admin-nav.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 ($role !== 'admin') {
  exit("Access denied. Admins only.");
}

// ------------------------------------------------------------
// 🧹 Helper: check if column exists (for relational cleanup)
// ------------------------------------------------------------
function columnExists(PDO $pdo, string $table, string $column): bool {
  $db = $pdo->query("SELECT DATABASE()")->fetchColumn();
  $stmt = $pdo->prepare("
    SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS
    WHERE TABLE_SCHEMA=? AND TABLE_NAME=? AND COLUMN_NAME=? LIMIT 1
  ");
  $stmt->execute([$db, $table, $column]);
  return (bool)$stmt->fetchColumn();
}

$message = "";

// ------------------------------------------------------------
// 🗑️ Delete Agent (safe cleanup across related tables)
// ------------------------------------------------------------
if (isset($_GET['delete'])) {
  $delete_id = (int)$_GET['delete'];

  foreach (['properties','smart_meters','flecto_meters','water_meters'] as $tbl) {
    if (columnExists($conn_rbe, $tbl, 'agent_id')) {
      $stmt = $conn_rbe->prepare("UPDATE {$tbl} SET agent_id=NULL WHERE agent_id=?");
      $stmt->execute([$delete_id]);
    }
  }

  $conn_rbe->prepare("DELETE FROM commission_settings WHERE agent_id=?")->execute([$delete_id]);
  $conn_rbe->prepare("DELETE FROM rbe_roles WHERE user_id=? AND role='agent'")->execute([$delete_id]);
  $conn_rbe->prepare("DELETE FROM rbe_users WHERE id=?")->execute([$delete_id]);
  $conn_rbe->prepare("DELETE FROM login_tokens WHERE user_id=?")->execute([$delete_id]);

  $message = "🗑️ Agent deleted successfully.";
}

// ------------------------------------------------------------
// ➕ Add New Agent
// ------------------------------------------------------------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_agent'])) {
  $fullname = trim($_POST['fullname'] ?? '');
  $email    = trim($_POST['email'] ?? '');
  $phone    = trim($_POST['phone'] ?? '');
  $company  = trim($_POST['company'] ?? '');
  $rate     = (float)($_POST['commission_rate'] ?? 0);

  if ($fullname && $email) {
    // Find or create standalone RBE user
    $stmt = $conn_rbe->prepare("SELECT id FROM rbe_users WHERE email=? LIMIT 1");
    $stmt->execute([$email]);
    $new_id = (int)($stmt->fetchColumn() ?: 0);
    if ($new_id > 0) {
      $stmt = $conn_rbe->prepare("UPDATE rbe_users SET fullname=?, company=?, phone=?, is_active=1, is_deleted=0 WHERE id=?");
      $stmt->execute([$fullname, $company, $phone, $new_id]);
    } else {
      $stmt = $conn_rbe->prepare("INSERT INTO rbe_users (fullname, email, company, phone, must_set_password, is_active, is_deleted) VALUES (?, ?, ?, ?, 1, 1, 0)");
      $stmt->execute([$fullname, $email, $company, $phone]);
      $new_id = (int)$conn_rbe->lastInsertId();
    }

    // Assign agent role
    $stmt = $conn_rbe->prepare("INSERT IGNORE INTO rbe_roles (user_id, role) VALUES (?, 'agent')");
    $stmt->execute([$new_id]);

    // Commission setting (if table exists)
    if (columnExists($conn_rbe, 'commission_settings', 'rate')) {
      $stmt = $conn_rbe->prepare("
        INSERT INTO commission_settings (agent_id, rate)
        VALUES (?, ?)
        ON DUPLICATE KEY UPDATE rate=VALUES(rate)
      ");
      $stmt->execute([$new_id, $rate]);
    }

    $message = "✅ Agent <b>$fullname</b> added successfully.";
  } else {
    $message = "❌ Full name and email are required.";
  }
}

// ------------------------------------------------------------
// 📋 Fetch Agents
// ------------------------------------------------------------
$stmt = $conn_rbe->query("
  SELECT 
    u.id AS user_id,
    u.fullname,
    u.email,
    u.phone,
    u.company,
    cs.rate AS commission_rate,
    COUNT(DISTINCT p.id) AS property_count,
    COUNT(DISTINCT sm.id) AS meter_count
  FROM rbe_users u
  JOIN rbe_roles r ON u.id = r.user_id AND r.role = 'agent'
  LEFT JOIN commission_settings cs ON cs.agent_id = u.id
  LEFT JOIN properties p ON p.agent_id = u.id
  LEFT JOIN smart_meters sm ON sm.agent_id = u.id
  GROUP BY u.id
  ORDER BY u.fullname ASC
");
$agents = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Manage Agents — RBE Utilities</title>
<link rel="stylesheet" href="modules/billing/billing.css">
<style>
.container {
  margin-left: 200px;
  padding: 40px;
}
.card { margin-bottom: 30px; }
.add-form input {
  width: 100%;
  max-width: 1100px;
  margin-bottom: 12px;
}
.add-form label { color: var(--accent2); font-weight: 600; }
.add-form button { width: 100%; margin-top: 10px; }
.table-wrap {
  overflow-x: auto;
}
</style>
</head>
<body>

<div class="container">
  <h1>👔 Manage Agents</h1>

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

  <div class="card">
    <h2>➕ Add New Agent</h2>
    <form method="post" class="add-form">
      <label>Full Name</label>
      <input type="text" name="fullname" required>

      <label>Email</label>
      <input type="email" name="email" required>

      <label>Phone</label>
      <input type="text" name="phone">

      <label>Company</label>
      <input type="text" name="company">

      <label>Commission Rate (%)</label>
      <input type="number" name="commission_rate" step="0.01" placeholder="e.g. 3.5">

      <button type="submit" name="add_agent">Add Agent</button>
    </form>
  </div>

  <div class="card">
    <h2>🧾 Current Agents</h2>
    <div class="table-wrap">
      <table>
        <thead>
          <tr>
            <th>ID</th>
            <th>Full Name</th>
            <th>Email</th>
            <th>Phone</th>
            <th>Company</th>
            <th>Commission %</th>
            <th>Properties</th>
            <th>Meters</th>
            <th>Actions</th>
          </tr>
        </thead>
        <tbody>
          <?php if ($agents): ?>
            <?php foreach ($agents as $a): ?>
              <tr>
                <td><?= htmlspecialchars($a['user_id']) ?></td>
                <td><?= htmlspecialchars($a['fullname']) ?></td>
                <td><?= htmlspecialchars($a['email']) ?></td>
                <td><?= htmlspecialchars($a['phone']) ?></td>
                <td><?= htmlspecialchars($a['company']) ?></td>
                <td><?= htmlspecialchars($a['commission_rate'] ?? '0.00') ?></td>
                <td><?= htmlspecialchars($a['property_count']) ?></td>
                <td><?= htmlspecialchars($a['meter_count']) ?></td>
                <td>
                  <a href="edit-agent.php?id=<?= $a['user_id'] ?>" class="btn secondary">Edit</a>
                  <a href="?delete=<?= $a['user_id'] ?>" class="btn secondary" style="color:var(--danger)" onclick="return confirm('Delete this agent?')">Delete</a>
                </td>
              </tr>
            <?php endforeach; ?>
          <?php else: ?>
            <tr><td colspan="9" style="text-align:center;color:var(--muted)">No agents found.</td></tr>
          <?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

</body>
</html>
