<?php
header('Content-Type: application/json');

require_once __DIR__.'/../includes/db.php';
require_once __DIR__.'/../includes/auth.php';
require_once __DIR__.'/../includes/helpers.php';
require_once __DIR__.'/../includes/config.php';
require_login();

// CSRF
$csrf = $_GET['csrf'] ?? $_POST['csrf'] ?? '';
if (!$csrf || $csrf !== ($_SESSION['csrf'] ?? '')) {
  http_response_code(400);
  echo json_encode(['ok'=>false,'error'=>'Bad token']); exit;
}

// Inputs
$bank_code = trim($_GET['bank_code'] ?? '');
$acct      = preg_replace('/\D+/', '', $_GET['account_number'] ?? '');

// Basic validation (before any test-mode overrides)
if (!preg_match('/^\d{8,20}$/', $acct)) {
  http_response_code(422);
  echo json_encode(['ok'=>false,'error'=>'Account number must be 8–20 digits']); exit;
}
if (!preg_match('/^\d{2,6}$/', $bank_code)) {
  // We'll override this in test mode, but in live mode we need a valid code
  $bank_code = ''; // mark invalid for now
}

// Config
if (empty(PAYSTACK_SECRET)) {
  http_response_code(500);
  echo json_encode(['ok'=>false,'error'=>'Paystack secret not set']); exit;
}
$IS_TEST_MODE = (strpos(PAYSTACK_SECRET, 'sk_test_') === 0);

// --- Test Mode unlimited: force Test Bank (001) and 10-digit acct ---
if ($IS_TEST_MODE) {
  $bank_code = '001';
  // Ensure exactly 10 digits for the mock bank (pads or trims)
  if (!preg_match('/^\d{10}$/', $acct)) {
    $acct = str_pad(substr($acct, 0, 10), 10, '0', STR_PAD_LEFT);
  }
} else {
  // Live mode: require a valid bank code from the client
  if ($bank_code === '') {
    http_response_code(422);
    echo json_encode(['ok'=>false,'error'=>'Bank code missing/invalid']); exit;
  }
}

// Build request
$qs  = http_build_query(['account_number'=>$acct,'bank_code'=>$bank_code]);
$url = "https://api.paystack.co/bank/resolve?$qs";

// Call Paystack
$ch = curl_init($url);
curl_setopt_array($ch, [
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_HTTPHEADER => [
    'Authorization: Bearer '.PAYSTACK_SECRET,
    'Accept: application/json',
  ],
  CURLOPT_TIMEOUT => 20,
]);
$resp = curl_exec($ch);
$errno= curl_errno($ch);
$err  = curl_error($ch);
$http = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($errno) {
  http_response_code(502);
  echo json_encode(['ok'=>false,'error'=>'Gateway error: '.$err]); exit;
}

$data = json_decode($resp, true);

// Success
if ($http>=200 && $http<300 && !empty($data['status']) && !empty($data['data']['account_name'])) {
  echo json_encode(['ok'=>true,'account_name'=>$data['data']['account_name']]); exit;
}

// Failure (debug friendly)
$msg = $data['message'] ?? 'Verification failed';
if (defined('APP_DEBUG_VERIFY') && APP_DEBUG_VERIFY) {
  $details = [
    'http'   => $http,
    'status' => $data['status'] ?? null,
    'msg'    => $msg,
    'raw'    => $data,
    'mode'   => $IS_TEST_MODE ? 'test' : 'live',
    'bank'   => $bank_code,
    'acct'   => $acct,
  ];
  http_response_code(422);
  echo json_encode(['ok'=>false,'error'=>'Provider: '.$msg,'debug'=>$details]); exit;
}

http_response_code(422);
echo json_encode(['ok'=>false,'error'=>$msg]); exit;
