<?php
require_once __DIR__ . '/../app/helpers/functions.php';
require_once __DIR__ . '/../app/helpers/otp.php';

session_boot();
$conn = require __DIR__ . '/../app/config/database.php';

/* MUST COME FROM login.php */
$userId = (int)($_SESSION['otp_user'] ?? 0);
if (!$userId) {
  redirect('login.php');
}

$error = '';

if (is_post()) {

  $code = trim($_POST['code'] ?? '');

  if ($code === '') {
    $error = 'OTP code required';
  } else {

    // ✅ CORRECT OTP verification (MySQLi + correct order)
    $ok = otp_verify($conn, $userId, 'login', $code);

    if (!$ok) {
      $error = 'Invalid or expired OTP';
    } else {

      // Load user
      $st = $conn->prepare("SELECT * FROM users WHERE id=? LIMIT 1");
      $st->bind_param("i", $userId);
      $st->execute();
      $user = $st->get_result()->fetch_assoc();

      if (!$user || ($user['status'] ?? 'active') !== 'active') {
        session_destroy();
        redirect('login.php');
      }

      // ✅ Login success
      session_regenerate_id(true);
      $_SESSION['user'] = $user;
      unset($_SESSION['otp_user']);

      // ✅ Redirect to dashboard
      header("Location: /customer/dashboard.php");
      exit;
    }
  }
}
?>
<!DOCTYPE html>
<html>
<head>
  <title>Verify OTP | Astrabank</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>

<body class="bg-dark d-flex align-items-center justify-content-center min-vh-100">

<div class="card p-4 shadow" style="width:360px">
  <h5 class="fw-bold text-center mb-3 text-warning">Verify OTP</h5>

  <?php if ($error): ?>
    <div class="alert alert-danger text-center"><?= e($error) ?></div>
  <?php endif; ?>

  <form method="post" autocomplete="off">
    <div class="mb-3">
      <label class="form-label">Enter 6-digit code</label>
      <input
        type="text"
        name="code"
        class="form-control text-center fs-4"
        maxlength="6"
        required>
    </div>

    <button class="btn btn-warning w-100 fw-semibold">
      Verify & Continue
    </button>

    <div class="text-center mt-3">
  <button
    id="resendBtn"
    class="btn btn-link text-warning"
    onclick="resendOtp()"
    disabled>
    Resend OTP (<span id="timer">60</span>s)
  </button>
</div>

  </form>
</div>
<script>
let seconds = 60;
const btn = document.getElementById('resendBtn');
const timer = document.getElementById('timer');

const countdown = setInterval(() => {
  seconds--;
  timer.innerText = seconds;

  if (seconds <= 0) {
    clearInterval(countdown);
    btn.disabled = false;
    btn.innerText = 'Resend OTP';
  }
}, 1000);

function resendOtp() {
  btn.disabled = true;
  btn.innerText = 'Sending...';

  fetch('/astrabank/public/resend_otp.php')
    .then(res => res.json())
    .then(data => {
      if (data.error) {
        alert(data.error);
        return;
      }
      alert('New OTP sent');
    })
    .catch(() => alert('Network error'));
}
</script>

</body>
</html>
