<?php
require_once 'includes/config.php';
require_once 'includes/functions.php';
require_once 'includes/auth.php';
requireUserLogin();
$currentUser = currentUser($pdo);
$uid = (int)$_SESSION['user_id'];

$error = ''; $success = '';
$step = $_SESSION['transfer_step'] ?? 1;

// KYC Gate
if ($currentUser['require_kyc_for_transfer'] && $currentUser['kyc_status'] !== 'verified') {
    $error = 'KYC verification required before making transfers. <a href="/kyc.php">Complete KYC</a>';
    $step = 0;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && $step != 0) {
    if (!verify_csrf()) { $error = 'Invalid CSRF token.'; goto done; }
    $action = $_POST['action'] ?? '';

    // ── Step 1: Initiate transfer ─────────────────────────────
    if ($action === 'initiate') {
        $amount = (float)str_replace(',', '', $_POST['amount'] ?? 0);
        $benName    = trim($_POST['ben_name'] ?? '');
        $benAccount = trim($_POST['ben_account'] ?? '');
        $benBank    = trim($_POST['ben_bank'] ?? '');
        $benSwift   = trim($_POST['ben_swift'] ?? '');
        $benIban    = trim($_POST['ben_iban'] ?? '');
        $benRouting = trim($_POST['ben_routing'] ?? '');
        $benCountry = trim($_POST['ben_country'] ?? '');
        $txType     = $_POST['transfer_type'] ?? 'local';
        $desc       = trim($_POST['description'] ?? 'Bank Transfer');

        if ($amount <= 0)   { $error = 'Enter a valid amount.'; goto done; }
        if (!$benName)      { $error = 'Beneficiary name is required.'; goto done; }
        if (!$benAccount)   { $error = 'Beneficiary account/IBAN is required.'; goto done; }
        if ((float)$currentUser['available_balance'] < $amount) { $error = 'Insufficient funds.'; goto done; }

        // Fee calc
        $fee = 0;
        if ($currentUser['transfer_fee_enabled']) {
            $feeVal = (float)$currentUser['transfer_fee_value'];
            $fee = $currentUser['transfer_fee_type'] === 'percentage' ? round($amount * $feeVal / 100, 2) : $feeVal;
        }

        $_SESSION['transfer_data'] = compact('amount','fee','benName','benAccount','benBank','benSwift','benIban','benRouting','benCountry','txType','desc');
        $_SESSION['transfer_step'] = 2;
        $_SESSION['transfer_gates_done'] = [];
        header('Location: /transfer.php'); exit;
    }

    // ── Gate verification steps ───────────────────────────────
    if ($action === 'verify_otp') {
        $uid = (int)$_SESSION['user_id'];
        $code = trim($_POST['otp_code'] ?? '');
        if (verifyOTP($pdo, $uid, $code, 'transfer')) {
            $_SESSION['transfer_gates_done'][] = 'otp';
        } else { $error = 'Invalid or expired OTP code.'; goto done; }
    }
    if ($action === 'verify_imf') {
        $entered = trim($_POST['imf_code'] ?? '');
        if ($entered === $currentUser['imf_code']) {
            $_SESSION['transfer_gates_done'][] = 'imf';
        } else { $error = 'Incorrect IMF code.'; goto done; }
    }
    if ($action === 'verify_cot') {
        $entered = trim($_POST['cot_code'] ?? '');
        if ($entered === $currentUser['cot_code']) {
            $_SESSION['transfer_gates_done'][] = 'cot';
        } else { $error = 'Incorrect COT code.'; goto done; }
    }
    if ($action === 'verify_atc') {
        $entered = trim($_POST['atc_code'] ?? '');
        if ($entered === $currentUser['anti_terrorist_code']) {
            $_SESSION['transfer_gates_done'][] = 'atc';
        } else { $error = 'Incorrect Anti-Terrorist Clearance code.'; goto done; }
    }
    if ($action === 'verify_txc') {
        $entered = trim($_POST['txc_code'] ?? '');
        if ($entered === $currentUser['tax_clearance_code']) {
            $_SESSION['transfer_gates_done'][] = 'txc';
        } else { $error = 'Incorrect Tax Clearance code.'; goto done; }
    }

    // Determine required gates
    $reqGates = [];
    if ($currentUser['enable_otp'])             $reqGates[] = 'otp';
    if ($currentUser['enable_imf'])             $reqGates[] = 'imf';
    if ($currentUser['enable_cot'])             $reqGates[] = 'cot';
    if ($currentUser['enable_anti_terrorist'])  $reqGates[] = 'atc';
    if ($currentUser['enable_tax_clearance'])   $reqGates[] = 'txc';
    $doneGates = $_SESSION['transfer_gates_done'] ?? [];

    // If OTP just entered or no gates required, check PIN and complete
    if ($action === 'complete') {
        $pin = $_POST['transaction_pin'] ?? '';
        if (!password_verify($pin, $currentUser['pin'])) {
            // Legacy 4-digit plain
            if ($pin !== $currentUser['pin']) {
                $error = 'Incorrect transaction PIN.'; goto done;
            }
        }

        // Verify all required gates passed
        $missing = array_diff($reqGates, $doneGates);
        if (!empty($missing)) { $error = 'Please complete all security verifications.'; goto done; }

        $td  = $_SESSION['transfer_data'];
        $ref = generateRef('FLE');
        $total = $td['amount'] + $td['fee'];

        if ($currentUser['available_balance'] < $total) { $error = 'Insufficient funds.'; goto done; }

        // Debit
        $ok = debitAccount($pdo, $uid, $total, $td['desc'], $ref, [
            'fee'           => $td['fee'],
            'ben_name'      => $td['benName'],
            'ben_account'   => $td['benAccount'],
            'ben_bank'      => $td['benBank'],
            'ben_swift'     => $td['benSwift'],
            'transfer_type' => $td['txType'],
        ]);

        if ($ok) {
            addNotification($pdo, $uid, 'Transfer Successful', "Your transfer of " . money($td['amount'],$currentUser['currency']) . " to {$td['benName']} was successful. Ref: $ref", 'transaction');
            logActivity($pdo, $uid, null, 'transfer', "Transfer $ref to {$td['benName']}");
            unset($_SESSION['transfer_data'], $_SESSION['transfer_step'], $_SESSION['transfer_gates_done']);
            $success = "Transfer of " . money($td['amount'],$currentUser['currency']) . " to {$td['benName']} completed! Reference: <strong>$ref</strong>";
            $step = 'done';
        } else {
            $error = 'Transfer failed. Please try again.';
        }
        goto done;
    }

    // If a gate was just done, determine the next required one
    if (in_array($action, ['verify_otp','verify_imf','verify_cot','verify_atc','verify_txc'])) {
        $_SESSION['transfer_step'] = 2;
        header('Location: /transfer.php'); exit;
    }
}

// Send OTP when step 2 starts
if (($step == 2) && $currentUser['enable_otp'] && !in_array('otp', $_SESSION['transfer_gates_done'] ?? [])) {
    if (!isset($_SESSION['otp_sent_for_transfer'])) {
        $otp = createOTP($pdo, $uid, 'transfer');
        sendOTPEmail($currentUser['email'], $currentUser['first_name'], $otp, 'transfer');
        $_SESSION['otp_sent_for_transfer'] = true;
    }
}

done:
// Determine current gate needed
$reqGates = [];
if ($currentUser['enable_otp'])             $reqGates[] = 'otp';
if ($currentUser['enable_imf'])             $reqGates[] = 'imf';
if ($currentUser['enable_cot'])             $reqGates[] = 'cot';
if ($currentUser['enable_anti_terrorist'])  $reqGates[] = 'atc';
if ($currentUser['enable_tax_clearance'])   $reqGates[] = 'txc';
$doneGates = $_SESSION['transfer_gates_done'] ?? [];
$nextGate = null;
foreach ($reqGates as $g) { if (!in_array($g, $doneGates)) { $nextGate = $g; break; } }

$banks = $pdo->query("SELECT * FROM banks WHERE status=1 ORDER BY country,bank_name")->fetchAll();
$beneficiaries = $pdo->prepare("SELECT * FROM beneficiaries WHERE user_id=? ORDER BY is_favourite DESC, created_at DESC");
$beneficiaries->execute([$uid]); $savedBens = $beneficiaries->fetchAll();

$pageTitle = 'Fund Transfer';
?>
<!DOCTYPE html><html lang="en"><head>
<meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title><?= $pageTitle ?> | <?= SITE_NAME ?></title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
<link rel="stylesheet" href="/assets/css/style.css">
</head><body>
<?php include 'includes/header.php'; ?>
<div class="page-wrapper"><div class="container" style="max-width:760px;">
<div class="page-title"><i class="fa fa-paper-plane me-2 text-danger"></i>Fund Transfer</div>

<?php if ($error): ?><div class="alert alert-danger"><i class="fa fa-exclamation-circle me-1"></i><?= $error ?></div><?php endif; ?>

<?php if ($step === 'done'): ?>
<!-- Success -->
<div class="card text-center p-5">
  <div style="font-size:4rem;color:#1abc9c;margin-bottom:1rem;">✓</div>
  <h4 class="fw-bold text-success">Transfer Successful!</h4>
  <p><?= $success ?></p>
  <div class="d-flex gap-2 justify-content-center mt-3">
    <a href="/transfer.php" class="btn btn-primary">New Transfer</a>
    <a href="/transactions.php" class="btn btn-outline-secondary">View Transactions</a>
  </div>
</div>

<?php elseif ($step == 1 || $step == 0): ?>
<!-- Step 1: Transfer Form -->
<div class="row g-4">
  <div class="col-md-8">
    <div class="card">
      <div class="card-header">Transfer Details</div>
      <div class="card-body">
        <?php if (!empty($savedBens)): ?>
        <div class="mb-3">
          <label class="form-label">Saved Beneficiaries</label>
          <select class="form-select" id="savedBenSelect" onchange="fillBeneficiary(this)">
            <option value="">-- Select saved beneficiary --</option>
            <?php foreach ($savedBens as $b): ?>
            <option value='<?= htmlspecialchars(json_encode($b)) ?>'><?= sanitize($b['nickname'] ?: $b['beneficiary_name']) ?> – <?= maskAccount($b['account_number']) ?></option>
            <?php endforeach; ?>
          </select>
        </div><hr>
        <?php endif; ?>
        <form method="POST">
          <?= csrf_field() ?><input type="hidden" name="action" value="initiate">
          <div class="row g-3">
            <div class="col-12">
              <label class="form-label">Beneficiary Name *</label>
              <input type="text" name="ben_name" id="ben_name" class="form-control" required>
            </div>
            <div class="col-12">
              <label class="form-label">Account Number *</label>
              <input type="text" name="ben_account" id="ben_account" class="form-control" required>
            </div>
            <div class="col-md-6">
              <label class="form-label">Transfer Type</label>
              <select name="transfer_type" id="transfer_type" class="form-select">
                <option value="local">Local Transfer</option>
                <option value="international">International Transfer</option>
                <option value="internal">Internal Transfer</option>
              </select>
            </div>
            <div class="col-md-6">
              <label class="form-label">Amount (<?= sanitize($currentUser['currency']) ?>) *</label>
              <div class="input-group"><span class="input-group-text">$</span>
              <input type="number" name="amount" class="form-control amount-input" step="0.01" min="0.01" required></div>
            </div>
            <div id="intl_fields">
              <div class="row g-3">
                <div class="col-md-6">
                  <label class="form-label">Bank Name</label>
                  <input type="text" name="ben_bank" id="ben_bank" class="form-control" list="bankList">
                  <datalist id="bankList"><?php foreach($banks as $bk): ?><option value="<?= sanitize($bk['bank_name']) ?>"><?php endforeach; ?></datalist>
                </div>
                <div class="col-md-6">
                  <label class="form-label">SWIFT Code</label>
                  <input type="text" name="ben_swift" id="ben_swift" class="form-control" placeholder="e.g. BOFAUS3N">
                </div>
                <div class="col-md-6">
                  <label class="form-label">IBAN</label>
                  <input type="text" name="ben_iban" class="form-control" placeholder="e.g. GB29NWBK60161331926819">
                </div>
                <div class="col-md-6">
                  <label class="form-label">Routing Number</label>
                  <input type="text" name="ben_routing" class="form-control">
                </div>
                <div class="col-12">
                  <label class="form-label">Beneficiary Country</label>
                  <input type="text" name="ben_country" class="form-control">
                </div>
              </div>
            </div>
            <div class="col-12">
              <label class="form-label">Description</label>
              <input type="text" name="description" class="form-control" value="Bank Transfer" maxlength="200">
            </div>
          </div>
          <button class="btn btn-primary w-100 mt-3 py-2 fw-bold" <?= $step==0?'disabled':'' ?>>Continue <i class="fa fa-arrow-right ms-1"></i></button>
        </form>
      </div>
    </div>
  </div>
  <div class="col-md-4">
    <div class="card">
      <div class="card-header">Account Summary</div>
      <div class="card-body">
        <div class="d-flex justify-content-between mb-2"><span class="text-muted small">Balance</span><strong><?= money((float)$currentUser['account_balance'],$currentUser['currency']) ?></strong></div>
        <div class="d-flex justify-content-between mb-2"><span class="text-muted small">Available</span><strong class="text-success"><?= money((float)$currentUser['available_balance'],$currentUser['currency']) ?></strong></div>
        <div class="d-flex justify-content-between mb-2"><span class="text-muted small">KYC Status</span><?= statusBadge($currentUser['kyc_status']) ?></div>
        <hr>
        <?php if (!empty($reqGates)): ?>
        <p class="small text-muted fw-bold mb-1">Security Gates</p>
        <?php $gateLabels=['otp'=>'Email OTP','imf'=>'IMF Code','cot'=>'COT Code','atc'=>'ATC Code','txc'=>'Tax Clearance'];
        foreach ($reqGates as $g): ?>
        <div class="small mb-1"><i class="fa fa-shield-alt me-1 text-warning"></i><?= $gateLabels[$g] ?></div>
        <?php endforeach; ?>
        <?php endif; ?>
      </div>
    </div>
  </div>
</div>

<?php elseif ($step == 2): ?>
<!-- Step 2: Security Gates -->
<div class="card">
  <div class="card-header">Security Verification</div>
  <div class="card-body">
    <div class="mb-3 p-3 bg-light rounded">
      <?php $td = $_SESSION['transfer_data']; ?>
      <div class="row g-2 small">
        <div class="col-6"><span class="text-muted">To:</span> <strong><?= sanitize($td['benName']) ?></strong></div>
        <div class="col-6"><span class="text-muted">Account:</span> <?= sanitize($td['benAccount']) ?></div>
        <div class="col-6"><span class="text-muted">Amount:</span> <strong class="text-danger"><?= money($td['amount'],$currentUser['currency']) ?></strong></div>
        <div class="col-6"><span class="text-muted">Fee:</span> <?= money($td['fee'],$currentUser['currency']) ?></div>
        <div class="col-12"><span class="text-muted">Total:</span> <strong><?= money($td['amount']+$td['fee'],$currentUser['currency']) ?></strong></div>
      </div>
    </div>

    <?php if ($nextGate): ?>
    <!-- Show the next required gate -->
    <?php $gateInfo = [
      'otp' => ['📧','Email OTP Verification','Enter the 6-digit code sent to your email.','otp_code','text','000000','verify_otp','OTP Code'],
      'imf' => ['🏦','IMF Code Required','Enter your International Monetary Fund clearance code.','imf_code','password','••••••','verify_imf','IMF Code'],
      'cot' => ['💼','Cost of Transfer Code','Enter your COT (Cost of Transfer) code.','cot_code','password','••••••','verify_cot','COT Code'],
      'atc' => ['🛡️','Anti-Terrorist Clearance','Enter your ATC (Anti-Terrorist Clearance) code.','atc_code','password','••••••','verify_atc','ATC Code'],
      'txc' => ['📋','Tax Clearance Code','Enter your TXC (Tax Clearance) code.','txc_code','password','••••••','verify_txc','Tax Clearance Code'],
    ]; [$icon,$title,$desc,$fname,$ftype,$placeholder,$action,$label] = $gateInfo[$nextGate]; ?>
    <div class="security-gate">
      <div class="gate-icon"><?= $icon ?></div>
      <h5><?= $title ?></h5>
      <p><?= $desc ?></p>
      <form method="POST">
        <?= csrf_field() ?><input type="hidden" name="action" value="<?= $action ?>">
        <div class="input-group mb-3" style="max-width:320px;margin:auto;">
          <input type="<?= $ftype ?>" name="<?= $fname ?>" class="form-control text-center fw-bold" placeholder="<?= $placeholder ?>" required <?= $ftype==='text'?'maxlength="6" style="letter-spacing:8px;font-size:1.3rem;"':'' ?>>
          <button class="btn btn-warning fw-bold">Verify</button>
        </div>
      </form>
    </div>
    <?php else: ?>
    <!-- All gates done – show PIN entry -->
    <div class="text-center mb-3"><span class="badge bg-success p-2"><i class="fa fa-check-circle me-1"></i>All security verifications passed</span></div>
    <form method="POST" class="text-center">
      <?= csrf_field() ?><input type="hidden" name="action" value="complete">
      <p class="fw-bold">Enter your 4-digit Transaction PIN to complete the transfer</p>
      <div class="input-group mb-3" style="max-width:240px;margin:auto;">
        <span class="input-group-text"><i class="fa fa-key"></i></span>
        <input type="password" name="transaction_pin" class="form-control text-center fw-bold" placeholder="••••" maxlength="4" pattern="\d{4}" required style="letter-spacing:8px;font-size:1.5rem;">
      </div>
      <button class="btn btn-danger px-5 py-2 fw-bold">Confirm Transfer</button>
    </form>
    <?php endif; ?>

    <div class="mt-3 text-center">
      <small class="text-muted">Gates completed: <?= count($doneGates) ?>/<?= count($reqGates) ?> &nbsp;|&nbsp;
      <?php foreach ($reqGates as $g): ?>
        <span class="badge <?= in_array($g,$doneGates)?'bg-success':'bg-secondary' ?>"><?= strtoupper($g) ?></span>
      <?php endforeach; ?>
      </small>
    </div>
    <div class="mt-2 text-center">
      <a href="/transfer.php?cancel=1" class="btn btn-sm btn-outline-secondary" onclick="return confirm('Cancel this transfer?')">Cancel Transfer</a>
    </div>
  </div>
</div>
<?php endif; ?>

</div></div>
<?php include 'includes/footer.php'; ?>
<script>
function fillBeneficiary(sel) {
  if (!sel.value) return;
  const b = JSON.parse(sel.value);
  document.getElementById('ben_name').value    = b.beneficiary_name || '';
  document.getElementById('ben_account').value = b.account_number || '';
  document.getElementById('ben_bank').value    = b.bank_name || '';
  document.getElementById('ben_swift').value   = b.swift_code || '';
}
</script>
<?php
if (isset($_GET['cancel'])) {
    unset($_SESSION['transfer_data'],$_SESSION['transfer_step'],$_SESSION['transfer_gates_done'],$_SESSION['otp_sent_for_transfer']);
    header('Location: /transfer.php'); exit;
}
?>
</body></html>
