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

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

$error = $success = '';

// Handle flash messages from register
if (!empty($_SESSION['flash_success'])) {
    $success = $_SESSION['flash_success'];
    unset($_SESSION['flash_success']);
}

// CSRF token
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 {
        $identifier = trim($_POST['identifier'] ?? '');
        $password   = $_POST['password'] ?? '';

        if (empty($identifier) || empty($password)) {
            $error = 'Please fill in all fields.';
        } else {
            // Brute-force protection
            $attempt_key = 'user_attempts_' . md5($identifier);
            $locked_key  = 'user_locked_'   . md5($identifier);

            if (!empty($_SESSION[$locked_key]) && time() < $_SESSION[$locked_key]) {
                $mins = ceil(($_SESSION[$locked_key] - time()) / 60);
                $error = "Too many failed attempts. Try again in {$mins} minute(s).";
            } else {
                $user = db_fetch_one(
                    "SELECT * FROM users WHERE (email = ? OR username = ?) LIMIT 1",
                    [$identifier, $identifier]
                );

                if ($user && password_verify($password, $user['password_hash'])) {
                    if ($user['status'] === 'banned') {
                        $error = 'Your account has been suspended. Please contact admin.';
                    } elseif ($user['status'] === 'inactive') {
                        $error = 'Your account is inactive. Please contact support.';
                    } else {
                        unset($_SESSION[$attempt_key], $_SESSION[$locked_key]);
                        session_regenerate_id(true);

                        $_SESSION['user_id']       = $user['id'];
                        $_SESSION['user_name']     = $user['full_name'];
                        $_SESSION['user_username'] = $user['username'];
                        $_SESSION['user_email']    = $user['email'];
                        $_SESSION['user_avatar']   = $user['avatar'];
                        $_SESSION['user_status']   = $user['status'];
                        $_SESSION['user_login_time'] = time();

                        // Update last login
                        db_execute("UPDATE users SET last_login = NOW() WHERE id = ?", [$user['id']]);

                        // Log to activity_log for admin visibility
                        db_execute(
                            "INSERT INTO activity_log (admin_id, action, target_type, target_id, target_name, details, ip_address)
                             SELECT id, 'user_login', 'user', ?, ?, 'User logged in from website', ? FROM admins WHERE role='super_admin' LIMIT 1",
                            [$user['id'], $user['full_name'], $_SERVER['REMOTE_ADDR']]
                        );

                        header('Location: dashboard.php'); exit;
                    }
                } else {
                    $_SESSION[$attempt_key] = ($_SESSION[$attempt_key] ?? 0) + 1;
                    if ($_SESSION[$attempt_key] >= 5) {
                        $_SESSION[$locked_key] = time() + 900;
                        $error = 'Too many failed attempts. Account locked for 15 minutes.';
                    } else {
                        $left  = 5 - $_SESSION[$attempt_key];
                        $error = "Invalid credentials. {$left} attempt(s) remaining.";
                    }
                }
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width,initial-scale=1.0"/>
<title>Sign In — 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>
/* ── TOKENS matching Wadata brand ──────────────────────── */
: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);
  --sh2:       0 20px 60px rgba(11,37,69,.18);
  --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{height:100%;font-family:'Plus Jakarta Sans',sans-serif;background:var(--page);color:var(--tb);overflow-x:hidden}

/* ── SCENE ─────────────────────────────────────────────── */
.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%),
    radial-gradient(ellipse 50% 50% at 55% 50%, rgba(255,165,0,.12),transparent 60%)}
.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}
.oc{width:240px;height:240px;background:radial-gradient(#ffa500,transparent 70%);top:38%;left:54%;opacity:.22;animation-duration:21s;animation-delay:-12s}
@keyframes drift{0%{transform:translate(0,0) scale(1)}100%{transform:translate(40px,28px) scale(1.07)}}

/* ── PAGE ──────────────────────────────────────────────── */
.page{position:relative;z-index:1;display:grid;grid-template-columns:1.15fr 1fr;min-height:100vh}

/* ── LEFT BRAND ────────────────────────────────────────── */
.brand{display:flex;flex-direction:column;justify-content:center;padding:60px 64px;position:relative;overflow:hidden}
.brand::before{content:'';position:absolute;width:320px;height:320px;border-radius:50%;
  background:rgba(255,255,255,.07);border:1px solid rgba(255,255,255,.1);top:-90px;right:-80px}
.brand::after{content:'';position:absolute;width:180px;height:180px;border-radius:50%;
  background:rgba(255,255,255,.04);border:1px solid rgba(255,255,255,.08);bottom:60px;left:-50px}

.bl-logo{display:flex;align-items:center;gap:14px;margin-bottom:46px}
.bl-logo-wrap{width:56px;height:56px;border-radius:16px;background:#fff;padding:7px;
  box-shadow:0 6px 24px rgba(255,106,0,.25);display:grid;place-items:center;overflow:hidden}
.bl-logo-wrap img{width:100%;height:100%;object-fit:contain}
.bl-logo-wrap .fallback{width:100%;height:100%;border-radius:10px;
  background:linear-gradient(135deg,var(--accent),var(--primary));display:grid;place-items:center;color:#fff;font-size:22px}
.bl-name strong{display:block;font-family:'Epilogue',sans-serif;font-size:20px;font-weight:800;color:var(--th);letter-spacing:-.3px}
.bl-name em{font-style:normal;font-size:10px;font-weight:700;letter-spacing:2px;text-transform:uppercase;color:var(--accent)}

.bl-hl{font-family:'Epilogue',sans-serif;font-size:clamp(26px,2.8vw,40px);font-weight:800;
  color:var(--th);line-height:1.15;letter-spacing:-.6px;margin-bottom:16px}
.bl-hl em{font-style:normal;background:linear-gradient(130deg,var(--accent) 20%,#ffa500 60%,var(--primary) 100%);
  -webkit-background-clip:text;-webkit-text-fill-color:transparent;background-clip:text}

.bl-sub{font-size:14.5px;color:var(--tm);line-height:1.75;max-width:370px;margin-bottom:38px}

/* Stats strip */
.bl-stats{display:flex;gap:24px;margin-bottom:40px;padding:18px 22px;
  background:var(--glass);border:1px solid var(--bdr);border-radius:14px;
  backdrop-filter:blur(20px);-webkit-backdrop-filter:blur(20px)}
.bls-item{text-align:center;flex:1}
.bls-n{font-family:'Epilogue',sans-serif;font-size:26px;font-weight:800;color:var(--accent);line-height:1}
.bls-l{font-size:10px;font-weight:700;color:var(--tm);text-transform:uppercase;letter-spacing:.8px;margin-top:2px}
.bls-div{width:1px;background:var(--bdr2);align-self:stretch}

/* Feature pills */
.bl-feats{display:flex;flex-direction:column;gap:9px}
.blfeat{display:flex;align-items:center;gap:11px;padding:11px 16px;
  background:var(--glass);border:1px solid var(--bdr);border-radius:12px;
  backdrop-filter:blur(20px);-webkit-backdrop-filter:blur(20px);
  font-size:13px;font-weight:600;color:var(--tb);max-width:360px;
  transition:transform .2s;animation:slideR .6s cubic-bezier(.22,1,.36,1) both}
.blfeat:hover{transform:translateX(4px)}
.blfeat:nth-child(1){animation-delay:.1s}.blfeat:nth-child(2){animation-delay:.18s}.blfeat:nth-child(3){animation-delay:.26s}
@keyframes slideR{from{opacity:0;transform:translateX(-14px)}to{opacity:1;transform:translateX(0)}}
.blfeat-ico{width:32px;height:32px;border-radius:9px;display:grid;place-items:center;font-size:13px;flex-shrink:0}

/* ── RIGHT FORM ────────────────────────────────────────── */
.form-side{display:flex;align-items:center;justify-content:center;padding:40px 32px;
  background:rgba(255,255,255,.30);backdrop-filter:blur(12px);-webkit-backdrop-filter:blur(12px);
  border-left:1px solid var(--bdr2)}

.card{width:100%;max-width:430px;
  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:42px 38px;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}}

.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:16px}

.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:26px;line-height:1.55}

/* Alert */
.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}
.as{background:rgba(16,185,129,.08);border:1px solid rgba(16,185,129,.25);color:#065F46}

/* Form */
.fg{margin-bottom:16px}
.fl{display:block;font-size:11px;font-weight:800;letter-spacing:.9px;text-transform:uppercase;color:var(--tm);margin-bottom:7px}
.iw{position:relative}
.ii{position:absolute;left:14px;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:12px;
  padding:12px 15px 12px 42px;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:40px}

/* Row */
.fr{display:flex;align-items:center;justify-content:space-between;margin-bottom:22px}
.cw{display:flex;align-items:center;gap:8px;cursor:pointer;font-size:13px;color:var(--tm);font-weight:600;user-select:none}
.cw input[type=checkbox]{appearance:none;width:16px;height:16px;border:1.5px solid var(--bdr2);border-radius:5px;
  background:rgba(255,255,255,.88);cursor:pointer;display:grid;place-items:center;transition:all .2s;flex-shrink:0}
.cw input:checked{background:var(--accent);border-color:var(--accent)}
.cw 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}
.fgt{font-size:12.5px;color:var(--primary);text-decoration:none;font-weight:700;transition:color .2s}
.fgt:hover{color:var(--accent)}

/* Button */
.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);letter-spacing:.1px}
.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:20px 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)}

.cta-link{display:block;text-align:center;font-size:13px;color:var(--tm);margin-top:14px}
.cta-link a{color:var(--primary);font-weight:800;text-decoration:none;transition:color .2s}
.cta-link a:hover{color:var(--accent)}

.cf{margin-top:12px;text-align:center;font-size:11px;color:var(--tm)}

/* ── RESPONSIVE ────────────────────────────────────────── */
@media(max-width:860px){.page{grid-template-columns:1fr}.brand{display:none}.form-side{padding:24px 16px;border-left:none}}
</style>
</head>
<body>

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

<div class="page">

  <!-- LEFT BRAND -->
  <div class="brand">
    <div class="bl-logo">
      <div class="bl-logo-wrap">
        <img src="../assets/img/logo.png" alt="Wadata"
             onerror="this.parentElement.innerHTML='<div class=fallback><i class=\'fas fa-graduation-cap\'></i></div>'"/>
      </div>
      <div class="bl-name">
        <strong>WADATA</strong>
        <em>Skill Acquisition Center</em>
      </div>
    </div>

    <div class="bl-stats">
      <div class="bls-item"><div class="bls-n">5K+</div><div class="bls-l">Graduates</div></div>
      <div class="bls-div"></div>
      <div class="bls-item"><div class="bls-n">50+</div><div class="bls-l">Programmes</div></div>
      <div class="bls-div"></div>
      <div class="bls-item"><div class="bls-n">95%</div><div class="bls-l">Employment</div></div>
    </div>

    <h1 class="bl-hl">Welcome Back to<br><em>Your Skills Journey</em></h1>
    <p class="bl-sub">Sign in to access your learning dashboard, track your progress, view certifications, and connect with your instructors.</p>

    <div class="bl-feats">
      <div class="blfeat">
        <div class="blfeat-ico" style="background:rgba(255,106,0,.12);color:var(--accent)"><i class="fas fa-chart-line"></i></div>
        Track your learning progress
      </div>
      <div class="blfeat">
        <div class="blfeat-ico" style="background:rgba(11,37,69,.10);color:var(--primary)"><i class="fas fa-certificate"></i></div>
        Access your certifications
      </div>
      <div class="blfeat">
        <div class="blfeat-ico" style="background:rgba(16,185,129,.10);color:#059669"><i class="fas fa-comments"></i></div>
        Connect with instructors
      </div>
    </div>
  </div>

  <!-- RIGHT FORM -->
  <div class="form-side">
    <div class="card">

      <div class="eyebrow"><i class="fas fa-graduation-cap"></i> Student Portal</div>
      <h1 class="card-h">Sign In</h1>
      <p class="card-s">Access your Wadata learning account.</p>

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

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

        <div class="fg">
          <label class="fl" for="identifier">Email or Username</label>
          <div class="iw">
            <input type="text" id="identifier" name="identifier" class="fi"
                   placeholder="your@email.com or username"
                   value="<?= htmlspecialchars($_POST['identifier'] ?? '') ?>"
                   autocomplete="username" required/>
            <i class="fas fa-at 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="Enter your password" autocomplete="current-password" required/>
            <i class="fas fa-lock ii"></i>
            <button type="button" class="pt" id="pti"><i class="fas fa-eye" id="pio"></i></button>
          </div>
        </div>

        <div class="fr">
          <label class="cw"><input type="checkbox" name="remember"/> Remember me</label>
          <a href="forgot-password.php" class="fgt">Forgot password?</a>
        </div>

        <button type="submit" class="btn-s" id="sb">
          <span class="bt"><i class="fas fa-right-to-bracket"></i> Sign In</span>
          <span class="spin"></span>
        </button>
      </form>

      <div class="dv">New to Wadata?</div>
      <a href="register.php" style="display:flex;align-items:center;justify-content:center;gap:8px;padding:12px;
         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"
         onmouseover="this.style.background='rgba(11,37,69,.12)'" onmouseout="this.style.background='rgba(11,37,69,.07)'">
        <i class="fas fa-user-plus" style="color:var(--accent)"></i> Create Free Account
      </a>

      <div class="cf"><i class="fas fa-shield-halved" style="color:var(--accent);font-size:10px;margin-right:4px"></i>Your data is safe and encrypted</div>
    </div>
  </div>

</div>

<script>
document.getElementById('pti').onclick=function(){
  const p=document.getElementById('password'),i=document.getElementById('pio'),s=p.type==='password';
  p.type=s?'text':'password';i.className=s?'fas fa-eye-slash':'fas fa-eye';
};
document.getElementById('lf').addEventListener('submit',function(e){
  const id=document.getElementById('identifier').value.trim();
  const pw=document.getElementById('password').value;
  if(!id||!pw){e.preventDefault();return;}
  const b=document.getElementById('sb');b.classList.add('loading');b.disabled=true;
});
</script>
</body>
</html>
