<?php
/**
 * get_banks.php — Returns Nigerian bank list from Paystack as JSON.
 * Called by withdrawal.php via AJAX: fetch('get_banks.php')
 */
ob_start();
include("config/paystack.php");
ob_clean();

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

if (!defined('PAYSTACK_SECRET') || empty(PAYSTACK_SECRET)) {
    echo json_encode(['error' => 'Payment config missing.']);
    exit;
}

$url = 'https://api.paystack.co/bank?currency=NGN&perPage=100';

$response = ps_curl_get($url, true);          // try with SSL
if ($response === false) {
    $response = ps_curl_get($url, false);     // fallback without SSL (localhost dev)
}

if ($response === false) {
    http_response_code(500);
    echo json_encode(['error' => 'Could not connect to Paystack. Check your internet connection.']);
    exit;
}

$result = json_decode($response, true);

if (empty($result['status']) || empty($result['data'])) {
    http_response_code(502);
    echo json_encode(['error' => $result['message'] ?? 'Paystack returned an empty bank list.']);
    exit;
}

echo json_encode($result['data']);

function ps_curl_get(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;
}
