<?php
// POST action=vtu_buy_data&api_key=KEY&plan_id=ID&phone=08012345678
// Buy a data plan

$user_id = $GLOBALS['api_user_id'];
$plan_id = (int)($_POST['plan_id'] ?? $_GET['plan_id'] ?? 0);
$phone   = trim($_POST['phone'] ?? $_GET['phone'] ?? '');

if (!$plan_id || empty($phone)) {
    api_response(['status' => 'error', 'message' => 'Missing plan_id or phone.'], 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 via the existing handler
$_POST['action']  = 'buy_data';
$_POST['plan_id'] = $plan_id;
$_POST['phone']   = $phone;

// Set session for the internal handler
$_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'] ?? 'Data purchased successfully.',
        'phone'   => $phone,
        'plan_id' => $plan_id,
    ]);
} else {
    api_response([
        'status'  => 'error',
        'message' => $data['msg'] ?? 'Purchase failed.',
    ], 400);
}
