<?php
// ============================================================
// admin-comm.php — RBE Utilities Commission Management
// ============================================================

require_once __DIR__ . '/core/db_connect.php';

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

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

if (!isset($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
$csrf_token = $_SESSION['csrf_token'];

$flash_ok = $flash_err = "";

// ------------------------------------------------------------
// Commission Update Logic
// ------------------------------------------------------------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_commission'])) {
    $agent_id = (int)($_POST['agent_id'] ?? 0);
    $rate     = (float)($_POST['commission_rate'] ?? 0);
    $csrf     = $_POST['csrf_token'] ?? '';

    if (!hash_equals($_SESSION['csrf_token'], $csrf)) {
        $flash_err = "Invalid session token. Please refresh the page.";
    } elseif ($agent_id <= 0) {
        $flash_err = "Invalid agent ID.";
    } else {
        try {
            $stmt = $conn_rbe->prepare("
                INSERT INTO commission_settings (agent_id, rate)
                VALUES (?, ?)
                ON DUPLICATE KEY UPDATE rate = VALUES(rate)
            ");
            $stmt->execute([$agent_id, $rate]);
            $flash_ok = "✅ Commission rate updated successfully.";
        } catch (Throwable $e) {
            $flash_err = "Error: ".$e->getMessage();
        }
    }
}
?>

<main class="dashboard-content">
<div class="section commission-section">
  <h2>💰 Commission Management</h2>
  <p>Set and update commission rates for each agent (ZAR per meter):</p>

  <?php if ($flash_ok): ?>
    <div class="alert ok"><?= htmlspecialchars($flash_ok) ?></div>
  <?php elseif ($flash_err): ?>
    <div class="alert err"><?= htmlspecialchars($flash_err) ?></div>
  <?php endif; ?>

  <div class="commission-table">
    <table>
      <tr>
        <th>Agent</th>
        <th>Email</th>
        <th>Current Rate / Meter</th>
        <th>Update</th>
      </tr>

      <?php
      $agents = $conn_rbe->query("
          SELECT u.id, u.fullname, u.email, cs.rate
          FROM rbe_users u
          JOIN rbe_roles r ON r.user_id=u.id AND r.role='agent'
          LEFT JOIN commission_settings cs ON cs.agent_id=u.id
          ORDER BY u.fullname ASC
      ");
      while ($ag = $agents->fetch(PDO::FETCH_ASSOC)): ?>
      <tr>
        <td><?= htmlspecialchars($ag['fullname']) ?></td>
        <td><?= htmlspecialchars($ag['email']) ?></td>
        <td><?= htmlspecialchars($ag['rate'] ?? 0) ?> ZAR</td>
        <td>
          <form method="post" class="inline-form">
            <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrf_token) ?>">
            <input type="hidden" name="agent_id" value="<?= (int)$ag['id'] ?>">
            <input type="number" name="commission_rate" step="1" min="0" 
                   value="<?= htmlspecialchars($ag['rate'] ?? 0) ?>" class="input-small">
            <button type="submit" name="update_commission" class="btn-primary">Save</button>
          </form>
        </td>
      </tr>
      <?php endwhile; ?>
    </table>
  </div>
</div>
</main>

<!-- ==========================================================
     STYLING
     ========================================================== -->
<style>
.dashboard-content {
  margin-left: 240px;
  padding: 40px 30px;
  color: #e6f5ff;
  box-sizing: border-box;
}

.commission-section {
  background: #0b2333;
  border-radius: 16px;
  padding: 25px;
  margin: -85px auto;
  box-shadow: 0 0 18px rgba(0, 0, 0, 0.4);
  max-width: 1200px;
}

.commission-section h2 {
  color: var(--accent2, #00ccff);
  text-align: center;
  margin-bottom: 20px;
}
.commission-section p {
  text-align: center;
  color: #9bb5c7;
  margin-bottom: 25px;
}

.commission-table table {
  width: 100%;
  border-collapse: collapse;
  background: #122c4c;
  color: #e6f5ff;
  border-radius: 10px;
  overflow: hidden;
}
.commission-table th, .commission-table td {
  text-align: center;
  padding: 12px;
  border-bottom: 1px solid #1b3a4d;
}
.commission-table th {
  background: #0f2536;
  color: var(--accent2, #00ccff);
  font-weight: 600;
}
.commission-table tr:hover {
  background-color: #1a3e57;
}

.inline-form {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  justify-content: center;
}
.input-small {
  width: 80px;
  padding: 8px;
  border-radius: 6px;
  border: none;
  background: #1b3a4d;
  color: #e6f5ff;
  text-align: center;
}

.btn-primary {
  background: var(--accent, #7ed957);
  color: #041622;
  font-weight: 600;
  padding: 8px 16px;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.25s ease;
}
.btn-primary:hover {
  background: #00cc77;
  transform: translateY(-2px);
}

.alert {
  text-align: center;
  padding: 10px 15px;
  border-radius: 8px;
  margin-bottom: 20px;
  font-weight: 500;
}
.alert.ok { background:#0f3b2a; color:#b6ffcf; border:1px solid #176546; }
.alert.err { background:#3b0f0f; color:#ffd6d6; border:1px solid #6b1a1a; }

@media (max-width: 768px) {
  .dashboard-content { margin-left: 80px; padding: 25px 15px; }
  .input-small { width: 65px; }
  .commission-table th, .commission-table td { font-size: 0.9em; padding: 8px; }
}
</style>

<!-- ==========================================================
     JS ANIMATION (optional smooth alert fade)
     ========================================================== -->
<script>
document.addEventListener("DOMContentLoaded", () => {
  const alert = document.querySelector(".alert");
  if (alert) {
    setTimeout(() => {
      alert.style.transition = "opacity 0.6s ease";
      alert.style.opacity = "0";
      setTimeout(() => alert.remove(), 600);
    }, 4000);
  }
});
</script>
