<?php
// GET ?action=sms_buy&api_key=KEY&country_id=ID&service_id=SVC
// Buys a virtual number — proxies to existing internal API

$user_id   = $GLOBALS['api_user_id'];
$country_id = trim($_GET['country_id'] ?? '');
$service_id = trim($_GET['service_id'] ?? '');
$operator   = trim($_GET['operator'] ?? '');

if (empty($country_id) || empty($service_id)) {
    api_response(['status' => 'error', 'message' => 'Missing country_id or service_id.'], 400);
}

// Reuse the internal buynumber logic by calling it internally
$_GET['server']   = $country_id;
$_GET['service']  = $service_id;
$_GET['token']    = (string)$user_id;  // internal token = user_id
$_GET['operator'] = $operator;

// Capture the internal API output
ob_start();
require __DIR__ . '/../../service/buynumber.php';
$output = ob_get_clean();

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

if ($data['status'] === '200') {
    // Parse: ACCESS_NUMBER:order_id:phone_number
    $parts = explode(':', $data['res'] ?? '', 3);
    api_response([
        'status'   => 'success',
        'order_id' => $parts[1] ?? '',
        'number'   => $parts[2] ?? '',
        'message'  => 'Number purchased successfully.',
    ]);
} else {
    api_response([
        'status'  => 'error',
        'message' => $data['message'] ?? 'Purchase failed.',
    ], 400);
}
