<?php
// POST action=vtu_buy_airtime&api_key=KEY&network=MTN&phone=08012345678&amount=500
// Buy airtime

$user_id = $GLOBALS['api_user_id'];
$network = strtoupper(trim($_POST['network'] ?? $_GET['network'] ?? ''));
$phone   = trim($_POST['phone'] ?? $_GET['phone'] ?? '');
$amount  = (float)($_POST['amount'] ?? $_GET['amount'] ?? 0);

if (empty($network) || empty($phone) || $amount <= 0) {
    api_response(['status' => 'error', 'message' => 'Missing network, phone, or amount.'], 400);
}

if (!in_array($network, ['MTN', 'GLO', 'AIRTEL', '9MOBILE'])) {
    api_response(['status' => 'error', 'message' => 'Invalid network. Use: MTN, GLO, AIRTEL, 9MOBILE'], 400);
}

if (!preg_match('/^(0[789][01]\d{8}|234[789][01]\d{8})$/', preg_replace('/\D/', '', $phone))) {
    api_response(['status' => 'error', 'message' => 'Invalid phone number format.'], 400);
}

// Simulate internal VTU purchase
$_POST['action']  = 'buy_airtime';
$_POST['network'] = $network;
$_POST['phone']   = $phone;
$_POST['amount']  = $amount;

$_SESSION['user_id']   = $user_id;
$_SESSION['logged_in'] = true;

ob_start();
require __DIR__ . '/../../user/ajax/vtu-purchase.php';
$output = ob_get_clean();

$data = json_decode($output, true);
if (!$data) {
    api_response(['status' => 'error', 'message' => 'Internal processing error.'], 500);
}

if ($data['status'] === '1') {
    api_response([
        'status'  => 'success',
        'message' => $data['msg'] ?? 'Airtime purchased successfully.',
        'network' => $network,
        'phone'   => $phone,
        'amount'  => $amount,
    ]);
} else {
    api_response([
        'status'  => 'error',
        'message' => $data['msg'] ?? 'Purchase failed.',
    ], 400);
}
