<?php
// ============================================================
//  user/register.php — Wadata User Registration
// ============================================================
session_start();
require_once '../includes/db.php';

if (!empty($_SESSION['user_id'])) { header('Location: dashboard.php'); exit; }

$error = $success = '';
$form  = [];

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (empty($_POST['csrf']) || $_POST['csrf'] !== $_SESSION['user_csrf']) {
        $error = 'Invalid request. Please try again.';
    } else {
        $form = [
            'full_name' => trim($_POST['full_name'] ?? ''),
            'username'  => trim($_POST['username']  ?? ''),
            'email'     => trim($_POST['email']     ?? ''),
            'phone'     => trim($_POST['phone']     ?? ''),
            'password'  => $_POST['password']  ?? '',
            'confirm'   => $_POST['confirm']   ?? '',
        ];

        // Validate
        $errors = [];
        if (strlen($form['full_name']) < 2)   $errors[] = 'Full name must be at least 2 characters.';
        if (!preg_match('/^[a-zA-Z0-9_]{3,30}$/', $form['username'])) $errors[] = 'Username must be 3-30 chars (letters, numbers, underscore only).';
        if (!filter_var($form['email'], FILTER_VALIDATE_EMAIL))        $errors[] = 'Please enter a valid email address.';
        if (strlen($form['password']) < 8)    $errors[] = 'Password must be at least 8 characters.';
        if ($form['password'] !== $form['confirm']) $errors[] = 'Passwords do not match.';

        // Check password strength
        if (strlen($form['password']) >= 8 && !preg_match('/[A-Z]/', $form['password']))    $errors[] = 'Password must contain at least one uppercase letter.';
        if (strlen($form['password']) >= 8 && !preg_match('/[0-9]/', $form['password']))    $errors[] = 'Password must contain at least one number.';

        if (empty($errors)) {
            // Check uniqueness
            $exists = db_fetch_one("SELECT id FROM users WHERE email = ? OR username = ? LIMIT 1", [$form['email'], $form['username']]);
            if ($exists) {
                $error = 'Email or username already taken. Please choose another.';
            } else {
                $hash = password_hash($form['password'], PASSWORD_BCRYPT);
                db_execute(
                    "INSERT INTO users (full_name, username, email, password_hash, phone, status, email_verified, created_at)
                     VALUES (?, ?, ?, ?, ?, 'pending', 0, NOW())",
                    [$form['full_name'], $form['username'], $form['email'], $hash, $form['phone']]
                );
                $new_id = db_last_id();

                // Log for admin
                db_execute(
                    "INSERT INTO activity_log (admin_id, action, target_type, target_id, target_name, details, ip_address)
                     SELECT id, 'user_registered', 'user', ?, ?, 'New user registered from website', ? FROM admins WHERE role='super_admin' LIMIT 1",
                    [$new_id, $form['full_name'], $_SERVER['REMOTE_ADDR']]
                );

                $_SESSION['flash_success'] = 'Account created successfully! Your account is pending approval. You can sign in once approved.';
                header('Location: login.php'); exit;
            }
        } else {
            $error = implode(' ', $errors);
        }
    }
}
$v = fn($k) => htmlspecialchars($form[$k] ?? '');
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width,initial-scale=1.0"/>
<title>Create Account — WADATA Skills Acquisition Center</title>
<link rel="icon" type="image/png" href="../assets/img/logo.png"/>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet"/>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.2/css/all.min.css"/>
<link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&family=Epilogue:wght@700;800&display=swap" rel="stylesheet"/>
<style>
:root {
  --primary:#0B2545; --primary-l:#1e3a5f;
  --accent:#FF6A00;  --accent-l:#ff8533;
  --light:#F6F9FC;
  --glass:rgba(255,255,255,.70); --glass2:rgba(255,255,255,.45);
  --bdr:rgba(255,255,255,.80);   --bdr2:rgba(11,37,69,.12);
  --sh:0 8px 40px rgba(11,37,69,.13),0 2px 8px rgba(0,0,0,.05);
  --sh-inp:0 0 0 3px rgba(255,106,0,.20);
  --page:#D6E4F5; --th:#0B2545; --tb:#2D3E5E; --tm:#6C7E9A;
  --t:.22s cubic-bezier(.22,1,.36,1);
}
*,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
html,body{min-height:100%;font-family:'Plus Jakarta Sans',sans-serif;background:var(--page);color:var(--tb)}

.scene{position:fixed;inset:0;z-index:0;overflow:hidden;pointer-events:none}
.scene::before{content:'';position:absolute;inset:0;
  background:radial-gradient(ellipse 70% 60% at 5% 8%,rgba(255,106,0,.18),transparent 55%),
             radial-gradient(ellipse 65% 70% at 95% 92%,rgba(11,37,69,.14),transparent 55%)}
.scene::after{content:'';position:absolute;inset:0;
  background-image:linear-gradient(rgba(11,37,69,.035) 1px,transparent 1px),linear-gradient(90deg,rgba(11,37,69,.035) 1px,transparent 1px);
  background-size:54px 54px}
.orb{position:absolute;border-radius:50%;filter:blur(88px);animation:drift ease-in-out infinite alternate;pointer-events:none}
.oa{width:480px;height:480px;background:radial-gradient(#ff8533,transparent 70%);top:-170px;left:-90px;opacity:.42;animation-duration:17s}
.ob{width:380px;height:380px;background:radial-gradient(#1e3a5f,transparent 70%);bottom:-110px;right:-80px;opacity:.35;animation-duration:14s;animation-delay:-7s}
@keyframes drift{0%{transform:translate(0,0) scale(1)}100%{transform:translate(40px,28px) scale(1.07)}}

.wrap{position:relative;z-index:1;display:flex;align-items:center;justify-content:center;
  min-height:100vh;padding:40px 20px}

.card{width:100%;max-width:560px;
  background:var(--glass);border:1px solid var(--bdr);border-radius:26px;
  backdrop-filter:blur(36px) saturate(180%);-webkit-backdrop-filter:blur(36px) saturate(180%);
  padding:44px 40px;box-shadow:var(--sh);
  animation:cardIn .65s cubic-bezier(.22,1,.36,1) both}
@keyframes cardIn{from{opacity:0;transform:translateY(22px) scale(.97)}to{opacity:1;transform:none}}

/* Logo bar */
.logo-bar{display:flex;align-items:center;gap:12px;margin-bottom:26px}
.lb-ico{width:46px;height:46px;border-radius:13px;background:#fff;padding:6px;
  box-shadow:0 4px 16px rgba(255,106,0,.22);display:grid;place-items:center;overflow:hidden}
.lb-ico img{width:100%;height:100%;object-fit:contain}
.lb-name strong{display:block;font-family:'Epilogue',sans-serif;font-size:17px;font-weight:800;color:var(--th)}
.lb-name em{font-style:normal;font-size:9.5px;font-weight:700;letter-spacing:2px;text-transform:uppercase;color:var(--accent)}

.eyebrow{display:inline-flex;align-items:center;gap:7px;padding:5px 13px;border-radius:20px;
  background:linear-gradient(135deg,rgba(255,106,0,.12),rgba(11,37,69,.08));
  border:1px solid rgba(255,106,0,.18);font-size:11px;font-weight:800;
  letter-spacing:1.2px;text-transform:uppercase;color:var(--accent);margin-bottom:14px}
.card-h{font-family:'Epilogue',sans-serif;font-size:24px;font-weight:800;color:var(--th);margin-bottom:4px;letter-spacing:-.4px}
.card-s{font-size:13px;color:var(--tm);margin-bottom:24px;line-height:1.55}

.al{display:flex;align-items:flex-start;gap:9px;padding:12px 15px;border-radius:12px;
  font-size:13px;font-weight:600;margin-bottom:18px;animation:alIn .3s ease both}
@keyframes alIn{from{opacity:0;transform:translateY(-5px)}to{opacity:1;transform:none}}
.ae{background:rgba(220,38,38,.08);border:1px solid rgba(220,38,38,.22);color:#991B1B}

/* Two column grid */
.fg2{display:grid;grid-template-columns:1fr 1fr;gap:14px;margin-bottom:2px}
.fg{margin-bottom:14px}
.fl{display:block;font-size:11px;font-weight:800;letter-spacing:.9px;text-transform:uppercase;color:var(--tm);margin-bottom:6px}
.iw{position:relative}
.ii{position:absolute;left:13px;top:50%;transform:translateY(-50%);font-size:13px;color:var(--tm);pointer-events:none;transition:color .2s}
.fi{width:100%;background:rgba(255,255,255,.88);border:1.5px solid var(--bdr2);border-radius:11px;
  padding:11px 14px 11px 40px;color:var(--th);font-family:'Plus Jakarta Sans',sans-serif;
  font-size:14px;font-weight:500;outline:none;transition:border-color .22s,box-shadow .22s;-webkit-appearance:none}
.fi::placeholder{color:var(--tm);font-weight:400}
.fi:focus{border-color:var(--accent);box-shadow:var(--sh-inp)}
.iw:focus-within .ii{color:var(--accent)}
.pt{position:absolute;right:12px;top:50%;transform:translateY(-50%);background:none;border:none;color:var(--tm);cursor:pointer;font-size:13px;padding:4px;transition:color .2s}
.pt:hover{color:var(--accent)}
.ht{padding-right:38px}

/* Strength meter */
.strength{margin-top:7px}
.strength-bars{display:flex;gap:4px;margin-bottom:5px}
.sb{height:4px;flex:1;border-radius:3px;background:var(--bdr2);transition:background .3s}
.strength-txt{font-size:10.5px;font-weight:700;color:var(--tm)}

/* Rules */
.rules{display:grid;grid-template-columns:1fr 1fr;gap:4px 8px;margin-top:8px}
.rule{display:flex;align-items:center;gap:5px;font-size:10.5px;color:var(--tm);font-weight:600;transition:color .2s}
.rule i{font-size:9px;transition:color .2s}
.rule.ok{color:#059669}.rule.ok i{color:#059669}

/* Terms */
.terms{display:flex;align-items:flex-start;gap:9px;margin-bottom:20px;font-size:12.5px;color:var(--tm)}
.terms input[type=checkbox]{appearance:none;width:16px;height:16px;border:1.5px solid var(--bdr2);border-radius:4px;
  background:rgba(255,255,255,.88);cursor:pointer;display:grid;place-items:center;transition:all .2s;flex-shrink:0;margin-top:1px}
.terms input:checked{background:var(--accent);border-color:var(--accent)}
.terms input:checked::before{content:'';width:9px;height:9px;
  background:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 12 12'%3E%3Cpath d='M2 6l3 3 5-5' stroke='white' stroke-width='2.2' fill='none' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E") center/contain no-repeat}
.terms a{color:var(--primary);font-weight:700;text-decoration:none}
.terms a:hover{color:var(--accent)}

.btn-s{width:100%;padding:14px;
  background:linear-gradient(130deg,var(--accent) 0%,var(--accent-l) 45%,var(--primary) 100%);
  background-size:200% 100%;background-position:0 0;
  border:none;border-radius:13px;color:#fff;
  font-family:'Epilogue',sans-serif;font-size:15px;font-weight:800;cursor:pointer;
  display:flex;align-items:center;justify-content:center;gap:9px;
  transition:background-position .45s,transform .2s,box-shadow .2s;
  box-shadow:0 6px 28px rgba(255,106,0,.38)}
.btn-s:hover{background-position:100% 0;transform:translateY(-2px);box-shadow:0 10px 36px rgba(255,106,0,.48)}
.btn-s:active{transform:none}
.spin{display:none;width:15px;height:15px;border:2px solid rgba(255,255,255,.4);
  border-top-color:#fff;border-radius:50%;animation:sp .6s linear infinite}
@keyframes sp{to{transform:rotate(360deg)}}
.btn-s.loading .bt{display:none}.btn-s.loading .spin{display:block}

.dv{display:flex;align-items:center;gap:12px;margin:18px 0 0;font-size:10.5px;letter-spacing:1.2px;text-transform:uppercase;color:var(--tm);font-weight:700}
.dv::before,.dv::after{content:'';flex:1;height:1px;background:var(--bdr2)}
.sign-in-lnk{display:flex;align-items:center;justify-content:center;gap:8px;margin-top:12px;padding:11px;
  border-radius:13px;background:rgba(11,37,69,.07);border:1.5px solid rgba(11,37,69,.12);
  font-family:'Epilogue',sans-serif;font-size:14px;font-weight:800;color:var(--primary);text-decoration:none;transition:all .2s}
.sign-in-lnk:hover{background:rgba(11,37,69,.12);color:var(--primary)}
</style>
</head>
<body>

<div class="scene"><div class="orb oa"></div><div class="orb ob"></div></div>

<div class="wrap">
  <div class="card">

    <div class="logo-bar">
      <div class="lb-ico">
        <img src="../assets/img/logo.png" alt="Wadata"
             onerror="this.parentElement.innerHTML='<i class=\'fas fa-graduation-cap\' style=\'font-size:20px;color:var(--accent)\'></i>'"/>
      </div>
      <div class="lb-name"><strong>WADATA</strong><em>Skill Acquisition Center</em></div>
    </div>

    <div class="eyebrow"><i class="fas fa-user-plus"></i> Create Account</div>
    <h1 class="card-h">Join WADATA</h1>
    <p class="card-s">Start your skills journey today — it's free.</p>

    <?php if ($error): ?>
      <div class="al ae"><i class="fas fa-circle-exclamation"></i><span><?= htmlspecialchars($error) ?></span></div>
    <?php endif; ?>

    <form method="POST" id="rf" autocomplete="off" novalidate>
      <input type="hidden" name="csrf" value="<?= htmlspecialchars($_SESSION['user_csrf']) ?>"/>

      <div class="fg2">
        <div class="fg" style="margin-bottom:0">
          <label class="fl" for="full_name">Full Name</label>
          <div class="iw">
            <input type="text" id="full_name" name="full_name" class="fi" placeholder="Your full name" value="<?= $v('full_name') ?>" required/>
            <i class="fas fa-user ii"></i>
          </div>
        </div>
        <div class="fg" style="margin-bottom:0">
          <label class="fl" for="username">Username</label>
          <div class="iw">
            <input type="text" id="username" name="username" class="fi" placeholder="choose_username" value="<?= $v('username') ?>" required/>
            <i class="fas fa-at ii"></i>
          </div>
        </div>
      </div>
      <div style="margin-bottom:14px"></div>

      <div class="fg">
        <label class="fl" for="email">Email Address</label>
        <div class="iw">
          <input type="email" id="email" name="email" class="fi" placeholder="your@email.com" value="<?= $v('email') ?>" required/>
          <i class="fas fa-envelope ii"></i>
        </div>
      </div>

      <div class="fg">
        <label class="fl" for="phone">Phone Number <span style="color:var(--tm);font-weight:400">(optional)</span></label>
        <div class="iw">
          <input type="tel" id="phone" name="phone" class="fi" placeholder="+234 xxx xxx xxxx" value="<?= $v('phone') ?>"/>
          <i class="fas fa-phone ii"></i>
        </div>
      </div>

      <div class="fg">
        <label class="fl" for="password">Password</label>
        <div class="iw">
          <input type="password" id="password" name="password" class="fi ht"
                 placeholder="Min. 8 characters" required oninput="checkPw(this.value)"/>
          <i class="fas fa-lock ii"></i>
          <button type="button" class="pt" onclick="togglePw('password','pico')"><i class="fas fa-eye" id="pico"></i></button>
        </div>
        <!-- Strength meter -->
        <div class="strength">
          <div class="strength-bars">
            <div class="sb" id="sb1"></div><div class="sb" id="sb2"></div>
            <div class="sb" id="sb3"></div><div class="sb" id="sb4"></div>
          </div>
          <div class="strength-txt" id="stxt">Enter a password</div>
          <div class="rules">
            <div class="rule" id="r-len"><i class="fas fa-circle"></i> 8+ characters</div>
            <div class="rule" id="r-upper"><i class="fas fa-circle"></i> Uppercase letter</div>
            <div class="rule" id="r-num"><i class="fas fa-circle"></i> Number</div>
            <div class="rule" id="r-special"><i class="fas fa-circle"></i> Special char</div>
          </div>
        </div>
      </div>

      <div class="fg">
        <label class="fl" for="confirm">Confirm Password</label>
        <div class="iw">
          <input type="password" id="confirm" name="confirm" class="fi ht"
                 placeholder="Repeat your password" required oninput="checkMatch()"/>
          <i class="fas fa-lock ii"></i>
          <button type="button" class="pt" onclick="togglePw('confirm','cico')"><i class="fas fa-eye" id="cico"></i></button>
        </div>
        <div style="font-size:11px;margin-top:5px;font-weight:700" id="match-msg"></div>
      </div>

      <label class="terms">
        <input type="checkbox" name="terms" id="terms" required/>
        <span>I agree to the <a href="#">Terms of Service</a> and <a href="#">Privacy Policy</a> of WADATA Skills Acquisition Center.</span>
      </label>

      <button type="submit" class="btn-s" id="sb">
        <span class="bt"><i class="fas fa-user-plus"></i> Create My Account</span>
        <span class="spin"></span>
      </button>
    </form>

    <div class="dv">Already have an account?</div>
    <a href="login.php" class="sign-in-lnk">
      <i class="fas fa-right-to-bracket" style="color:var(--accent)"></i> Sign In
    </a>

  </div>
</div>

<script>
function togglePw(id, icoId) {
  const p = document.getElementById(id), i = document.getElementById(icoId), s = p.type === 'password';
  p.type = s ? 'text' : 'password';
  i.className = s ? 'fas fa-eye-slash' : 'fas fa-eye';
}

function checkPw(v) {
  const rules = {
    'r-len':     v.length >= 8,
    'r-upper':   /[A-Z]/.test(v),
    'r-num':     /[0-9]/.test(v),
    'r-special': /[^A-Za-z0-9]/.test(v),
  };
  let score = Object.values(rules).filter(Boolean).length;
  const colors = ['','#EF4444','#F59E0B','#3B82F6','#10B981'];
  const labels = ['','Weak','Fair','Good','Strong'];
  [1,2,3,4].forEach(n => {
    const el = document.getElementById('sb'+n);
    el.style.background = n <= score ? colors[score] : 'rgba(11,37,69,.12)';
  });
  document.getElementById('stxt').textContent = v.length ? labels[score] : 'Enter a password';
  document.getElementById('stxt').style.color = colors[score] || 'var(--tm)';
  Object.entries(rules).forEach(([id, ok]) => {
    const el = document.getElementById(id);
    el.classList.toggle('ok', ok);
    el.querySelector('i').className = ok ? 'fas fa-circle-check' : 'fas fa-circle';
  });
}

function checkMatch() {
  const p = document.getElementById('password').value;
  const c = document.getElementById('confirm').value;
  const m = document.getElementById('match-msg');
  if (!c) { m.textContent = ''; return; }
  if (p === c) { m.style.color = '#059669'; m.textContent = '✓ Passwords match'; }
  else         { m.style.color = '#DC2626'; m.textContent = '✗ Passwords do not match'; }
}

document.getElementById('rf').addEventListener('submit', function(e) {
  if (!document.getElementById('terms').checked) {
    e.preventDefault(); alert('Please agree to the Terms of Service.'); return;
  }
  const b = document.getElementById('sb'); b.classList.add('loading'); b.disabled = true;
});
</script>
</body>
</html>
