<?php
require_once __DIR__ . '/../app/helpers/functions.php';
require_once __DIR__ . '/../app/helpers/csrf.php';
require_once __DIR__ . '/../app/helpers/otp.php';
require_once __DIR__ . '/../app/middleware/auth.php';
$pdo = require __DIR__ . '/../app/config/database.php';

session_boot();

$pendingId = (int)($_SESSION['pending_login_user_id'] ?? 0);
$purpose   = $_SESSION['pending_otp_purpose'] ?? 'login';

if (!$pendingId) {
  flash('err', 'No pending verification session. Please login again.');
  redirect('login.php');
}

if (is_post()) {
  csrf_verify();
  $otp = trim($_POST['otp'] ?? '');
  if (otp_verify($pdo, $pendingId, $purpose, $otp)) {
    $stmt = $pdo->prepare("SELECT id, full_name, email, status, kyc_status FROM users WHERE id=?");
    $stmt->execute([$pendingId]);
    $user = $stmt->fetch();

    if (!$user || $user['status'] !== 'active') {
      flash('err', 'Account not active.');
      redirect('login.php');
    }

    unset($_SESSION['pending_login_user_id'], $_SESSION['pending_otp_purpose']);
    $_SESSION['user'] = $user;

    // route by role
    if (user_has_role($pdo, (int)$user['id'], ['super_admin','ops','compliance','support'])) {
      redirect('admin/dashboard.php');
    }
    redirect('customer/dashboard.php');
  } else {
    flash('err', 'Invalid or expired OTP.');
  }
}

$title = 'Verify OTP';
include __DIR__ . '/../views/partials/head.php';
include __DIR__ . '/../views/partials/nav_website.php';
?>

<div class="container py-5" style="max-width:560px">
  <div class="card ab-card p-4">
    <h3 class="fw-bold mb-1">Verify your login</h3>
    <div class="ab-muted mb-3">We sent a 6-digit OTP to your email. Enter it to continue.</div>

    <?php if ($m = flash('err')): ?>
      <div class="alert alert-danger mb-3"><?= e($m) ?></div>
    <?php endif; ?>

    <form method="post">
      <?= csrf_field() ?>
      <label class="form-label">OTP Code</label>
      <input class="form-control form-control-lg" name="otp" inputmode="numeric" pattern="[0-9]{6}" maxlength="6" required>
      <button class="btn ab-btn text-white w-100 mt-3">Verify</button>
      <div class="ab-muted mt-3" style="font-size:12px">Tip: check Spam/Junk if you don’t see it.</div>
    </form>
  </div>
</div>

<?php include __DIR__ . '/../views/partials/foot.php'; ?>
