<?php
// agent-register.php
declare(strict_types=1);

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

session_start();
require_once 'db_connect.php'; // standalone RBE database connection

if (!isset($conn_rbe) || !($conn_rbe instanceof PDO)) {
  http_response_code(500);
  die('RBE database connection not available.');
}

// CSRF
if (empty($_SESSION['csrf_token'])) {
  $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
$csrf_token = $_SESSION['csrf_token'];

function esc($v){ return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8'); }

$prefill_email = isset($_GET['email']) ? trim((string)$_GET['email']) : '';
$errors = [];
$ok_msg = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  // Basic rate limit
  $_SESSION['agent_reg_attempts'] = ($_SESSION['agent_reg_attempts'] ?? 0) + 1;
  if ($_SESSION['agent_reg_attempts'] > 100) {
    http_response_code(429);
    die('Too many attempts. Try again later.');
  }

  // CSRF check
  if (!hash_equals($_SESSION['csrf_token'] ?? '', $_POST['csrf_token'] ?? '')) {
    $errors[] = 'Invalid session token. Please refresh and submit again.';
  }

  // Collect & validate fields
  $fullname = trim($_POST['fullname'] ?? '');
  $email    = trim($_POST['email'] ?? '');
  $password = (string)($_POST['password'] ?? '');
  $confirm  = (string)($_POST['confirm'] ?? '');
  $phone    = trim($_POST['phone'] ?? '');
  $company  = trim($_POST['company'] ?? '');
  $website  = trim($_POST['website'] ?? '');
  $notes    = trim($_POST['notes'] ?? '');

  if ($fullname === '') $errors[] = 'Full name is required.';
  if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) $errors[] = 'A valid email is required.';
  if ($password === '' || strlen($password) < 8) $errors[] = 'Password must be at least 8 characters.';
  if ($password !== $confirm) $errors[] = 'Passwords do not match.';
  if ($phone === '') $errors[] = 'Phone is required.';

  // Optional: normalize website
  if ($website !== '' && !preg_match('#^https?://#i', $website)) {
    $website = 'https://' . $website;
  }

  if (!$errors) {
    try {
      // Standalone RBE user/application transaction
      $conn_rbe->beginTransaction();

      // 1) Find or create the RBE user directly in rbe_users
      $st = $conn_rbe->prepare("SELECT id, password_hash FROM rbe_users WHERE email = ? LIMIT 1");
      $st->execute([$email]);
      $existingUser = $st->fetch(PDO::FETCH_ASSOC);
      $hash = password_hash($password, PASSWORD_DEFAULT);

      if ($existingUser) {
        $user_id = (int)$existingUser['id'];
        $updUser = $conn_rbe->prepare("
          UPDATE rbe_users
          SET fullname=?, phone=?, company=?, is_active=1, is_deleted=0,
              password_hash=COALESCE(password_hash, ?),
              password_updated_at=CASE WHEN password_hash IS NULL THEN NOW() ELSE password_updated_at END,
              must_set_password=CASE WHEN password_hash IS NULL THEN 0 ELSE must_set_password END
          WHERE id=?
        ");
        $updUser->execute([$fullname, $phone, $company ?: null, $hash, $user_id]);
      } else {
        $ins = $conn_rbe->prepare("
          INSERT INTO rbe_users
            (fullname, email, company, phone, password_hash, password_updated_at, must_set_password, is_active, is_deleted)
          VALUES (?, ?, ?, ?, ?, NOW(), 0, 1, 0)
        ");
        $ins->execute([$fullname, $email, $company ?: null, $phone, $hash]);
        $user_id = (int)$conn_rbe->lastInsertId();
      }

      // 2) Ensure there is NO active agent role yet (approval remains required)
      $roleCheck = $conn_rbe->prepare("SELECT role FROM rbe_roles WHERE user_id = ? AND role = 'agent' LIMIT 1");
      $roleCheck->execute([$user_id]);
      if ($roleCheck->fetchColumn() === 'agent') {
        throw new RuntimeException('You are already registered as an Agent.');
      }

      // 3) Create or refresh the pending agent application
      $pendingCheck = $conn_rbe->prepare("SELECT id, status FROM agent_applications WHERE user_id = ? AND status IN ('pending','review') ORDER BY id DESC LIMIT 1");
      $pendingCheck->execute([$user_id]);
      $existingApp = $pendingCheck->fetch(PDO::FETCH_ASSOC);

      if ($existingApp) {
        $upd = $conn_rbe->prepare("
          UPDATE agent_applications
          SET fullname=?, email=?, phone=?, company=?, website=?, notes=?, updated_at=NOW()
          WHERE id=?
        ");
        $upd->execute([$fullname, $email, $phone, $company, $website, $notes, (int)$existingApp['id']]);
        $app_id = (int)$existingApp['id'];
      } else {
        $insApp = $conn_rbe->prepare("
          INSERT INTO agent_applications (user_id, fullname, email, phone, company, website, notes, status, created_at, updated_at)
          VALUES (?,?,?,?,?,?,?,'pending',NOW(),NOW())
        ");
        $insApp->execute([$user_id, $fullname, $email, $phone, $company, $website, $notes]);
        $app_id = (int)$conn_rbe->lastInsertId();
      }

      $conn_rbe->commit();

      // (Optional) Notify admin via email/Telegram — implement as needed
      // sendAdminNotification($app_id, $fullname, $email, $phone, $company);

      $ok_msg = 'Thank you! Your agent application was submitted successfully and is pending admin approval. You will be notified once approved.';
      // Reset form fields
      $fullname = $email = $phone = $company = $website = $notes = '';
    } catch (Throwable $e) {
      if ($conn_rbe->inTransaction()) $conn_rbe->rollBack();
      $errors[] = 'Unexpected error: ' . $e->getMessage();
    }
  }
}
?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Register as Agent – RBE Utilities</title>
  <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1">
  <style>
    :root{--bg:#051a25;--card:#122c4c;--line:#233a53;--accent:#7ed957;--mut:#bfe8ff}
    *{box-sizing:border-box}
    body{margin:0;font-family:Arial,system-ui,Segoe UI,Roboto,sans-serif;background:var(--bg);color:#fff;min-height:100vh;display:flex;align-items:center;justify-content:center;padding:24px}
    .wrap{width:100%;max-width:560px;background:var(--card);border:1px solid var(--line);border-radius:14px;padding:22px;box-shadow:0 10px 30px rgba(0,0,0,.35)}
    h1{margin:0 0 6px;font-size:22px;color:var(--accent)}
    p.lead{margin:0 0 18px;color:var(--mut)}
    form{display:grid;grid-template-columns:1fr 1fr;gap:12px}
    label{font-size:12px;color:#cfe6ff}
    input,textarea{width:100%;padding:10px;border-radius:8px;border:1px solid var(--line);background:#0d223a;color:#fff}
    input::placeholder,textarea::placeholder{color:#7aa0c2}
    textarea{min-height:90px;grid-column:1 / -1}
    .full{grid-column:1 / -1}
    .row{display:flex;gap:10px}
    .btn{background:var(--accent);color:#000;padding:12px;border:none;border-radius:8px;font-weight:bold;cursor:pointer}
    .btn:hover{background:#00cc77}
    .mut{color:var(--mut)}
    .top-links{display:flex;justify-content:space-between;margin-bottom:12px}
    a{color:var(--accent);text-decoration:none}
    a:hover{text-decoration:underline}
    .alert{margin:12px 0;padding:10px 12px;border-radius:8px}
    .ok{background:#103624;color:#d8ffe9;border:1px solid #1e5c3f}
    .err{background:#3a0f14;color:#ffd6d6;border:1px solid #6b1a1a}
  </style>
</head>
<body>
  <div class="wrap">
    <div class="top-links">
      <a href="login.php">← Back to Login</a>
      <a href="//rbelectrical.enterprises/#contact" target="_blank" rel="noopener">Need help?</a>
    </div>

    <h1>Register as an Agent</h1>
    <p class="lead">Apply to become an RBE Agent. Your application will be reviewed by an Admin before activation.</p>

    <?php if ($ok_msg): ?>
      <div class="alert ok"><?= esc($ok_msg) ?></div>
    <?php endif; ?>

    <?php if ($errors): ?>
      <div class="alert err">
        <?php foreach ($errors as $e): ?>
          <div>• <?= esc($e) ?></div>
        <?php endforeach; ?>
      </div>
    <?php endif; ?>

    <form method="post" novalidate>
      <input type="hidden" name="csrf_token" value="<?= esc($csrf_token) ?>">

      <div class="full">
        <label>Full Name</label>
        <input name="fullname" placeholder="e.g. Jane Doe" required value="<?= esc($fullname ?? '') ?>">
      </div>

      <div class="full">
        <label>Email</label>
        <input type="email" name="email" placeholder="you@company.com" required value="<?= esc(($email ?? '') ?: $prefill_email) ?>">
      </div>

      <div>
        <label>Password</label>
        <input type="password" name="password" placeholder="Min 8 characters" required>
      </div>
      <div>
        <label>Confirm Password</label>
        <input type="password" name="confirm" placeholder="Repeat password" required>
      </div>

      <div class="full">
        <label>Phone</label>
        <input name="phone" placeholder="+27 82 123 4567" required value="<?= esc($phone ?? '') ?>">
      </div>

      <div>
        <label>Company (optional)</label>
        <input name="company" placeholder="Your company" value="<?= esc($company ?? '') ?>">
      </div>
      <div>
        <label>Website (optional)</label>
        <input name="website" placeholder="https://example.com" value="<?= esc($website ?? '') ?>">
      </div>

      <div class="full">
        <label>Notes (optional)</label>
        <textarea name="notes" placeholder="Tell us about your region, expected meter volumes, etc."><?= esc($notes ?? '') ?></textarea>
      </div>

      <div class="full row" style="justify-content:flex-end;margin-top:6px">
        <button class="btn" type="submit">Submit Application</button>
      </div>

      <div class="full" style="margin-top:6px">
        <span class="mut">By submitting, you agree that your account will only be activated after admin approval.</span>
      </div>
    </form>
  </div>
</body>
</html>
