<?php
// GET ?action=vtu_plans&api_key=KEY&network=MTN&type=data
// Returns VTU data plans for a network

$network = strtoupper(trim($_GET['network'] ?? ''));
$type    = strtolower(trim($_GET['type'] ?? 'data'));

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

$api_markup = $GLOBALS['api_markup'];

try {
    if ($type === 'data') {
        $stmt = $pdo->prepare(
            "SELECT id, network, plan_name, plan_code, price, validity
               FROM vtu_data_plans
              WHERE UPPER(network) = :net AND status = 1
              ORDER BY price ASC"
        );
        $stmt->execute([':net' => $network]);
    } else {
        // For airtime, just return supported networks
        api_response([
            'status'   => 'success',
            'networks' => ['MTN', 'GLO', 'AIRTEL', '9MOBILE'],
            'message'  => 'For airtime, use vtu_buy_airtime with network, phone, and amount.',
        ]);
        return;
    }

    $plans = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    api_response(['status' => 'error', 'message' => 'Database error.'], 500);
}

$result = [];
foreach ($plans as $p) {
    $price = (float)$p['price'];
    if ($api_markup > 0) {
        $price = round($price * (1 + $api_markup / 100), 2);
    }
    $result[] = [
        'plan_id'   => (int)$p['id'],
        'network'   => $p['network'],
        'name'      => $p['plan_name'],
        'price'     => number_format($price, 2, '.', ''),
        'validity'  => $p['validity'] ?? '',
    ];
}

api_response([
    'status' => 'success',
    'count'  => count($result),
    'plans'  => $result,
]);
