<?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');

$id = isset($_POST['id']) ? intval($_POST['id']) : 0;

if ($id <= 0) {
    echo json_encode(['status' => 'error', 'message' => 'Invalid account ID']);
    exit;
}

// Fetch paystack_dva_id from DB
$fetchStmt = $con->prepare(
    "SELECT paystack_dva_id FROM school_virtual_accounts WHERE id = ? LIMIT 1"
);
$fetchStmt->bind_param('i', $id);
$fetchStmt->execute();
$fetchResult = $fetchStmt->get_result();
$accountRow  = $fetchResult->fetch_assoc();
$fetchStmt->close();

if (!$accountRow) {
    echo json_encode(['status' => 'error', 'message' => 'Account record not found']);
    exit;
}

$paystackDvaId = $accountRow['paystack_dva_id'];
$secretKey     = $_ENV['PAYSTACK_SECRET_KEY'];

// Call Paystack API to deactivate the DVA
$ch = curl_init("https://api.paystack.co/dedicated_account/{$paystackDvaId}");
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_CUSTOMREQUEST  => 'DELETE',
    CURLOPT_HTTPHEADER     => [
        'Authorization: Bearer ' . $secretKey,
        'Content-Type: application/json',
    ],
]);
$response  = curl_exec($ch);
$curlError = curl_error($ch);
curl_close($ch);

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

$result = json_decode($response, true);

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

// Update is_active = 0 in DB
$updateStmt = $con->prepare(
    "UPDATE school_virtual_accounts SET is_active = 0 WHERE id = ?"
);
$updateStmt->bind_param('i', $id);

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

echo json_encode(['status' => 'success']);
