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

if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

// Admin gate
$admin_id = (int)$_SESSION['user_id'];
$st = $conn_rbe->prepare("SELECT role FROM rbe_roles WHERE user_id = ? LIMIT 1");
$st->execute([$admin_id]);
if ($st->fetchColumn() !== 'admin') {
    exit('Access denied.');
}

// Agent user id
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if ($id <= 0) { echo "Invalid agent ID."; exit(); }

// Helpers
function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }
$dbName = $conn_rbe->query("SELECT DATABASE()")->fetchColumn();

function tableExists(PDO $pdo, string $db, string $table): bool {
    $q = $pdo->prepare("SELECT 1 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? LIMIT 1");
    $q->execute([$db, $table]); return (bool)$q->fetchColumn();
}
function columnExists(PDO $pdo, string $db, string $table, string $col): bool {
    $q = $pdo->prepare("SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? AND COLUMN_NAME = ? LIMIT 1");
    $q->execute([$db, $table, $col]); return (bool)$q->fetchColumn();
}
function fetchAssoc(PDO $pdo, string $sql, array $params=[]): ?array {
    $s = $pdo->prepare($sql); $s->execute($params); $row = $s->fetch(PDO::FETCH_ASSOC);
    return $row ?: null;
}
function fetchAll(PDO $pdo, string $sql, array $params=[]): array {
    $s = $pdo->prepare($sql); $s->execute($params); return $s->fetchAll(PDO::FETCH_ASSOC);
}

// Handle actions
$msg = $err = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Update core profile
    if (isset($_POST['save'])) {
        $fullname = trim($_POST['fullname'] ?? '');
        $email    = trim($_POST['email'] ?? '');
        $phone    = trim($_POST['phone'] ?? '');
        if ($fullname && $email) {
            $u = $conn_rbe->prepare("UPDATE rbe_users SET fullname=?, email=?, phone=? WHERE id=?");
            $u->execute([$fullname, $email, $phone, $id]);
            $msg = "✅ Agent profile updated.";
        } else {
            $err = "❌ Full name and email are required.";
        }
    }

    // Ensure agent role
    if (isset($_POST['ensure_role'])) {
        $chk = fetchAssoc($conn_rbe, "SELECT 1 FROM rbe_roles WHERE user_id=? AND role='agent' LIMIT 1", [$id]);
        if (!$chk) {
            $ins = $conn_rbe->prepare("INSERT INTO rbe_roles (user_id, role, created_at) VALUES (?, 'agent', NOW())");
            $ins->execute([$id]);
            $msg = "✅ Agent role added for user #$id.";
        } else {
            $msg = "ℹ️ Agent role already exists.";
        }
    }

    // Resend invite / set-password link
    if (isset($_POST['resend_invite'])) {
        $u = fetchAssoc($conn_rbe, "SELECT fullname, email FROM rbe_users WHERE id=?", [$id]);
        if ($u && !empty($u['email'])) {
            $token   = bin2hex(random_bytes(32));
            $expires = date('Y-m-d H:i:s', strtotime('+30 minutes'));
            $conn_rbe->prepare("INSERT INTO login_tokens (user_id, token, expires_at) VALUES (?, ?, ?)")
                     ->execute([$id, $token, $expires]);
            $link = RBE_V1_BASE_URL . "/set-password.php?token=" . urlencode($token);

            // Simple mail; replace headers/transport as needed
            $subject = "Set up your RBE agent account";
            $body    = "Hi {$u['fullname']},\n\nPlease set your password using the link below:\n$link\n\nThis link expires in 30 minutes.";
            $headers = "From: " . RBE_MAIL_FROM;
            if (@mail($u['email'], $subject, $body, $headers)) {
                $msg = "📧 Invite sent to {$u['email']}.";
            } else {
                $err = "⚠️ Failed to send email to {$u['email']}.";
            }
        } else {
            $err = "❌ Cannot send invite: missing agent email.";
        }
    }
}

// Pull core profile
$agent = fetchAssoc($conn_rbe, "SELECT * FROM rbe_users WHERE id=?", [$id]);
if (!$agent) { echo "Agent not found."; exit(); }

// Roles
$roles = fetchAll($conn_rbe, "SELECT role, created_at FROM rbe_roles WHERE user_id=? ORDER BY created_at ASC", [$id]);

// Agent application (latest) if table exists
$appTable = tableExists($conn_rbe, $dbName, 'agent_applications');
$app = null;
if ($appTable) {
    // prefer join on user_id if present; fall back to email match if not
    $hasUserIdCol = columnExists($conn_rbe, $dbName, 'agent_applications', 'user_id');
    if ($hasUserIdCol) {
        $app = fetchAssoc($conn_rbe, "SELECT * FROM agent_applications WHERE user_id=? ORDER BY id DESC LIMIT 1", [$id]);
    }
    if (!$app && !empty($agent['email']) && columnExists($conn_rbe, $dbName, 'agent_applications', 'email')) {
        $app = fetchAssoc($conn_rbe, "SELECT * FROM agent_applications WHERE email=? ORDER BY id DESC LIMIT 1", [$agent['email']]);
    }
}

// Stats (scoped by optional agent_id)
$hasAgentProps  = columnExists($conn_rbe, $dbName, 'properties',     'agent_id');
$hasAgentSmart  = columnExists($conn_rbe, $dbName, 'smart_meters',   'agent_id');
$hasAgentFlecto = columnExists($conn_rbe, $dbName, 'flecto_meters',  'agent_id');
$hasAgentWater  = columnExists($conn_rbe, $dbName, 'water_meters',   'agent_id');

$propertiesCount = $hasAgentProps
    ? (int)fetchAssoc($conn_rbe, "SELECT COUNT(*) c FROM properties WHERE agent_id=?", [$id])['c']
    : (int)0;

$iamCount = $hasAgentSmart
    ? (int)fetchAssoc($conn_rbe, "SELECT COUNT(*) c FROM smart_meters WHERE agent_id=?", [$id])['c']
    : (int)fetchAssoc($conn_rbe, "SELECT COUNT(*) c FROM smart_meters", [])['c'];

$flectoCount = $hasAgentFlecto
    ? (int)fetchAssoc($conn_rbe, "SELECT COUNT(*) c FROM flecto_meters WHERE agent_id=?", [$id])['c']
    : (int)fetchAssoc($conn_rbe, "SELECT COUNT(*) c FROM flecto_meters", [])['c'];

$waterCount = $hasAgentWater
    ? (int)fetchAssoc($conn_rbe, "SELECT COUNT(*) c FROM water_meters WHERE agent_id=?", [$id])['c']
    : (int)fetchAssoc($conn_rbe, "SELECT COUNT(*) c FROM water_meters", [])['c'];

$totalMeters = $iamCount + $flectoCount + $waterCount;

// Small lists
$properties = $hasAgentProps
    ? fetchAll($conn_rbe, "SELECT id, property_number, address FROM properties WHERE agent_id=? ORDER BY id DESC LIMIT 10", [$id])
    : [];

$iamList = $hasAgentSmart
    ? fetchAll($conn_rbe, "SELECT id, serial, phases FROM smart_meters WHERE agent_id=? ORDER BY id DESC LIMIT 10", [$id])
    : [];

$flectoList = $hasAgentFlecto
    ? fetchAll($conn_rbe, "SELECT id, serial_number, description FROM flecto_meters WHERE agent_id=? ORDER BY id DESC LIMIT 10", [$id])
    : [];

$waterList = $hasAgentWater
    ? fetchAll($conn_rbe, "SELECT id, serial_number, description FROM water_meters WHERE agent_id=? ORDER BY id DESC LIMIT 10", [$id])
    : [];

// Utility to render any assoc row (for “all details”)
function renderDetailTable(array $row): string {
    if (!$row) return '<p>—</p>';
    $html = '<table class="kv"><tbody>';
    foreach ($row as $k=>$v) {
        $label = ucwords(str_replace('_',' ', (string)$k));
        $val   = is_null($v) || $v === '' ? '—' : h($v);
        $html .= "<tr><th>".h($label)."</th><td>{$val}</td></tr>";
    }
    $html .= '</tbody></table>';
    return $html;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Edit Agent • RBE Admin</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
  body{background:#0a1a2f;color:#fff;font-family:Arial, sans-serif;margin:0;padding:40px}
  .wrap{max-width:1000px;margin:0 auto}
  a.btn,a.back{display:inline-block;background:#7ed957;color:#000;text-decoration:none;font-weight:bold;padding:10px 16px;border-radius:10px}
  a.btn:hover{background:#00cc77}
  .card{background:#122c4c;border-radius:12px;padding:22px;margin:18px 0;box-shadow:0 0 15px rgba(0,0,0,.35)}
  h1,h2{color:#7ed957;margin:0 0 16px}
  .grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(260px,1fr));gap:16px}
  .kv{width:100%;border-collapse:collapse;overflow:hidden}
  .kv th,.kv td{padding:10px;border-bottom:1px solid #284361;vertical-align:top}
  .kv th{width:35%;color:#7ed957;text-align:left;background:#0f2438}
  .msg{padding:10px 14px;border-radius:8px;margin:10px 0}
  .ok{background:#0f3b2a;color:#b6ffcf;border:1px solid #176546}
  .err{background:#3b0f0f;color:#ffd6d6;border:1px solid #6b1a1a}
  .actions form{display:inline-block;margin-right:10px}
  input,button{padding:10px;border:none;border-radius:8px}
  input[type=text],input[type=email]{width:100%;background:#1b3a4d;color:#fff;margin:6px 0}
  button.save{background:#7ed957;color:#000;font-weight:bold;cursor:pointer}
  button.alt{background:#334b6a;color:#fff;cursor:pointer}
  table.list{width:100%;border-collapse:collapse}
  table.list th,table.list td{border-bottom:1px solid #284361;padding:10px}
  table.list th{color:#7ed957;background:#0f2438;text-align:left}
  .pill{display:inline-block;padding:2px 8px;border-radius:999px;background:#213a57;color:#bfe2ff;margin-right:6px;font-size:12px}
</style>
</head>
<body>
<div class="wrap">
  <a href="manage-agents.php" class="back">⬅ Back to Manage Agents</a>
  <h1>✏️ Edit Agent #<?= (int)$id ?></h1>

  <?php if ($msg): ?><div class="msg ok"><?= h($msg) ?></div><?php endif; ?>
  <?php if ($err): ?><div class="msg err"><?= h($err) ?></div><?php endif; ?>

  <div class="card">
    <h2>Profile</h2>
    <div class="grid">
      <div>
        <?= renderDetailTable($agent) ?>
      </div>
      <div>
        <h3 style="margin-top:0;color:#7ed957">Update Basic Info</h3>
        <form method="post">
          <label>Full Name</label>
          <input type="text" name="fullname" value="<?= h($agent['fullname'] ?? '') ?>" required>
          <label>Email</label>
          <input type="email" name="email" value="<?= h($agent['email'] ?? '') ?>" required>
          <label>Phone</label>
          <input type="text" name="phone" value="<?= h($agent['phone'] ?? '') ?>">
          <button class="save" type="submit" name="save">💾 Save Changes</button>
        </form>
        <div class="actions" style="margin-top:12px;">
          <form method="post"><button class="alt" type="submit" name="ensure_role">✅ Ensure Agent Role</button></form>
          <form method="post"><button class="alt" type="submit" name="resend_invite">📧 Resend Invite</button></form>
        </div>
        <div style="margin-top:12px;">
          <strong>Roles:</strong>
          <?php if ($roles): foreach ($roles as $r): ?>
            <span class="pill"><?= h($r['role']) ?></span>
          <?php endforeach; else: ?>
            <span class="pill">—</span>
          <?php endif; ?>
        </div>
      </div>
    </div>
  </div>

  <div class="card">
    <h2>Agent Application (All Details)</h2>
    <?php
      if ($appTable) {
          echo $app ? renderDetailTable($app) : "<p>No application found for this agent.</p>";
      } else {
          echo "<p>Table <code>agent_applications</code> not found in this database.</p>";
      }
    ?>
  </div>

  <div class="card">
    <h2>Stats</h2>
    <div class="grid">
      <div class="kv">
        <table class="kv">
          <tr><th>Properties (assigned to agent)</th><td><?= (int)$propertiesCount ?></td></tr>
          <tr><th>IAMMETER Meters<?= $hasAgentSmart ? ' (scoped)' : '' ?></th><td><?= (int)$iamCount ?></td></tr>
          <tr><th>FLECTO Meters<?= $hasAgentFlecto ? ' (scoped)' : '' ?></th><td><?= (int)$flectoCount ?></td></tr>
          <tr><th>WATER Meters<?= $hasAgentWater ? ' (scoped)' : '' ?></th><td><?= (int)$waterCount ?></td></tr>
          <tr><th>Total Meters</th><td><?= (int)$totalMeters ?></td></tr>
        </table>
      </div>
      <div>
        <p style="opacity:.85;">Notes: Counts are scoped by <code>agent_id</code> where those columns exist; otherwise they fall back to global totals so this page never breaks on older schemas.</p>
      </div>
    </div>
  </div>

  <div class="card">
    <h2>Recent Properties (up to 10)</h2>
    <?php if ($properties): ?>
      <table class="list">
        <tr><th>ID</th><th>Property #</th><th>Address</th></tr>
        <?php foreach ($properties as $p): ?>
          <tr>
            <td><?= (int)$p['id'] ?></td>
            <td><?= h($p['property_number'] ?? '') ?></td>
            <td><?= h($p['address'] ?? '') ?></td>
          </tr>
        <?php endforeach; ?>
      </table>
    <?php else: ?>
      <p>—</p>
    <?php endif; ?>
  </div>

  <div class="card">
    <h2>Recent Meters (up to 10 of each)</h2>
    <div class="grid">
      <div>
        <h3 style="color:#7ed957;margin:0 0 10px">IAMMETER</h3>
        <?php if ($iamList): ?>
          <table class="list">
            <tr><th>ID</th><th>Serial</th><th>Phases</th></tr>
            <?php foreach ($iamList as $m): ?>
              <tr><td><?= (int)$m['id'] ?></td><td><?= h($m['serial']) ?></td><td><?= (int)$m['phases'] ?></td></tr>
            <?php endforeach; ?>
          </table>
        <?php else: ?><p>—</p><?php endif; ?>
      </div>
      <div>
        <h3 style="color:#7ed957;margin:0 0 10px">FLECTO</h3>
        <?php if ($flectoList): ?>
          <table class="list">
            <tr><th>ID</th><th>Serial</th><th>Description</th></tr>
            <?php foreach ($flectoList as $m): ?>
              <tr><td><?= (int)$m['id'] ?></td><td><?= h($m['serial_number']) ?></td><td><?= h($m['description']) ?></td></tr>
            <?php endforeach; ?>
          </table>
        <?php else: ?><p>—</p><?php endif; ?>
      </div>
      <div>
        <h3 style="color:#7ed957;margin:0 0 10px">WATER</h3>
        <?php if ($waterList): ?>
          <table class="list">
            <tr><th>ID</th><th>Serial</th><th>Description</th></tr>
            <?php foreach ($waterList as $m): ?>
              <tr><td><?= (int)$m['id'] ?></td><td><?= h($m['serial_number']) ?></td><td><?= h($m['description']) ?></td></tr>
            <?php endforeach; ?>
          </table>
        <?php else: ?><p>—</p><?php endif; ?>
      </div>
    </div>
  </div>
</div>
</body>
</html>
