<?php
/**
 * verify_account.php — Resolves a bank account number to account name via Paystack.
 * Called by withdrawal.php via AJAX: fetch('verify_account.php?account_number=...&bank_code=...')
 */
ob_start();
include("config/paystack.php");
ob_clean();

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

$account_number = trim($_GET['account_number'] ?? '');
$bank_code      = trim($_GET['bank_code']      ?? '');

// Validate
if (strlen($account_number) !== 10 || !ctype_digit($account_number)) {
    echo json_encode(['status' => false, 'message' => 'Account number must be exactly 10 digits.']);
    exit;
}
if (empty($bank_code)) {
    echo json_encode(['status' => false, 'message' => 'No bank selected.']);
    exit;
}
if (!defined('PAYSTACK_SECRET') || empty(PAYSTACK_SECRET)) {
    echo json_encode(['status' => false, 'message' => 'Payment config error. Contact support.']);
    exit;
}

$url = 'https://api.paystack.co/bank/resolve'
     . '?account_number=' . urlencode($account_number)
     . '&bank_code='      . urlencode($bank_code);

// Try SSL first, fallback for localhost
$response = va_curl($url, true);
if ($response === false) {
    $response = va_curl($url, false);
}

if ($response === false) {
    echo json_encode(['status' => false, 'message' => 'Connection error. Check your internet and try again.']);
    exit;
}

// Log for debugging
@file_put_contents(
    __DIR__ . '/paystack_log.txt',
    date('Y-m-d H:i:s') . " | verify_account | acc={$account_number} | bank={$bank_code} | {$response}\n",
    FILE_APPEND
);

$result = json_decode($response, true);

if ($result === null) {
    echo json_encode(['status' => false, 'message' => 'Invalid response from payment gateway.']);
    exit;
}

if (!empty($result['status']) && $result['status'] === true && !empty($result['data']['account_name'])) {
    echo json_encode([
        'status'         => true,
        'account_name'   => $result['data']['account_name'],
        'account_number' => $account_number,
    ]);
    exit;
}

// Friendly error messages
$msg = $result['message'] ?? 'Could not resolve account.';
if (stripos($msg, 'Could not resolve') !== false) {
    $msg = 'Account not found. Check the account number and selected bank.';
} elseif (stripos($msg, 'Invalid key') !== false || stripos($msg, 'No API key') !== false) {
    $msg = 'Payment gateway authentication failed. Contact support.';
} elseif (stripos($msg, 'balance') !== false) {
    $msg = 'Low Paystack balance. Please top up your Paystack account.';
}

echo json_encode(['status' => false, 'message' => $msg]);

function va_curl(string $url, bool $verify_ssl): string|false {
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL            => $url,
        CURLOPT_HTTPHEADER     => [
            'Authorization: Bearer ' . PAYSTACK_SECRET,
            'Accept: application/json',
            'Cache-Control: no-cache',
        ],
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT        => 30,
        CURLOPT_CONNECTTIMEOUT => 10,
        CURLOPT_SSL_VERIFYPEER => $verify_ssl,
        CURLOPT_SSL_VERIFYHOST => $verify_ssl ? 2 : 0,
        CURLOPT_FOLLOWLOCATION => true,
    ]);
    $res = curl_exec($ch);
    $err = curl_errno($ch);
    curl_close($ch);
    return ($err === 0 && $res !== false) ? $res : false;
}
