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

session_boot();
require_login();

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

/* ===============================
   HELPERS (local)
================================ */
function has_available_code(mysqli $conn, int $userId, string $type): bool {
  $st = $conn->prepare("
    SELECT COUNT(*) c
    FROM wire_codes
    WHERE user_id=? AND type=? AND used=0 AND enabled=1
  ");
  $st->bind_param("is", $userId, $type);
  $st->execute();
  $row = $st->get_result()->fetch_assoc();
  return (int)($row['c'] ?? 0) > 0;
}

function mark_codes_used(mysqli $conn, int $userId, array $codes): void {
  $codes = array_values(array_filter(array_map('trim', $codes), fn($v) => $v !== ''));
  $codes = array_values(array_unique($codes));
  if (!$codes) return;

  $placeholders = implode(',', array_fill(0, count($codes), '?'));
  $sql = "UPDATE wire_codes SET used=1, used_at=NOW() WHERE user_id=? AND code IN ($placeholders)";
  $st = $conn->prepare($sql);

  $types = 'i' . str_repeat('s', count($codes));
  $params = array_merge([$userId], $codes);

  $bind_names = [];
  $bind_names[] = $types;
  for ($i=0; $i<count($params); $i++) $bind_names[] = &$params[$i];

  call_user_func_array([$st, 'bind_param'], $bind_names);
  $st->execute();
}

/* ===============================
   LOAD ACCOUNTS (FIXED)
   include new ENUM types so wire works
================================ */
$accounts = [];
$st = $conn->prepare("
  SELECT *
  FROM accounts
  WHERE user_id=?
    AND account_type IN (
      'savings','current','checking','online_banking',
      'non_resident','domiciliary','joint'
    )
  ORDER BY is_primary DESC, id ASC
");
$uid = (int)($u['id'] ?? 0);
$st->bind_param("i", $uid);
$st->execute();
$rs = $st->get_result();
while ($r = $rs->fetch_assoc()) $accounts[] = $r;

if (!$accounts) die('No account');

/* Use first/primary account currency for wire */
$accountCurrency = $accounts[0]['currency'] ?? 'USD';

/* ===============================
   SETTINGS
================================ */
$fee = 2.00;
$dailyLimit = 5000.00;

$s = $conn->query("SELECT * FROM settings WHERE id=1 LIMIT 1");
if ($s && $row = $s->fetch_assoc()) {
  $fee = (float)($row['wire_fee'] ?? $fee);
  $dailyLimit = (float)($row['wire_daily_limit'] ?? $dailyLimit);
}

/* ===============================
   BENEFICIARIES
================================ */
$beneficiaries = [];
$st = $conn->prepare("SELECT * FROM beneficiaries WHERE user_id=? ORDER BY id DESC");
$st->bind_param("i", $uid);
$st->execute();
$rs = $st->get_result();
while ($r = $rs->fetch_assoc()) $beneficiaries[] = $r;

/* ===============================
   CODE VISIBILITY (AUTO)
================================ */
$codeVisible = [
  'vat' => has_available_code($conn, $uid, 'vat'),
  'tax' => has_available_code($conn, $uid, 'tax'),
  'imf' => has_available_code($conn, $uid, 'imf'),
];

/* ===============================
   WIZARD STATE
================================ */
$step = (int)($_POST['step'] ?? ($_GET['step'] ?? 1));
if ($step < 1 || $step > 3) $step = 1;

/* Reset draft if requested */
if (isset($_GET['reset']) && $_GET['reset'] === '1') {
  unset($_SESSION['wire_draft']);
  redirect('wire_create.php');
}

/* Ensure draft container */
if (!isset($_SESSION['wire_draft']) || !is_array($_SESSION['wire_draft'])) {
  $_SESSION['wire_draft'] = [];
}

/* ===============================
   POST HANDLING (STEPS)
================================ */
if (is_post()) {
  csrf_verify();

  try {

    /* ---------------------------
       STEP 1
    ---------------------------- */
    if ($step === 1) {
      $amount = (float)($_POST['amount'] ?? 0);
      $reason = trim($_POST['reason'] ?? '');
      $beneficiary_id = (int)($_POST['beneficiary_id'] ?? 0);

      $bank_name = trim($_POST['bank_name'] ?? '');
      $ben_name = trim($_POST['ben_name'] ?? '');
      $account_number = trim($_POST['account_number'] ?? '');
      $save_ben = isset($_POST['save_ben']);

      $swift_code = trim($_POST['swift_code'] ?? '');
      $destination_country = trim($_POST['destination_country'] ?? '');

      if ($amount <= 0) throw new Exception('Enter a valid amount');

      if (!$beneficiary_id) {
        if (!$bank_name || !$ben_name || !$account_number) {
          throw new Exception('Provide beneficiary details or choose from saved beneficiaries');
        }
      }

      if (!$swift_code) throw new Exception('SWIFT / BIC is required');
      if (!$destination_country) throw new Exception('Destination country is required');

      $_SESSION['wire_draft'] = [
        'amount' => $amount,
        'reason' => $reason,
        'beneficiary_id' => $beneficiary_id,
        'bank_name' => $bank_name,
        'ben_name' => $ben_name,
        'account_number' => $account_number,
        'save_ben' => $save_ben ? 1 : 0,
        'swift_code' => $swift_code,
        'destination_country' => $destination_country,
      ];

      redirect('wire_create.php?step=2');
    }

    /* ---------------------------
       STEP 2
    ---------------------------- */
    if ($step === 2) {

      $codeVisible = [
        'vat' => has_available_code($conn, $uid, 'vat'),
        'tax' => has_available_code($conn, $uid, 'tax'),
        'imf' => has_available_code($conn, $uid, 'imf'),
      ];

      $vat = trim($_POST['vat_code'] ?? '');
      $tax = trim($_POST['tax_code'] ?? '');
      $imf = trim($_POST['imf_code'] ?? '');

      if ($codeVisible['vat'] && $vat === '') throw new Exception('VAT code is required');
      if ($codeVisible['tax'] && $tax === '') throw new Exception('Tax code is required');
      if ($codeVisible['imf'] && $imf === '') throw new Exception('IMF code is required');

      $check = $conn->prepare("
        SELECT COUNT(*) AS c
        FROM wire_codes
        WHERE user_id = ?
          AND code = ?
          AND type = ?
          AND used = 0
          AND enabled = 1
      ");

      if ($codeVisible['vat']) {
        $type = 'vat';
        $check->bind_param("iss", $uid, $vat, $type);
        $check->execute();
        $res = $check->get_result()->fetch_assoc();
        if ((int)($res['c'] ?? 0) === 0) throw new Exception('Invalid or disabled VAT code');
        $_SESSION['wire_draft']['vat_code'] = $vat;
      } else unset($_SESSION['wire_draft']['vat_code']);

      if ($codeVisible['tax']) {
        $type = 'tax';
        $check->bind_param("iss", $uid, $tax, $type);
        $check->execute();
        $res = $check->get_result()->fetch_assoc();
        if ((int)($res['c'] ?? 0) === 0) throw new Exception('Invalid or disabled Tax code');
        $_SESSION['wire_draft']['tax_code'] = $tax;
      } else unset($_SESSION['wire_draft']['tax_code']);

      if ($codeVisible['imf']) {
        $type = 'imf';
        $check->bind_param("iss", $uid, $imf, $type);
        $check->execute();
        $res = $check->get_result()->fetch_assoc();
        if ((int)($res['c'] ?? 0) === 0) throw new Exception('Invalid or disabled IMF code');
        $_SESSION['wire_draft']['imf_code'] = $imf;
      } else unset($_SESSION['wire_draft']['imf_code']);

      redirect('wire_create.php?step=3');
    }

    /* ---------------------------
       STEP 3: FINALIZE
    ---------------------------- */
    if ($step === 3) {

      $d = $_SESSION['wire_draft'];

      $amount = (float)($d['amount'] ?? 0);
      $reason = trim($d['reason'] ?? '');
      $beneficiary_id = (int)($d['beneficiary_id'] ?? 0);

      $bank_name = trim($d['bank_name'] ?? '');
      $ben_name = trim($d['ben_name'] ?? '');
      $account_number = trim($d['account_number'] ?? '');
      $save_ben = (int)($d['save_ben'] ?? 0) === 1;

      $swift_code = trim($d['swift_code'] ?? '');
      $destination_country = trim($d['destination_country'] ?? '');

      $codeVisible = [
        'vat' => has_available_code($conn, $uid, 'vat'),
        'tax' => has_available_code($conn, $uid, 'tax'),
        'imf' => has_available_code($conn, $uid, 'imf'),
      ];

      $vat = trim($d['vat_code'] ?? '');
      $tax = trim($d['tax_code'] ?? '');
      $imf = trim($d['imf_code'] ?? '');

      if ($amount <= 0) throw new Exception('Draft amount missing. Restart wire.');
      if (!$swift_code || !$destination_country) throw new Exception('SWIFT/Country missing. Go back.');

      if ($codeVisible['vat'] && strlen($vat) < 3) throw new Exception('VAT code missing. Go back.');
      if ($codeVisible['tax'] && strlen($tax) < 3) throw new Exception('Tax code missing. Go back.');
      if ($codeVisible['imf'] && strlen($imf) < 3) throw new Exception('IMF code missing. Go back.');

      $st = $conn->prepare("
        SELECT COALESCE(SUM(amount),0) AS total
        FROM wire_transfers
        WHERE user_id=?
          AND DATE(created_at)=CURDATE()
          AND status IN ('pending_review','approved','processed','draft')
      ");
      $st->bind_param("i", $uid);
      $st->execute();
      $todayTotal = (float)($st->get_result()->fetch_assoc()['total'] ?? 0);

      if (($todayTotal + $amount) > $dailyLimit) throw new Exception('Daily wire limit exceeded');

      $conn->begin_transaction();

      /* If beneficiary selected, verify exists + load details */
      if ($beneficiary_id > 0) {
        $bx = $conn->prepare("SELECT id, name, bank_name, account_number FROM beneficiaries WHERE id=? AND user_id=? LIMIT 1");
        $bx->bind_param("ii", $beneficiary_id, $uid);
        $bx->execute();
        $brow = $bx->get_result()->fetch_assoc();

        if (!$brow) {
          throw new Exception('Selected beneficiary not found. Please reselect.');
        }

        $ben_name = $ben_name ?: (string)$brow['name'];
        $bank_name = $bank_name ?: (string)$brow['bank_name'];
        $account_number = $account_number ?: (string)$brow['account_number'];
      } else {
        if (!$bank_name || !$ben_name || !$account_number) throw new Exception('Beneficiary details missing');

        if ($save_ben) {
          $ins = $conn->prepare("INSERT INTO beneficiaries (user_id, name, bank_name, account_number, verified) VALUES (?,?,?,?,1)");
          $ins->bind_param("isss", $uid, $ben_name, $bank_name, $account_number);
          $ins->execute();
          $beneficiary_id = (int)$conn->insert_id;
        }
      }

      $ref = now_ref('WIRE');

      /* ledger_txn */
      $txnType = 'wire';
      $txnStatus = 'pending';
      $narr = $reason ?: 'Wire transfer';
      $createdBy = $uid;

      $st = $conn->prepare("INSERT INTO ledger_txn (ref, type, status, narration, created_by) VALUES (?,?,?,?,?)");
      $st->bind_param("ssssi", $ref, $txnType, $txnStatus, $narr, $createdBy);
      $st->execute();
      $txnId = (int)$conn->insert_id;

      /* wire_transfers currency: use account currency (NOT hardcoded GHS) */
      $currency = $accountCurrency;
      $wStatus = 'draft';

      $vat_db = $codeVisible['vat'] ? $vat : null;
      $tax_db = $codeVisible['tax'] ? $tax : null;
      $imf_db = $codeVisible['imf'] ? $imf : null;

      if ($beneficiary_id > 0) {

        $st = $conn->prepare("
          INSERT INTO wire_transfers
            (txn_id, user_id, beneficiary_id, amount, fee, currency, status, reason,
             ben_name, bank_name, account_number,
             vat_code, tax_code, imf_code,
             swift_code, destination_country)
          VALUES
            (?, ?, ?, ?, ?, ?, ?, ?,
             ?, ?, ?, ?, ?, ?, ?, ?)
        ");

        $st->bind_param(
          "iiiddsssssssssss",
          $txnId,
          $uid,
          $beneficiary_id,
          $amount,
          $fee,
          $currency,
          $wStatus,
          $narr,
          $ben_name,
          $bank_name,
          $account_number,
          $vat_db,
          $tax_db,
          $imf_db,
          $swift_code,
          $destination_country
        );

      } else {

        $st = $conn->prepare("
          INSERT INTO wire_transfers
            (txn_id, user_id, beneficiary_id, amount, fee, currency, status, reason,
             ben_name, bank_name, account_number,
             vat_code, tax_code, imf_code,
             swift_code, destination_country)
          VALUES
            (?, ?, NULL, ?, ?, ?, ?, ?,
             ?, ?, ?, ?, ?, ?, ?, ?)
        ");

        $st->bind_param(
          "iiddsssssssssss",
          $txnId,
          $uid,
          $amount,
          $fee,
          $currency,
          $wStatus,
          $narr,
          $ben_name,
          $bank_name,
          $account_number,
          $vat_db,
          $tax_db,
          $imf_db,
          $swift_code,
          $destination_country
        );
      }

      $st->execute();
      $wireId = (int)$conn->insert_id;

      /* Mark codes used */
      $toMark = [];
      if ($codeVisible['vat'] && $vat) $toMark[] = $vat;
      if ($codeVisible['tax'] && $tax) $toMark[] = $tax;
      if ($codeVisible['imf'] && $imf) $toMark[] = $imf;
      mark_codes_used($conn, $uid, $toMark);

      /* OTP */
      if (!otp_create($conn, $uid, 'wire_transfer', $u['email'], 5)) {
        throw new Exception('Unable to send OTP. Configure mail() / SMTP');
      }

      /* Audit log */
      $meta = json_encode([
        'wire_id' => $wireId,
        'ref' => $ref,
        'amount' => $amount,
        'fee' => $fee,
        'vat' => $vat_db,
        'tax' => $tax_db,
        'imf' => $imf_db
      ], JSON_UNESCAPED_SLASHES);

      $ip = client_ip();
      $action = 'WIRE_CREATE';

      $st = $conn->prepare("INSERT INTO audit_logs (actor_id, action, meta, ip) VALUES (?,?,?,?)");
      $st->bind_param("isss", $uid, $action, $meta, $ip);
      $st->execute();

      $conn->commit();

      unset($_SESSION['wire_draft']);
      $_SESSION['pending_wire_id'] = $wireId;

      flash('msg', 'OTP sent to your email. Verify to submit for review.');
      redirect('wire_verify.php');
    }

  } catch (Throwable $e) {
    try { $conn->rollback(); } catch(Throwable $x) {}
    flash('err', $e->getMessage());
  }
}

/* Draft values for UI */
$d = $_SESSION['wire_draft'] ?? [];

$title = 'Wire Transfer';
include __DIR__ . '/../../views/partials/head.php';
include __DIR__ . '/../../views/partials/customer_sidebar.php';
?>

<style>
.wizard-steps{display:flex;gap:10px;flex-wrap:wrap}
.wizard-step{padding:10px 12px;border-radius:999px;border:1px solid #e5e7eb;background:#fff;font-weight:700}
.wizard-step.active{background:var(--ab-accent);color:#fff;border-color:var(--ab-accent)}
.wizard-card{border-radius:16px}
.summary-box{border:1px dashed #e5e7eb;border-radius:14px;padding:14px}
.kv{display:flex;justify-content:space-between;gap:10px}
.kv span{color:#6b7280}
</style>

<main style="margin-left:240px; min-height:100vh">
<div class="container-fluid py-4">

  <div class="d-flex align-items-center justify-content-between mb-3">
    <h3 class="fw-bold m-0">Wire Transfer</h3>
    <div class="d-flex gap-2">
      <a class="btn btn-sm btn-outline-secondary" href="dashboard.php"><i class="bi bi-arrow-left"></i> Back</a>
      <a class="btn btn-sm btn-outline-danger" href="wire_create.php?reset=1"><i class="bi bi-arrow-counterclockwise"></i> Reset</a>
    </div>
  </div>

  <?php if ($m=flash('msg')): ?><div class="alert alert-success"><?= e($m) ?></div><?php endif; ?>
  <?php if ($m=flash('err')): ?><div class="alert alert-danger"><?= e($m) ?></div><?php endif; ?>

  <div class="wizard-steps mb-3">
    <div class="wizard-step <?= $step===1?'active':'' ?>">1. Beneficiary</div>
    <div class="wizard-step <?= $step===2?'active':'' ?>">2. Codes</div>
    <div class="wizard-step <?= $step===3?'active':'' ?>">3. Confirm</div>
  </div>

  <div class="row g-4">
    <div class="col-lg-7">

      <div class="card ab-card wizard-card p-4">
        <div class="ab-muted mb-3">
          Fee: <b><?= e($accountCurrency) ?> <?= money($fee) ?></b> • Daily limit: <b><?= e($accountCurrency) ?> <?= money($dailyLimit) ?></b>
        </div>

        <?php if ($step === 1): ?>
          <form method="post">
            <?= csrf_field() ?>
            <input type="hidden" name="step" value="1">

            <label class="form-label fw-semibold">Choose beneficiary (optional)</label>
            <select name="beneficiary_id" class="form-select mb-3" id="beneficiarySelect">
              <option value="0">-- Enter new beneficiary below --</option>
              <?php foreach($beneficiaries as $b): ?>
                <option value="<?= (int)$b['id'] ?>">
                  <?= e($b['name']) ?> • <?= e($b['bank_name']) ?> • <?= e($b['account_number']) ?>
                </option>
              <?php endforeach; ?>
            </select>

            <div class="row g-2">
              <div class="col-md-6">
                <label class="form-label">Beneficiary name</label>
                <input name="ben_name" class="form-control" placeholder="e.g., Kofi Mensah" value="<?= e($d['ben_name'] ?? '') ?>">
              </div>
              <div class="col-md-6">
                <label class="form-label">Bank name</label>
                <input name="bank_name" class="form-control" placeholder="e.g., GCB" value="<?= e($d['bank_name'] ?? '') ?>">
              </div>

              <div class="col-md-6">
                <label class="form-label">SWIFT / BIC</label>
                <input name="swift_code" class="form-control" required value="<?= e($d['swift_code'] ?? '') ?>">
              </div>

              <div class="col-md-6">
                <label class="form-label">Destination Country</label>
                <input name="destination_country" class="form-control" required value="<?= e($d['destination_country'] ?? '') ?>">
              </div>

              <div class="col-12">
                <label class="form-label">Account number</label>
                <input name="account_number" class="form-control" placeholder="Account number" value="<?= e($d['account_number'] ?? '') ?>">
              </div>
            </div>

            <div class="form-check mt-2">
              <input class="form-check-input" type="checkbox" name="save_ben" id="save_ben" <?= !empty($d['save_ben'])?'checked':'' ?>>
              <label class="form-check-label" for="save_ben">Save beneficiary</label>
            </div>

            <hr class="my-3">

            <div class="row g-2">
              <div class="col-md-6">
                <label class="form-label fw-semibold">Amount (<?= e($accountCurrency) ?>)</label>
                <input name="amount" type="number" step="0.01" class="form-control" required value="<?= e((string)($d['amount'] ?? '')) ?>">
              </div>
              <div class="col-md-6">
                <label class="form-label fw-semibold">Reason</label>
                <input name="reason" class="form-control" placeholder="Narration" value="<?= e($d['reason'] ?? '') ?>">
              </div>
            </div>

            <button class="btn ab-btn text-white mt-3 w-100">
              Continue
              <i class="bi bi-arrow-right ms-2"></i>
            </button>
          </form>
        <?php endif; ?>

        <?php if ($step === 2): ?>
          <form method="post">
            <?= csrf_field() ?>
            <input type="hidden" name="step" value="2">

            <div class="summary-box mb-3">
              <div class="fw-bold mb-2">Draft summary</div>
              <div class="kv"><span>Amount</span><b><?= e($accountCurrency) ?> <?= money((float)($d['amount'] ?? 0)) ?></b></div>
              <div class="kv"><span>Fee</span><b><?= e($accountCurrency) ?> <?= money($fee) ?></b></div>
              <div class="kv"><span>Reason</span><b><?= e($d['reason'] ?? '-') ?></b></div>
            </div>

            <?php if (!$codeVisible['vat'] && !$codeVisible['tax'] && !$codeVisible['imf']): ?>
              <div class="alert alert-warning">
                No enabled wire codes have been issued to your account yet. Contact support.
              </div>
            <?php endif; ?>

            <div id="vatWrap" class="<?= $codeVisible['vat'] ? '' : 'd-none' ?>">
              <label class="form-label fw-semibold">VAT Code</label>
              <input name="vat_code" class="form-control mb-3" placeholder="Enter VAT code"
                     <?= $codeVisible['vat'] ? 'required' : '' ?>
                     value="<?= e($d['vat_code'] ?? '') ?>">
            </div>

            <div id="taxWrap" class="<?= $codeVisible['tax'] ? '' : 'd-none' ?>">
              <label class="form-label fw-semibold">Tax Code</label>
              <input name="tax_code" class="form-control mb-3" placeholder="Enter Tax code"
                     <?= $codeVisible['tax'] ? 'required' : '' ?>
                     value="<?= e($d['tax_code'] ?? '') ?>">
            </div>

            <div id="imfWrap" class="<?= $codeVisible['imf'] ? '' : 'd-none' ?>">
              <label class="form-label fw-semibold">IMF Code</label>
              <input name="imf_code" class="form-control mb-3" placeholder="Enter IMF code"
                     <?= $codeVisible['imf'] ? 'required' : '' ?>
                     value="<?= e($d['imf_code'] ?? '') ?>">
            </div>

            <div class="d-flex gap-2">
              <a class="btn btn-outline-secondary w-50" href="wire_create.php?step=1">
                <i class="bi bi-arrow-left me-1"></i> Back
              </a>
              <button class="btn ab-btn text-white w-50" <?= (!$codeVisible['vat'] && !$codeVisible['tax'] && !$codeVisible['imf']) ? 'disabled' : '' ?>>
                Continue
                <i class="bi bi-arrow-right ms-2"></i>
              </button>
            </div>
          </form>
        <?php endif; ?>

        <?php if ($step === 3): ?>
          <form method="post">
            <?= csrf_field() ?>
            <input type="hidden" name="step" value="3">

            <div class="fw-bold mb-2">Confirm wire</div>
            <div class="summary-box">
              <div class="kv"><span>Amount</span><b><?= e($accountCurrency) ?> <?= money((float)($d['amount'] ?? 0)) ?></b></div>
              <div class="kv"><span>Fee</span><b><?= e($accountCurrency) ?> <?= money($fee) ?></b></div>
              <div class="kv"><span>Total</span><b><?= e($accountCurrency) ?> <?= money(((float)($d['amount'] ?? 0)) + $fee) ?></b></div>

              <hr>

              <?php if (!empty($d['vat_code'])): ?>
                <div class="kv"><span>VAT Code</span><b><?= e($d['vat_code']) ?></b></div>
              <?php endif; ?>
              <?php if (!empty($d['tax_code'])): ?>
                <div class="kv"><span>Tax Code</span><b><?= e($d['tax_code']) ?></b></div>
              <?php endif; ?>
              <?php if (!empty($d['imf_code'])): ?>
                <div class="kv"><span>IMF Code</span><b><?= e($d['imf_code']) ?></b></div>
              <?php endif; ?>

              <hr>

              <div class="kv"><span>SWIFT</span><b><?= e($d['swift_code'] ?? '-') ?></b></div>
              <div class="kv"><span>Country</span><b><?= e($d['destination_country'] ?? '-') ?></b></div>

              <hr>

              <div class="kv"><span>Beneficiary</span><b><?= e(($d['ben_name'] ?? '') ?: 'Saved beneficiary') ?></b></div>
              <div class="kv"><span>Bank</span><b><?= e($d['bank_name'] ?? '-') ?></b></div>
              <div class="kv"><span>Account</span><b><?= e($d['account_number'] ?? '-') ?></b></div>
              <div class="kv"><span>Reason</span><b><?= e($d['reason'] ?? '-') ?></b></div>
            </div>

            <div class="alert alert-warning mt-3 mb-0">
              After you continue, we’ll send an <b>OTP</b> to your email for verification.
            </div>

            <div class="d-flex gap-2 mt-3">
              <a class="btn btn-outline-secondary w-50" href="wire_create.php?step=2">
                <i class="bi bi-arrow-left me-1"></i> Back
              </a>
              <button class="btn ab-btn text-white w-50">
                <i class="bi bi-shield-check me-2"></i> Finalize & Send OTP
              </button>
            </div>
          </form>
        <?php endif; ?>

      </div>
    </div>

    <div class="col-lg-5">
      <div class="card ab-card p-4">
        <div class="fw-bold mb-2">How it works</div>
        <ol class="ab-muted mb-0">
          <li>Enter beneficiary + amount</li>
          <li>Enter required codes</li>
          <li>Confirm and verify with Email OTP</li>
          <li>Admin reviews/approves</li>
          <li>Ledger posts & you get notification</li>
        </ol>
      </div>

      <div class="card ab-card p-4 mt-3">
        <div class="fw-bold mb-2">Security checks</div>
        <div class="ab-muted">
          Disabled codes won’t be accepted, and code fields automatically hide when none are available.
        </div>
      </div>
    </div>
  </div>
</div>

<script>
(function(){
  const sel = document.getElementById('beneficiarySelect');
  if (!sel) return;

  const toggleManual = () => {
    const manualFields = ['ben_name','bank_name','account_number','swift_code','destination_country']
      .map(n => document.querySelector(`[name="${n}"]`));
    const chosen = parseInt(sel.value || '0', 10) > 0;
    manualFields.forEach(el => { if (!el) return; el.disabled = chosen; if (chosen) el.value = ''; });
    const save = document.getElementById('save_ben');
    if (save) { save.checked = false; save.disabled = chosen; }
  };

  sel.addEventListener('change', toggleManual);
  toggleManual();
})();
</script>

<?php include __DIR__ . '/../../views/partials/foot.php'; ?>
