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

session_boot();
require_login();

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

/* MUST COME FROM wire_create.php */
$wireId = (int)($_SESSION['pending_wire_id'] ?? 0);
if (!$wireId) {
  redirect('transactions.php');
}

/* ===============================
   LOAD WIRE
================================ */
$st = $conn->prepare("
  SELECT wt.id, wt.amount, wt.currency, wt.txn_id
  FROM wire_transfers wt
  WHERE wt.id=? AND wt.user_id=?
  LIMIT 1
");
$st->bind_param("ii", $wireId, $u['id']);
$st->execute();
$wire = $st->get_result()->fetch_assoc();

if (!$wire) {
  redirect('transactions.php');
}

$error = '';

/* ===============================
   OTP VERIFY
================================ */
if (is_post()) {

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

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

    $ok = otp_verify($conn, (int)$u['id'], 'wire_transfer', $code);

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

      $conn->begin_transaction();

      try {

        /* Mark wire pending review */
        $st = $conn->prepare("
          UPDATE wire_transfers
          SET status='pending_review'
          WHERE id=? AND user_id=?
        ");
        $st->bind_param("ii", $wireId, $u['id']);
        $st->execute();

        /* ===== INSERT PLACEHOLDER LEDGER ENTRY (VISIBLE TO CUSTOMER) ===== */
        $acct = $conn->prepare("
          SELECT id, currency, balance
          FROM accounts
          WHERE user_id=? AND account_type IN ('savings','current')
          ORDER BY is_primary DESC
          LIMIT 1
        ");
        $acct->bind_param("i", $u['id']);
        $acct->execute();
        $acc = $acct->get_result()->fetch_assoc();

        if ($acc) {
          $le = $conn->prepare("
            INSERT INTO ledger_entries
              (txn_id, account_id, direction, amount, currency, balance_after)
            VALUES (?, ?, 'debit', 0.00, ?, ?)
          ");
          $le->bind_param(
            "iisd",
            $wire['txn_id'],
            $acc['id'],
            $acc['currency'],
            $acc['balance']
          );
          $le->execute();
        }

        unset($_SESSION['pending_wire_id']);
        $conn->commit();

        flash('msg', 'Wire submitted successfully and awaiting admin review.');
        redirect('transactions.php');

      } catch (Throwable $e) {
        $conn->rollback();
        $error = 'Verification failed. Try again.';
      }
    }
  }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Verify Wire OTP | 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;
}
.verify-card{
  width:380px;
  border-radius:18px;
}
.amount-box{
  border:1px dashed #e5e7eb;
  border-radius:14px;
  padding:14px;
  background:#0b1220;
}
</style>
</head>

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

<div class="card verify-card bg-dark text-white p-4 shadow-lg">

  <h5 class="text-warning fw-bold text-center mb-3">
    Verify Wire Transfer
  </h5>

  <div class="amount-box mb-3">
    <div class="d-flex justify-content-between">
      <span class="text-muted">Transfer Amount</span>
      <span class="fw-bold fs-5">
        USD<?= money((float)$wire['amount']) ?>
      </span>
    </div>
  </div>

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

  <form method="post" autocomplete="off">
    <div class="mb-3">
      <label class="form-label">Enter OTP 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-bold">
      Verify & Submit
    </button>
  </form>

</div>

</body>
</html>
