<?php

// Only allow POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    exit;
}

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

// Session setup — same pattern as manage_wallet.php
session_name('super_admin_session');

if (!is_dir(dirname(__DIR__) . '/session_data/super')) {
    mkdir(dirname(__DIR__) . '/session_data/super', 0700, true);
}
session_save_path(dirname(__DIR__) . '/session_data/super');

session_set_cookie_params(['path' => '/', 'httponly' => true, 'samesite' => 'Strict']);

session_start();

error_reporting(0);

// Admin auth check
if (empty($_SESSION['sid'])) {
    http_response_code(403);
    echo json_encode(['status' => 'error', 'message' => 'Unauthorized']);
    exit;
}

require_once 'vendor/autoload.php';

$dotenv = Dotenv\Dotenv::createImmutable(__DIR__ . '/..');
$dotenv->load();

include('includes/dbconnection.php');

$customer_code  = trim($_POST['customer_code'] ?? '');
$preferred_bank = trim($_POST['preferred_bank'] ?? '');

// Call Paystack API to create dedicated virtual account
$secretKey = $_ENV['PAYSTACK_SECRET_KEY'];

$payload = json_encode([
    'customer'       => $customer_code,
    'preferred_bank' => $preferred_bank,
]);

$ch = curl_init('https://api.paystack.co/dedicated_account');
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST           => true,
    CURLOPT_POSTFIELDS     => $payload,
    CURLOPT_HTTPHEADER     => [
        'Authorization: Bearer ' . $secretKey,
        'Content-Type: application/json',
    ],
]);

$response = curl_exec($ch);
curl_close($ch);

$result = json_decode($response, true);

if (!$result || !isset($result['status'])) {
    echo json_encode(['status' => 'error', 'message' => 'Could not reach payment provider']);
    exit;
}

if ($result['status'] !== true) {
    $msg = $result['message'] ?? 'Paystack error';
    echo json_encode(['status' => 'error', 'message' => $msg]);
    exit;
}

// Map fields from Paystack response
$data           = $result['data'];
$bank_name      = $data['bank']['name'];
$account_number = $data['account_number'];
$account_name   = $data['account_name'];
$paystack_customer_id = $data['customer']['customer_code'];
$paystack_dva_id      = (string) $data['id'];

// Insert into school_virtual_accounts
$stmt = $con->prepare(
    "INSERT INTO school_virtual_accounts (bank_name, account_number, account_name, paystack_customer_id, paystack_dva_id, is_active)
     VALUES (?, ?, ?, ?, ?, 1)"
);

$stmt->bind_param('sssss', $bank_name, $account_number, $account_name, $paystack_customer_id, $paystack_dva_id);

if (!$stmt->execute()) {
    echo json_encode(['status' => 'error', 'message' => 'Could not save account record']);
    exit;
}

echo json_encode([
    'status'  => 'success',
    'account' => [
        'bank_name'      => $bank_name,
        'account_number' => $account_number,
        'account_name'   => $account_name,
    ],
]);
