<?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/middleware/auth.php';

session_boot();
require_login();

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

$step = $_GET['step'] ?? 'form';

/* ===============================
   LOAD ENABLED ASSETS
================================ */
$assets = [];
$res = $conn->query("
  SELECT id, symbol, name
  FROM crypto_assets
  WHERE enabled = 1
  ORDER BY symbol ASC
");
while ($r = $res->fetch_assoc()) {
  $assets[] = $r;
}

/* ===============================
   HANDLE POST
================================ */
if (is_post()) {
  csrf_verify();
  $action = $_POST['action'] ?? '';

  /* ---------- CREATE SEND ---------- */
  if ($action === 'create') {
    try {
      $assetId     = (int)($_POST['asset_id'] ?? 0);
      $amount      = (float)($_POST['amount'] ?? 0);
      $destination = trim($_POST['destination'] ?? '');

      if ($assetId < 1) throw new Exception('Select asset');
      if ($amount <= 0) throw new Exception('Invalid amount');
      if (strlen($destination) < 6) throw new Exception('Destination address required');

      /* CHECK BALANCE */
      $st = $conn->prepare("
        SELECT balance
        FROM crypto_wallets
        WHERE user_id = ? AND asset_id = ?
        LIMIT 1
      ");
      $st->bind_param("ii", $u['id'], $assetId);
      $st->execute();
      $bal = (float)($st->get_result()->fetch_assoc()['balance'] ?? 0);

      if ($bal < $amount) throw new Exception('Insufficient balance');

      /* CREATE TRANSACTION */
      $ref = now_ref('CTX');

      $st = $conn->prepare("
        INSERT INTO crypto_txn
          (ref, user_id, asset_id, type, amount, fee, status, destination)
        VALUES
          (?, ?, ?, 'send', ?, 0, 'otp_pending', ?)
      ");
      $st->bind_param(
        "siids",
        $ref,
        $u['id'],
        $assetId,
        $amount,
        $destination
      );
      $st->execute();

      $_SESSION['pending_crypto_ref'] = $ref;

      otp_create($conn, (int)$u['id'], 'crypto_send', $u['email'], 5);

      flash('msg', 'OTP sent. Enter code to continue.');
      redirect('crypto.php?step=verify');

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

  /* ---------- VERIFY OTP ---------- */
  if ($action === 'verify') {
    $otp = trim($_POST['otp'] ?? '');
    $ref = $_SESSION['pending_crypto_ref'] ?? '';

    if (!$ref) redirect('crypto_wallet.php');

    if (!otp_verify($conn, (int)$u['id'], 'crypto_send', $otp)) {
      flash('err', 'Invalid or expired OTP');
      redirect('crypto.php?step=verify');
    }

    $st = $conn->prepare("
      UPDATE crypto_txn
      SET status = 'pending_admin'
      WHERE ref = ? AND user_id = ?
    ");
    $st->bind_param("si", $ref, $u['id']);
    $st->execute();

    unset($_SESSION['pending_crypto_ref']);

    flash('msg', 'Transaction submitted for admin approval.');
    redirect('crypto_wallet.php');
  }
}

/* ===============================
   VIEW
================================ */
$title = 'Send Crypto';
include __DIR__ . '/../../views/partials/head.php';
include __DIR__ . '/../../views/partials/customer_sidebar.php';
?>

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

  <div class="d-flex flex-wrap gap-2 align-items-center justify-content-between mb-3">
    <div>
      <h3 class="fw-bold mb-0">Send Crypto</h3>
      <div class="ab-muted">OTP required. Transaction is queued for admin approval.</div>
    </div>
    <a class="btn btn-outline-secondary" href="crypto_wallet.php">
      <i class="bi bi-arrow-left"></i> Back
    </a>
  </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; ?>

<?php if ($step === 'verify'): ?>

<!-- OTP STEP -->
<div class="card ab-card p-4" style="max-width:420px">
  <h5 class="fw-bold mb-3">OTP Verification</h5>
  <form method="post">
    <?= csrf_field() ?>
    <input type="hidden" name="action" value="verify">
    <input class="form-control mb-3" name="otp" placeholder="Enter OTP" required>
    <button class="btn ab-btn text-white w-100">Verify</button>
  </form>
</div>

<?php else: ?>

<!-- SEND FORM -->
<div class="card ab-card p-4" style="max-width:700px">
<form method="post">
<?= csrf_field() ?>
<input type="hidden" name="action" value="create">

<div class="row g-3">

  <div class="col-md-4">
    <label class="form-label">Asset</label>
    <select name="asset_id" class="form-select" required>
      <option value="">Select</option>
      <?php foreach ($assets as $a): ?>
        <option value="<?= $a['id'] ?>">
          <?= e($a['symbol']) ?> — <?= e($a['name']) ?>
        </option>
      <?php endforeach; ?>
    </select>
  </div>

  <div class="col-md-4">
    <label class="form-label">Amount</label>
    <input type="number" step="0.00000001" name="amount" class="form-control" required>
  </div>

  <div class="col-md-12">
    <label class="form-label">Destination Address</label>
    <input
      name="destination"
      class="form-control"
      placeholder="Paste destination wallet address"
      required
    >
  </div>

  <div class="col-12">
    <button class="btn ab-btn text-white w-100">
      <i class="bi bi-send me-1"></i> Send OTP
    </button>
  </div>

</div>
</form>
</div>

<?php endif; ?>

</div>
</main>

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