<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);

require_once __DIR__.'/../includes/db.php';
require_once __DIR__.'/../includes/auth.php';
require_once __DIR__.'/../includes/helpers.php';
require_login();
$page_title = "Payouts • Bank Details";

if (empty($_SESSION['csrf'])) $_SESSION['csrf'] = bin2hex(random_bytes(16));

// Load bank list
$banks = require __DIR__.'/../includes/banks_ng.php';

// Fetch current details
$sel = $pdo->prepare("SELECT bank_name, account_number, account_name, country_code, updated_at 
                      FROM user_bank_details WHERE user_id=:uid LIMIT 1");
$sel->execute([':uid'=>$_SESSION['uid']]);
$bank = $sel->fetch();

// Save (after verification)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  if (empty($_POST['csrf']) || $_POST['csrf'] !== ($_SESSION['csrf'] ?? '')) {
    flash_err('Invalid request token.'); header('Location: payouts.php'); exit;
  }

  $bank_code      = trim($_POST['bank_code'] ?? '');
  $bank_name      = trim($_POST['bank_name'] ?? ''); // we store the nice label as well
  $account_number = preg_replace('/\D+/', '', trim($_POST['account_number'] ?? ''));
  $account_name   = trim($_POST['account_name'] ?? '');
  $country_code   = strtoupper(trim($_POST['country_code'] ?? 'NG'));

  $errors = [];
  if (!preg_match('/^\d{8,20}$/', $account_number)) $errors[] = 'Account number must be 8–20 digits.';
  if ($account_name === '') $errors[] = 'Please verify to fetch account name.';
  if (!preg_match('/^[A-Z]{2}$/', $country_code)) $country_code = 'NG';

  if ($errors) { flash_err(implode(' ', $errors)); header('Location: payouts.php'); exit; }

  $up = $pdo->prepare("
    INSERT INTO user_bank_details (user_id, bank_name, account_number, account_name, country_code)
    VALUES (:uid, :bank, :acct, :name, :cc)
    ON DUPLICATE KEY UPDATE
      bank_name=VALUES(bank_name),
      account_number=VALUES(account_number),
      account_name=VALUES(account_name),
      country_code=VALUES(country_code)
  ");
  $up->execute([
    ':uid'=>$_SESSION['uid'],
    ':bank'=>$bank_name,
    ':acct'=>$account_number,
    ':name'=>$account_name,
    ':cc'=>$country_code,
  ]);

  flash_ok('Bank details saved.'); header('Location: payouts.php'); exit;
}

include __DIR__.'/../includes/header.php';
?>

<div class="row g-4">

  <div class="col-md-9">
    <div class="card shadow-sm">
      <div class="card-body">
        <h5 class="card-title mb-3">Payouts (Bank Details)</h5>
        <p class="text-muted">Select your bank, enter your account number, click <b>Verify</b> to fetch your registered account name, then save.</p>

        <form method="post" class="row g-3" id="bankForm" autocomplete="off" novalidate>
          <div class="col-md-6">
            <label class="form-label">Bank</label>
            <select class="form-select" name="bank_code" id="bank_code" required>
              <option value="">Select bank…</option>
              <?php
                $curName = $bank['bank_name'] ?? '';
                foreach ($banks as $b) {
                  $sel = ($curName === $b['name']) ? 'selected' : '';
                  echo "<option value=\"{$b['code']}\" data-name=\"".sanitize($b['name'])."\" $sel>{$b['name']}</option>";
                }
              ?>
            </select>
            <input type="hidden" name="bank_name" id="bank_name"
                   value="<?= sanitize($bank['bank_name'] ?? '') ?>">
          </div>

          <div class="col-md-6">
            <label class="form-label">Account number</label>
            <div class="input-group">
              <input class="form-control" name="account_number" id="account_number"
                     value="<?= sanitize($bank['account_number'] ?? '') ?>"
                     placeholder="10-digit account (NG)" required>
              <button class="btn btn-outline-secondary" type="button" id="btnVerify">Verify</button>
            </div>
            <div class="form-text" id="verifyMsg"></div>
          </div>

          <div class="col-md-6">
            <label class="form-label">Account name (from bank)</label>
            <input class="form-control" name="account_name" id="account_name"
                   value="<?= sanitize($bank['account_name'] ?? '') ?>" readonly required>
          </div>

          <div class="col-md-3">
            <label class="form-label">Country</label>
            <select class="form-select" name="country_code">
              <?php
                $countries = ['NG'=>'Nigeria','GH'=>'Ghana','KE'=>'Kenya','ZA'=>'South Africa','US'=>'United States','GB'=>'United Kingdom'];
                $sel_cc = $bank['country_code'] ?? 'NG';
                foreach ($countries as $cc=>$label) {
                  $sel = $sel_cc === $cc ? 'selected' : '';
                  echo "<option value=\"{$cc}\" {$sel}>$label</option>";
                }
              ?>
            </select>
          </div>

          <div class="col-12">
            <input type="hidden" name="csrf" value="<?= $_SESSION['csrf'] ?>">
            <button class="btn btn-dark" id="btnSave" disabled>Save details</button>
            <?php if (!empty($bank['updated_at'])): ?>
              <span class="text-muted ms-2 small">Last updated: <?= sanitize($bank['updated_at']) ?></span>
            <?php endif; ?>
          </div>
        </form>
      </div>
    </div>
  </div>
</div>

<script>
(function(){
  const bankSel  = document.getElementById('bank_code');
  const bankName = document.getElementById('bank_name');
  const acct     = document.getElementById('account_number');
  const accName  = document.getElementById('account_name');
  const msg      = document.getElementById('verifyMsg');
  const btnV     = document.getElementById('btnVerify');
  const btnS     = document.getElementById('btnSave');
  const csrf     = '<?= $_SESSION['csrf'] ?>';

  function setMsg(text, ok){
    msg.textContent = text;
    msg.className   = 'form-text ' + (ok ? 'text-success' : 'text-danger');
  }
  function setSavingAllowed(ok){
    btnS.disabled = !ok;
  }
  bankSel.addEventListener('change', () => {
    bankName.value = bankSel.options[bankSel.selectedIndex]?.dataset?.name || '';
    setMsg('', true);
    setSavingAllowed(!!accName.value);
  });

  btnV.addEventListener('click', async () => {
    setMsg('Verifying…', true);
    setSavingAllowed(false);
    accName.value = '';

    const bank_code = bankSel.value.trim();
    const account_number = acct.value.replace(/\D+/g, '');
    if (!bank_code || account_number.length < 8){
      setMsg('Choose bank and enter a valid account number.', false);
      return;
    }

    try {
      const url = `verify_account.php?bank_code=${encodeURIComponent(bank_code)}&account_number=${encodeURIComponent(account_number)}&csrf=${encodeURIComponent(csrf)}`;
      const res = await fetch(url, {credentials:'same-origin'});
      const data = await res.json();
      if (data.ok){
        accName.value = data.account_name;
        setMsg('✅ Verified', true);
        setSavingAllowed(true);
      } else {
        setMsg('❌ ' + (data.error || 'Verification failed'), false);
      }
    } catch(e){
      setMsg('❌ Network error', false);
    }
  });
})();
</script>

<?php include __DIR__.'/../includes/footer.php'; ?>
