<?php
require_once __DIR__ . '/functions.php';
global $PACKAGES;
try {
    $pkgKey = clean_value($_GET['package'] ?? '', 30);
    if (!isset($PACKAGES[$pkgKey])) throw new Exception('Invalid package');
    $pkg = $PACKAGES[$pkgKey];

    $invoice = new_invoice();
    $loginUrl = clean_value($_GET['login_url'] ?? '', 500);
    if (!$loginUrl || strpos($loginUrl, '$(') !== false) {
        throw new Exception('Open this page from MikroTik hotspot, not local computer. Missing real login URL.');
    }

    db_insert_txn([
        'invoice' => $invoice,
        'username' => 'hotspot',
        'package_key' => $pkgKey,
        'package_label' => $pkg['label'] ?? $pkgKey,
        'amount' => (float)$pkg['amount'],
        'profile' => $pkg['profile'],
        'days' => (int)$pkg['days'],
        'mac' => clean_value($_GET['mac'] ?? '', 80),
        'ip' => clean_value($_GET['ip'] ?? '', 80),
        'login_url' => $loginUrl,
        'dst' => clean_value($_GET['dst'] ?? '', 500),
    ]);

    $created = bkash_create_payment($invoice, (float)$pkg['amount']);
    db_mark_payment_created($invoice, (string)$created['paymentID'], $created);

    echo bkash_redirect_html($created['bkashURL']);
    exit;
} catch (Throwable $e) {
    if (!empty($invoice)) {
        try { db_mark_failed($invoice, $e->getMessage()); } catch (Throwable $ignore) {}
    }
    error_page('Payment start failed', $e->getMessage());
}
