<?php
require_once __DIR__ . '/../app/helpers/functions.php';
require_once __DIR__ . '/../app/helpers/mailer.php'; // ✅ ADD: PHPMailer helper

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

/* ===============================
   ALREADY VERIFIED → DASHBOARD
================================ */
if (!empty($_SESSION['customer']['id'])) {
    redirect('/customer/dashboard.php');
}

/* ===============================
   PIN STEP REQUIRED
================================ */
if (empty($_SESSION['pin_user']) || empty($_SESSION['pin_time'])) {
    redirect('/customer/login.php');
}

/* ===============================
   PIN EXPIRY (3 MINUTES)
================================ */
if (time() - (int)$_SESSION['pin_time'] > 180) {
    unset($_SESSION['pin_user'], $_SESSION['pin_time']);
    redirect('/customer/login.php');
}

$error = '';

/* ===============================
   HANDLE PIN SUBMIT
================================ */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

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

    if (!ctype_digit($pin) || strlen($pin) < 4 || strlen($pin) > 6) {
        $error = "Invalid PIN";
    } else {

        $uid = (int) $_SESSION['pin_user'];

        $st = $conn->prepare("
            SELECT id, email, full_name, kyc_status, pin_hash
            FROM users
            WHERE id = ?
            LIMIT 1
        ");
        $st->bind_param("i", $uid);
        $st->execute();
        $user = $st->get_result()->fetch_assoc();

        if (!$user || !password_verify($pin, $user['pin_hash'])) {
            $error = "Incorrect PIN";
        } else {

            /* ===============================
               ✅ COMPLETE CUSTOMER LOGIN
            ================================ */

            session_regenerate_id(true);

            $_SESSION['customer'] = [
                'id'         => (int)$user['id'],
                'email'      => $user['email'],
                'full_name'  => $user['full_name'],
                'kyc_status' => $user['kyc_status'] ?? null
            ];

            unset($_SESSION['pin_user'], $_SESSION['pin_time']);

            /* ===============================
               🔐 LOGIN NOTIFICATION EMAIL
            ================================ */
            if (function_exists('send_mail')) {
                $ip   = client_ip();
                $time = date('d M Y, H:i');

                $subject = 'New Login Alert Federal Reserve Bank';

                $body = "
Hello {$user['full_name']},

We detected a successful login to your Federal Reserve Bank account.

LOGIN DETAILS
--------------------------------
Account Name: {$user['full_name']}
Email: {$user['email']}
IP Address: {$ip}
Date & Time: {$time}

If this was you, no action is needed.
If you do NOT recognize this activity, please contact support immediately.

Regards,
Federal Reserve Bank Security Team
";

                // Send silently (do not block login if mail fails)
                try {
                    send_mail($user['email'], $subject, $body);
                } catch (Throwable $e) {
                    // intentionally ignored for login safety
                }
            }

            redirect('/customer/dashboard.php');
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Verify PIN | Astrabank</title>
<meta name="viewport" content="width=device-width, initial-scale=1">

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

<style>
body{
  background:
    linear-gradient(rgba(6,15,30,.85), rgba(6,15,30,.85)),
    url('/assets/img/bank-login-bg.jpg') center/cover no-repeat;
}
.pin-card{width:380px;border-radius:22px}
.pin-display{
  letter-spacing:10px;font-size:26px;text-align:center;
  background:#0b1220;color:#fff;border:none;
  padding:14px;border-radius:14px
}
.keypad{
  display:grid;grid-template-columns:repeat(3,1fr);gap:14px
}
.keypad button{
  height:76px;font-size:22px;font-weight:800;border-radius:18px
}
</style>
</head>

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

<div class="card pin-card bg-dark text-white p-4 shadow-lg text-center">
  <h5 class="text-warning fw-bold mb-3">Enter PIN</h5>

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

  <input type="password" id="pinDisplay" class="form-control pin-display mb-4" readonly>

  <form method="post">
    <input type="hidden" name="pin" id="pinInput">

    <div class="keypad mb-2">
      <?php foreach ([1,2,3,4,5,6,7,8,9] as $n): ?>
        <button type="button" class="btn btn-outline-light" onclick="addPin('<?= $n ?>')"><?= $n ?></button>
      <?php endforeach; ?>

      <button type="button" class="btn btn-outline-danger" onclick="backspace()">Del</button>
      <button type="button" class="btn btn-outline-light" onclick="addPin('0')">0</button>
      <button type="submit" class="btn btn-warning">OK</button>
    </div>
  </form>
</div>

<script>
let pin='';
function addPin(n){ if(pin.length>=6)return; pin+=n; update(); }
function backspace(){ pin=pin.slice(0,-1); update(); }
function update(){
  document.getElementById('pinDisplay').value='•'.repeat(pin.length);
  document.getElementById('pinInput').value=pin;
}
</script>

</body>
</html>
