<?php
session_start();
if (!isset($_SESSION['user_id'])) { header("Location: signin.php?redirect=" . urlencode($_SERVER['REQUEST_URI'])); exit; }

$page_title = 'Withdraw Funds';
$active_nav = 'withdraw';
include("includes/header.php");
include("config/paystack.php");

$uid = (int)$_SESSION['user_id'];
?>

<div style="max-width:580px;margin:0 auto">
  <div style="margin-bottom:28px">
    <a href="wallet.php" style="display:inline-flex;align-items:center;gap:6px;font-size:.82rem;color:var(--text-muted);font-weight:600;margin-bottom:14px">
      <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><path d="M19 12H5m0 0l7 7M5 12l7-7"/></svg>
      Back to Wallet
    </a>
    <h1 style="font-size:1.5rem;font-weight:800;letter-spacing:-.03em;margin-bottom:4px">Withdraw Funds</h1>
    <p style="color:var(--text-muted);font-size:.875rem">Transfer your wallet balance to any Nigerian bank account</p>
  </div>

  <!-- Balance Banner -->
  <div style="background:var(--primary-bg);border:1.5px solid rgba(34,90,227,.2);border-radius:14px;padding:18px 22px;display:flex;align-items:center;justify-content:space-between;margin-bottom:24px">
    <div>
      <div style="font-size:.7rem;font-weight:700;text-transform:uppercase;letter-spacing:.1em;color:var(--primary);opacity:.7;margin-bottom:3px">Available Balance</div>
      <div style="font-size:1.5rem;font-weight:800;letter-spacing:-.03em;color:var(--primary)">₦<?php echo number_format($__balance, 2); ?></div>
    </div>
    <?php if ($__balance < 100): ?>
      <span class="badge badge-error" style="font-size:.75rem">Low Balance</span>
    <?php endif; ?>
  </div>

  <?php if ($__balance < 100): ?>
  <div class="alert alert-warning" style="margin-bottom:20px">
    <svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round" fill="none" stroke="currentColor" width="16" height="16"><path d="M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>
    Your balance is too low to withdraw. Minimum withdrawal is ₦100.
    <a href="fund_wallet.php" style="font-weight:700;color:var(--warning);margin-left:4px">Fund wallet →</a>
  </div>
  <?php endif; ?>

  <div class="card">
    <div class="card-header"><h3>Bank Transfer</h3></div>
    <div class="card-body">

      <div id="successMsg" class="alert alert-success" style="display:none">
        <svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round" fill="none" stroke="currentColor" width="16" height="16"><path d="M22 11.08V12a10 10 0 11-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>
        <span id="successText"></span>
      </div>
      <div id="errorMsg" class="alert alert-error" style="display:none">
        <svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round" fill="none" stroke="currentColor" width="16" height="16"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>
        <span id="errorText"></span>
      </div>

      <!-- Bank loading states -->
      <div id="bankLoadingMsg" class="alert alert-info" style="margin-bottom:16px">
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" id="bankSpinner" style="animation:spin .8s linear infinite"><circle cx="12" cy="12" r="10" stroke-dasharray="30 70"/></svg>
        Loading bank list from Paystack…
      </div>
      <div id="bankErrorMsg" class="alert alert-error" style="display:none;margin-bottom:16px">
        <svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round" fill="none" stroke="currentColor" width="16" height="16"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/></svg>
        Failed to load banks.
        <button onclick="loadBanks()" style="background:none;border:none;cursor:pointer;font-weight:700;color:var(--error);font-family:inherit;font-size:.82rem;padding:0;margin-left:6px;text-decoration:underline">Retry</button>
      </div>

      <form id="withdrawForm">

        <div class="form-group">
          <label>Select Bank</label>
          <select name="bank_code" id="bankSelect" class="form-control" required disabled>
            <option value="">Loading…</option>
          </select>
        </div>

        <div class="form-group">
          <label>Account Number</label>
          <input type="text" name="account_number" id="accNum" class="form-control"
                 maxlength="10" placeholder="10-digit account number" required>

          <div id="accNameWrap" style="display:none;margin-top:8px;padding:10px 14px;
               background:var(--success-bg);border-radius:8px;border:1px solid #BBF7D0">
            <div style="display:flex;align-items:center;gap:8px">
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="var(--success)"
                   stroke-width="2.5" stroke-linecap="round">
                <path d="M22 11.08V12a10 10 0 11-5.93-9.14"/>
                <polyline points="22 4 12 14.01 9 11.01"/>
              </svg>
              <span style="font-size:.82rem;font-weight:700;color:var(--success)" id="accNameText"></span>
            </div>
          </div>

          <div id="accErrWrap" style="display:none;margin-top:8px;padding:10px 14px;
               background:var(--error-bg);border-radius:8px;border:1px solid #FECACA">
            <span style="font-size:.8rem;color:var(--error);font-weight:600">
              Could not verify account. Check your details.
            </span>
          </div>

          <div id="accLoading" style="display:none;margin-top:8px;font-size:.78rem;
               color:var(--text-muted);align-items:center;gap:6px">
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor"
                 stroke-width="2" style="animation:spin .8s linear infinite">
              <circle cx="12" cy="12" r="10" stroke-dasharray="30 70"/>
            </svg>
            Verifying account…
          </div>
        </div>

        <div class="form-group">
          <label>Amount (₦)</label>
          <div style="position:relative">
            <span style="position:absolute;left:14px;top:50%;transform:translateY(-50%);font-weight:700;color:var(--text-muted)">₦</span>
            <input type="number" name="amount" id="wdAmount" class="form-control"
                   placeholder="0.00" min="100" max="<?php echo $__balance; ?>"
                   step="0.01"
                   style="padding-left:30px;font-size:1rem;font-weight:700;height:50px"
                   required>
          </div>
          <div style="font-size:.75rem;color:var(--text-muted);margin-top:5px">
            Max: ₦<?php echo number_format($__balance, 2); ?> &bull; Min: ₦100
          </div>
        </div>

        <!-- Quick amounts -->
        <div style="display:flex;gap:8px;margin-bottom:20px;flex-wrap:wrap">
          <?php foreach ([500, 1000, 2000, 5000] as $qa): ?>
            <?php if ($__balance >= $qa): ?>
            <button type="button" onclick="setWdAmount(<?php echo $qa; ?>)"
                    class="btn btn-secondary btn-sm" style="font-size:.78rem;font-weight:700">
              ₦<?php echo number_format($qa); ?>
            </button>
            <?php endif; ?>
          <?php endforeach; ?>
        </div>

        <button type="submit" class="btn btn-primary btn-lg btn-block" id="wdBtn"
          <?php echo ($__balance < 100) ? 'disabled style="opacity:.5;cursor:not-allowed"' : ''; ?>>
          <svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round" fill="none"
               stroke="currentColor" width="16" height="16">
            <path d="M12 5v14m-7-7l7 7 7-7"/>
          </svg>
          Withdraw Funds
        </button>

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

  <div style="display:flex;align-items:center;justify-content:center;gap:8px;
       margin-top:20px;font-size:.78rem;color:var(--text-muted)">
    <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor"
         stroke-width="2" stroke-linecap="round">
      <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>
    </svg>
    Transfers processed securely via Paystack &bull; 0–30 minutes
  </div>
</div>

<style>
@keyframes spin { to { transform: rotate(360deg); } }
</style>

<script>
/* ── Load banks ──────────────────────────────────────────────────────────────*/
function loadBanks() {
  const sel      = document.getElementById('bankSelect');
  const loadMsg  = document.getElementById('bankLoadingMsg');
  const errMsg   = document.getElementById('bankErrorMsg');

  sel.disabled       = true;
  sel.innerHTML      = '<option value="">Loading…</option>';
  loadMsg.style.display = 'flex';
  errMsg.style.display  = 'none';

  fetch('get_banks.php')
    .then(r => {
      if (!r.ok) throw new Error('HTTP ' + r.status);
      return r.json();
    })
    .then(data => {
      loadMsg.style.display = 'none';

      if (!Array.isArray(data) || data.length === 0) {
        throw new Error('Empty bank list');
      }

      sel.innerHTML = '<option value="">— Select your bank —</option>';
      data.sort((a, b) => a.name.localeCompare(b.name))
          .forEach(b => {
            sel.innerHTML += `<option value="${b.code}">${b.name}</option>`;
          });
      sel.disabled = false;
    })
    .catch(err => {
      loadMsg.style.display = 'none';
      errMsg.style.display  = 'flex';
      console.error('Bank load error:', err);
    });
}

/* ── Account verification ────────────────────────────────────────────────────*/
let verifyTimer;

function verifyAccount() {
  const acc      = document.getElementById('accNum').value.trim();
  const bank     = document.getElementById('bankSelect').value;
  const nameWrap = document.getElementById('accNameWrap');
  const errWrap  = document.getElementById('accErrWrap');
  const loading  = document.getElementById('accLoading');

  nameWrap.style.display = 'none';
  errWrap.style.display  = 'none';
  loading.style.display  = 'none';

  if (acc.length === 10 && bank) {
    loading.style.display = 'flex';
    clearTimeout(verifyTimer);
    verifyTimer = setTimeout(() => {
      fetch(`verify_account.php?account_number=${acc}&bank_code=${bank}`)
        .then(r => r.json())
        .then(d => {
          loading.style.display = 'none';
          if (d.status) {
            document.getElementById('accNameText').textContent = d.account_name;
            nameWrap.style.display = 'block';
          } else {
            errWrap.style.display = 'block';
          }
        })
        .catch(() => { loading.style.display = 'none'; });
    }, 800);
  }
}

document.getElementById('accNum').addEventListener('input', verifyAccount);
document.getElementById('bankSelect').addEventListener('change', verifyAccount);

/* ── Quick amount ────────────────────────────────────────────────────────────*/
function setWdAmount(v) {
  document.getElementById('wdAmount').value = v;
}

/* ── Submit ──────────────────────────────────────────────────────────────────*/
document.getElementById('withdrawForm').addEventListener('submit', function (e) {
  e.preventDefault();

  const btn     = document.getElementById('wdBtn');
  const errDiv  = document.getElementById('errorMsg');
  const succDiv = document.getElementById('successMsg');
  errDiv.style.display  = 'none';
  succDiv.style.display = 'none';

  // Must have verified account name before submitting
  if (document.getElementById('accNameWrap').style.display === 'none') {
    document.getElementById('errorText').textContent =
      'Please wait for account verification to complete before withdrawing.';
    errDiv.style.display = 'flex';
    errDiv.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
    return;
  }

  btn.disabled = true;
  btn.innerHTML = `
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor"
         stroke-width="2" style="animation:spin .8s linear infinite">
      <circle cx="12" cy="12" r="10" stroke-dasharray="30 70"/>
    </svg>
    Processing…`;

  fetch('withdraw.php', { method: 'POST', body: new FormData(this) })
    .then(r => r.json())
    .then(data => {
      btn.disabled = false;
      btn.innerHTML = `
        <svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round" fill="none"
             stroke="currentColor" width="16" height="16">
          <path d="M12 5v14m-7-7l7 7 7-7"/>
        </svg>
        Withdraw Funds`;

      if (data.success) {
        document.getElementById('successText').textContent = data.message;
        succDiv.style.display = 'flex';
        this.reset();
        document.getElementById('accNameWrap').style.display = 'none';
        succDiv.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
        setTimeout(() => window.location.href = 'wallet.php', 3000);
      } else {
        document.getElementById('errorText').textContent = data.message || 'An error occurred. Please try again.';
        errDiv.style.display = 'flex';
        errDiv.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
      }
    })
    .catch(err => {
      btn.disabled = false;
      btn.innerHTML = `
        <svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round" fill="none"
             stroke="currentColor" width="16" height="16">
          <path d="M12 5v14m-7-7l7 7 7-7"/>
        </svg>
        Withdraw Funds`;
      document.getElementById('errorText').textContent = 'Network error. Please check your connection and try again.';
      errDiv.style.display = 'flex';
      console.error('Withdraw fetch error:', err);
    });
});

// Kick off bank loading on page ready
loadBanks();
</script>

<?php include("includes/footer.php"); ?>
