<?php
require_once '../config/conn.php';
require_once '../config/paystack.php'; // Contains Paystack secret key

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    die(json_encode(['success' => false, 'message' => 'Invalid request method']));
}

$data = json_decode(file_get_contents('php://input'), true);
$bank_code = $data['bank_code'] ?? '';
$account_number = $data['account_number'] ?? '';

if (empty($bank_code) || empty($account_number)) {
    die(json_encode(['success' => false, 'message' => 'Bank code and account number are required']));
}

// Verify with Paystack API
$curl = curl_init();
curl_setopt_array($curl, [
    CURLOPT_URL => "https://api.paystack.co/bank/resolve?account_number=" . rawurlencode($account_number) . 
                   "&bank_code=" . rawurlencode($bank_code),
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => [
        "Authorization: Bearer " . PAYSTACK_SECRET_KEY
    ],
]);

$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);

if ($err) {
    die(json_encode(['success' => false, 'message' => 'Verification failed: ' . $err]));
}

$result = json_decode($response, true);

if (!$result['status']) {
    die(json_encode(['success' => false, 'message' => $result['message']]));
}

echo json_encode([
    'success' => true,
    'account_name' => $result['data']['account_name']
]);
?>