<?php
// POST action=electricity_buy&api_key=KEY&disco=IKEDC&meter_no=12345&amount=5000&phone=080...&type=prepaid
// Buy electricity token

$user_id  = $GLOBALS['api_user_id'];
$disco    = strtoupper(trim($_POST['disco'] ?? $_GET['disco'] ?? ''));
$meter_no = trim($_POST['meter_no'] ?? $_GET['meter_no'] ?? '');
$amount   = (float)($_POST['amount'] ?? $_GET['amount'] ?? 0);
$phone    = trim($_POST['phone'] ?? $_GET['phone'] ?? '');
$type     = strtolower(trim($_POST['type'] ?? $_GET['type'] ?? 'prepaid'));

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

$valid_discos = ['IKEDC', 'EKEDC', 'AEDC', 'KEDCO', 'PHED', 'JED', 'IBEDC', 'KAEDCO', 'BEDC'];
if (!in_array($disco, $valid_discos)) {
    api_response(['status' => 'error', 'message' => 'Invalid disco. Use: ' . implode(', ', $valid_discos)], 400);
}

$_POST['action']       = 'buy_electricity';
$_POST['disco']        = $disco;
$_POST['meter_no']     = $meter_no;
$_POST['amount']       = $amount;
$_POST['phone_number'] = $phone;
$_POST['meter_type']   = $type;

$_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'] ?? 'Electricity token purchased.',
        'token'   => $data['token'] ?? null,
        'meter'   => $meter_no,
        'amount'  => $amount,
    ]);
} else {
    api_response(['status' => 'error', 'message' => $data['msg'] ?? 'Purchase failed.'], 400);
}
