<?php
// agent_reg.php
// preserves plan from previous page (POST or GET). Defaults to 'Basic' if not provided.
$plan = 'Basic';
if (isset($_REQUEST['plan']) && !empty($_REQUEST['plan'])) {
  $plan = htmlspecialchars($_REQUEST['plan']);
}
?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width,initial-scale=1" />
  <title>Agent Registration</title>

  <!-- Bootstrap CSS -->
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">

  <!-- Font Awesome for icons -->
  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css" rel="stylesheet">

  <style>
    :root{
      --accent: #0d6efd;
      --muted: #6c757d;
      --card-radius: 12px;
    }
    body { background: #f4f8fb; font-family: Inter, system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial; }
    .card { border-radius: var(--card-radius); box-shadow: 0 8px 30px rgba(21,32,43,0.06); }
    .form-step { display: none; animation: fadeIn 420ms ease both; }
    .form-step.active { display: block; }
    @keyframes fadeIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }

    /* progress */
    .progress {
      height: 8px;
      border-radius: 999px;
      background: rgba(13,110,253,0.08);
      overflow: hidden;
    }
    .progress-bar {
      background: linear-gradient(90deg, #0d6efd, #2a8cff);
    }

    /* step indicators */
    .step-indicators { display:flex; gap:12px; justify-content:center; align-items:center; margin-bottom:1rem; }
    .step-dot {
      width:36px; height:36px; border-radius:50%; display:flex; align-items:center; justify-content:center;
      background:#e9eef8; color:var(--muted); font-weight:600;
      box-shadow: 0 4px 14px rgba(13,110,253,0.04);
    }
    .step-dot.active { background: var(--accent); color:#fff; box-shadow: 0 8px 26px rgba(13,110,253,0.16); }

    /* image preview */
    .avatar-preview {
      width:120px; height:120px; border-radius:10px; overflow:hidden; background:#fff; display:inline-block;
      border: 1px dashed rgba(13,110,253,0.12); object-fit:cover;
    }
    .small-muted { font-size:0.85rem; color:var(--muted); }

    /* buttons */
    .btn-ghost { background: transparent; border:1px solid rgba(13,110,253,0.12); color:var(--accent); }
    .note { font-size:0.92rem; color:var(--muted); }

    /* responsive tweaks */
    @media (max-width: 575px) {
      .avatar-preview { width:96px; height:96px; }
    }

    /* password helper */
    .pw-err { color:#d63384; font-size:0.9rem; display:none; }
    .pw-ok { color:#198754; font-size:0.9rem; display:none; }
  </style>
</head>
<body>

<div class="container py-5">
  <div class="row justify-content-center">
    <div class="col-xl-7 col-lg-8 col-md-10">
      <div class="card p-4">
        <div class="d-flex align-items-start justify-content-between mb-3">
          <div>
            <h4 class="mb-0">Agent Registration</h4>
            <div class="small-muted">Create your agent account — it works for all subscription tiers.</div>
          </div>
          <div class="text-end">
            <div class="small-muted">Selected plan</div>
            <strong><?php echo $plan; ?></strong>
          </div>
        </div>

        <!-- progress -->
        <div class="mb-3">
          <div class="progress" role="progressbar" aria-label="Registration progress">
            <div id="progressBar" class="progress-bar" style="width:33%"></div>
          </div>
        </div>

        <!-- step indicators -->
        <div class="step-indicators mb-3" aria-hidden="true">
          <div class="step-dot active"><span>1</span></div>
          <div class="step-dot"><span>2</span></div>
          <div class="step-dot"><span>3</span></div>
        </div>

        <form id="regForm" action="pro_agent_reg.php" method="post" enctype="multipart/form-data" novalidate>
          <!-- keep selected plan -->
          <input type="hidden" name="plan" id="planInput" value="<?php echo $plan; ?>">

          <!-- STEP 1: Personal Info -->
          <div class="form-step active" data-step="1" aria-labelledby="step1Title">
            <h5 id="step1Title" class="mb-3">Personal Info</h5>

            <div class="mb-3">
              <label for="first_name" class="form-label">First name <span class="text-danger">*</span></label>
              <input id="first_name" name="first_name" type="text" class="form-control" required>
            </div>

            <div class="mb-3">
              <label for="last_name" class="form-label">Last name <span class="text-danger">*</span></label>
              <input id="last_name" name="last_name" type="text" class="form-control" required>
            </div>

            <div class="mb-3">
              <label class="form-label d-block">Profile image <span class="text-muted small">(max 2MB)</span></label>
              <div class="d-flex align-items-center gap-3">
                <div class="avatar-preview" id="avatarPreview">
                  <img id="avatarImg" src="" alt="Preview" style="width:100%;height:100%;object-fit:cover;display:none;">
                  <div id="avatarEmpty" class="d-flex align-items-center justify-content-center h-100 small-muted" style="padding:10px;">
                    <i class="fa-regular fa-image fa-2x"></i>
                  </div>
                </div>

                <div class="flex-fill">
                  <input id="image" name="image" type="file" accept="image/*" class="form-control" required>
                  <div class="small-muted mt-1">Allowed: JPG, PNG. We'll resize on server.</div>
                </div>
              </div>
            </div>
          </div>

          <!-- STEP 2: Contact Info -->
          <div class="form-step" data-step="2" aria-labelledby="step2Title">
            <h5 id="step2Title" class="mb-3">Contact Info</h5>

            <div class="mb-3">
              <label for="email" class="form-label">Email <span class="text-danger">*</span></label>
              <div class="input-group">
                <span class="input-group-text"><i class="fa fa-envelope"></i></span>
                <input id="email" name="email" type="email" class="form-control" required>
              </div>
            </div>

            <div class="mb-3">
              <label for="phone" class="form-label">Phone <span class="text-danger">*</span></label>
              <div class="input-group">
                <span class="input-group-text"><i class="fa fa-phone"></i></span>
                <input id="phone" name="phone" type="tel" class="form-control" placeholder="+234..." required>
              </div>
            </div>

            <div class="mb-3">
              <label for="address" class="form-label">Office address</label>
              <textarea id="address" name="address" class="form-control" rows="3" placeholder="Street, City, State"></textarea>
            </div>
          </div>

          <!-- STEP 3: Login Info -->
          <div class="form-step" data-step="3" aria-labelledby="step3Title">
            <h5 id="step3Title" class="mb-3">Login Info</h5>

            <div class="mb-3">
              <label for="username" class="form-label">Username <span class="text-danger">*</span></label>
              <div class="input-group">
                <span class="input-group-text"><i class="fa fa-user"></i></span>
                <input id="username" name="username" type="text" class="form-control" minlength="3" required>
              </div>
              <div id="usernameFeedback" class="small mt-1"></div>
            </div>

            <div class="mb-3 position-relative">
              <label for="password" class="form-label">Password <span class="text-danger">*</span></label>
              <div class="input-group">
                <span class="input-group-text"><i class="fa fa-lock"></i></span>
                <input id="password" name="password" type="password" class="form-control" minlength="6" required>
              </div>
              <div class="pw-err" id="pwLengthErr">Password must be at least 6 characters.</div>
            </div>

            <div class="mb-3">
              <label for="confirm_password" class="form-label">Confirm Password <span class="text-danger">*</span></label>
              <div class="input-group">
                <span class="input-group-text"><i class="fa fa-lock"></i></span>
                <input id="confirm_password" name="confirm_password" type="password" class="form-control" required>
              </div>
              <div class="pw-err" id="pwMatchErr">Passwords do not match.</div>
              <div class="pw-ok" id="pwMatchOk">Passwords match.</div>
            </div>
          </div>

          <!-- navigation -->
          <div class="d-flex align-items-center justify-content-between mt-3">
            <button type="button" id="prevBtn" class="btn btn-ghost" disabled>
              <i class="fa fa-arrow-left me-2" aria-hidden="true"></i> Previous
            </button>

            <div class="d-flex gap-2">
              <button type="button" id="saveDraft" class="btn btn-outline-secondary me-2" title="Save progress (not implemented server-side)">
                <i class="fa-regular fa-save me-1"></i> Save
              </button>

              <button type="button" id="nextBtn" class="btn btn-primary">
                Next <i class="fa fa-arrow-right ms-2" aria-hidden="true"></i>
              </button>
            </div>
          </div>
        </form>

        <div class="mt-3 small text-muted text-center">
          By creating an account you agree to our <a href="#" class="text-decoration-underline">terms & privacy</a>.
        </div>
      </div>
    </div>
  </div>
</div>

<!-- Bootstrap JS bundle -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>

<script>
  (function () {
    // Elements
    const form = document.getElementById('regForm');
    const steps = Array.from(document.querySelectorAll('.form-step'));
    const stepDots = Array.from(document.querySelectorAll('.step-dot'));
    const progressBar = document.getElementById('progressBar');
    const prevBtn = document.getElementById('prevBtn');
    const nextBtn = document.getElementById('nextBtn');

    let current = 0; // zero-based step index

    // show step
    function showStep(n) {
      steps.forEach((s, i) => s.classList.toggle('active', i === n));
      stepDots.forEach((d, i) => d.classList.toggle('active', i === n));
      prevBtn.disabled = n === 0;
      const percent = Math.round(((n + 1) / steps.length) * 100);
      progressBar.style.width = percent + '%';

      if (n === steps.length - 1) {
        nextBtn.innerHTML = 'Submit <i class="fa fa-check ms-2"></i>';
      } else {
        nextBtn.innerHTML = 'Next <i class="fa fa-arrow-right ms-2"></i>';
      }

      const firstField = steps[n].querySelector('input, textarea');
      if (firstField) firstField.focus();
    }

    function validateStep(n) {
      const fields = Array.from(steps[n].querySelectorAll('input, textarea'));
      for (let f of fields) {
        if (f.name === 'address') continue;
        if (!f.checkValidity()) {
          f.reportValidity();
          return false;
        }
      }
      if (n === 2) {
        const pw = document.getElementById('password').value;
        const cpw = document.getElementById('confirm_password').value;
        const pwLengthErr = document.getElementById('pwLengthErr');
        const pwMatchErr = document.getElementById('pwMatchErr');
        const pwMatchOk = document.getElementById('pwMatchOk');

        pwLengthErr.style.display = 'none';
        pwMatchErr.style.display = 'none';
        pwMatchOk.style.display = 'none';

        if (pw.length < 6) {
          pwLengthErr.style.display = 'block';
          return false;
        }
        if (pw !== cpw) {
          pwMatchErr.style.display = 'block';
          return false;
        }
        pwMatchOk.style.display = 'block';
      }
      return true;
    }

    nextBtn.addEventListener('click', function () {
      if (!validateStep(current)) return;
      if (current < steps.length - 1) {
        current++;
        showStep(current);
      } else {
        if (!form.checkValidity()) {
          const firstInvalid = form.querySelector(':invalid');
          if (firstInvalid) firstInvalid.reportValidity();
          return;
        }
        form.submit();
      }
    });

    prevBtn.addEventListener('click', function () {
      if (current === 0) return;
      current--;
      showStep(current);
    });

    showStep(current);

    // Image preview
    const imageInput = document.getElementById('image');
    const avatarImg = document.getElementById('avatarImg');
    const avatarEmpty = document.getElementById('avatarEmpty');

    imageInput.addEventListener('change', function (ev) {
      const file = ev.target.files[0];
      if (!file) {
        avatarImg.style.display = 'none';
        avatarEmpty.style.display = 'flex';
        return;
      }
      if (file.size > 2 * 1024 * 1024) {
        alert('Image too large. Max 2MB.');
        imageInput.value = '';
        avatarImg.style.display = 'none';
        avatarEmpty.style.display = 'flex';
        return;
      }
      const reader = new FileReader();
      reader.onload = function (e) {
        avatarImg.src = e.target.result;
        avatarImg.style.display = 'block';
        avatarEmpty.style.display = 'none';
      };
      reader.readAsDataURL(file);
    });

    // Enter key navigation
    form.addEventListener('keydown', function (e) {
      if (e.key === 'Enter') {
        const active = document.querySelector('.form-step.active');
        if (document.activeElement && document.activeElement.tagName === 'TEXTAREA') return;
        e.preventDefault();
        nextBtn.click();
      }
    });

    document.getElementById('saveDraft').addEventListener('click', function () {
      alert('Save draft not implemented on server in this demo. Use pro_agent_reg.php to process submissions.');
    });

    (function syncPlanFromUrl() {
      const urlParams = new URLSearchParams(window.location.search);
      if (urlParams.has('plan')) {
        document.getElementById('planInput').value = urlParams.get('plan');
      }
    })();

    // Username availability check
    const usernameInput = document.getElementById('username');
    const usernameFeedback = document.getElementById('usernameFeedback');
    let usernameTimer;
    usernameInput.addEventListener('input', function() {
      clearTimeout(usernameTimer);
      const username = this.value.trim();
      if (username.length < 3) {
        usernameFeedback.textContent = "Username must be at least 3 characters.";
        usernameFeedback.style.color = "#d63384";
        return;
      }
      usernameFeedback.textContent = "Checking...";
      usernameFeedback.style.color = "#6c757d";

      usernameTimer = setTimeout(() => {
        fetch("check_username.php?username=" + encodeURIComponent(username))
          .then(res => res.json())
          .then(data => {
            if (data.available) {
              usernameFeedback.textContent = "Username is available ✔";
              usernameFeedback.style.color = "#198754";
            } else {
              usernameFeedback.textContent = "Username already taken ✖";
              usernameFeedback.style.color = "#d63384";
            }
          })
          .catch(() => {
            usernameFeedback.textContent = "Error checking username.";
            usernameFeedback.style.color = "#d63384";
          });
      }, 400);
    });

    // Live password match check
    const pwInput = document.getElementById('password');
    const cpwInput = document.getElementById('confirm_password');
    const pwMatchErr = document.getElementById('pwMatchErr');
    const pwMatchOk = document.getElementById('pwMatchOk');
    function checkPasswords() {
      pwMatchErr.style.display = 'none';
      pwMatchOk.style.display = 'none';
      if (!pwInput.value || !cpwInput.value) return;
      if (pwInput.value !== cpwInput.value) {
        pwMatchErr.style.display = 'block';
      } else {
        pwMatchOk.style.display = 'block';
      }
    }
    pwInput.addEventListener('input', checkPasswords);
    cpwInput.addEventListener('input', checkPasswords);

  })();
</script>
</body>
</html>
