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

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

/* If already logged in, force dashboard */
if (!empty($_SESSION['user_id'])) {
  header("Location: customer/dashboard.php");
  exit;
}

$error = '';
$account = '';

if (is_post()) {

  $account  = trim($_POST['account_number'] ?? '');
  $password = $_POST['password'] ?? '';

  if (!$account || !$password) {
    $error = "Account number and password required";
  } else {

    $st = $conn->prepare("
      SELECT id, password_hash, status
      FROM users
      WHERE account_number = ?
      LIMIT 1
    ");
    $st->bind_param("s", $account);
    $st->execute();
    $user = $st->get_result()->fetch_assoc();

    if (
      !$user ||
      $user['status'] !== 'active' ||
      !password_verify($password, $user['password_hash'])
    ) {
      $error = "Invalid login credentials";
    } else {

      /* STEP 1 OK → PIN */
      $_SESSION['pin_user'] = (int)$user['id'];
      $_SESSION['pin_time'] = time();

      header("Location: pin_verify.php");
      exit;
    }
  }
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Eliteguarantytrust Inc-Login</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,.7), rgba(6,15,30,.7)),
    url('assets/img/bank-login-bg.jpg') center/cover no-repeat;
}
.login-card{
  width:380px;
  border-radius:18px;
}
</style>
</head>

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

<div class="card login-card bg-dark text-white p-4 shadow-lg">
  <h4 class="text-warning text-center fw-bold mb-3">Eliteguarantytrust Inc</h4>

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

  <form method="post">
    <div class="mb-3">
      <label>Account Number</label>
      <input type="text" name="account_number" class="form-control" required autofocus value="<?= e($account) ?>">
    </div>

    <div class="mb-3">
      <label>Password</label>
      <input type="password" name="password" class="form-control" required>
    </div>

    <button class="btn btn-warning w-100 fw-bold">Continue</button>
  </form>
</div>

</body>
</html>
