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

session_boot();
require_login();

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

$error = '';
$success = '';

if (is_post()) {

  $current = $_POST['current_pin'] ?? '';
  $new     = $_POST['new_pin'] ?? '';
  $confirm = $_POST['confirm_pin'] ?? '';

  if (!$current || !$new || !$confirm) {
    $error = "All fields are required";
  } elseif ($new !== $confirm) {
    $error = "New PINs do not match";
  } elseif (!ctype_digit($new) || strlen($new) < 4 || strlen($new) > 6) {
    $error = "PIN must be 4–6 digits";
  } else {

    $st = $conn->prepare("SELECT pin_hash FROM users WHERE id=?");
    $st->bind_param("i", $user['id']);
    $st->execute();
    $row = $st->get_result()->fetch_assoc();

    if (!$row || !password_verify($current, $row['pin_hash'])) {
      $error = "Current PIN is incorrect";
    } else {

      $hash = password_hash($new, PASSWORD_DEFAULT);

      $st = $conn->prepare("
        UPDATE users
        SET pin_hash=?, pin_temp=0
        WHERE id=?
      ");
      $st->bind_param("si", $hash, $user['id']);
      $st->execute();

      $success = "PIN updated successfully";
    }
  }
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Change 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">
</head>

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

<div class="card p-4 shadow-lg" style="width:380px">
  <h5 class="text-warning fw-bold text-center mb-3">Change PIN</h5>

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

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

  <form method="post">
    <div class="mb-3">
      <label>Current PIN</label>
      <input type="password" name="current_pin" class="form-control" required>
    </div>

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

    <div class="mb-3">
      <label>Confirm New PIN</label>
      <input type="password" name="confirm_pin" class="form-control" required>
    </div>

    <button class="btn btn-warning w-100 fw-bold mb-2">
      Update PIN
    </button>
  </form>

  <!-- BACK TO DASHBOARD -->
  <a href="dashboard.php" class="btn btn-outline-dark w-100">
    ← Back to Dashboard
  </a>
</div>

</body>
</html>
