<?php
require_once __DIR__ . '/functions.php';
try {
    $invoice = clean_value($_GET['invoice'] ?? $_POST['invoice'] ?? '', 80);
    $paymentID = clean_value($_GET['paymentID'] ?? $_POST['paymentID'] ?? '', 160);
    $status = strtolower(clean_value($_GET['status'] ?? $_POST['status'] ?? '', 40));

    if ($invoice) {
        $txn = db_get_txn($invoice);
    } elseif ($paymentID) {
        $txn = db_get_txn_by_payment_id($paymentID);
        $invoice = (string)($txn['invoice'] ?? '');
    } else {
        throw new Exception('paymentID missing');
    }
    if (!$txn || !$invoice) throw new Exception('Payment record not found');

    if (($txn['status'] ?? '') === 'paid') {
        echo auto_login_html($txn['login_url'], $txn['dst'], $txn['token'], $txn['token']);
        exit;
    }

    if ($status !== 'success' || !$paymentID) {
        db_mark_failed($invoice, 'Payment status: ' . $status, ['query' => $_GET, 'post' => $_POST]);
        throw new Exception('Payment not success: ' . ($status ?: 'empty'));
    }

    $exec = bkash_execute_payment($paymentID);
    $trxId = clean_value($exec['trxID'] ?? '', 120);
    $amount = (float)($exec['amount'] ?? 0);
    $transactionStatus = strtolower((string)($exec['transactionStatus'] ?? ''));

    if (!$trxId || $transactionStatus !== 'completed') {
        db_mark_failed($invoice, 'bKash execute not completed', $exec);
        throw new Exception('bKash execute not completed: ' . json_encode($exec, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
    }
    if (round($amount, 2) !== round((float)$txn['amount'], 2)) {
        db_mark_failed($invoice, 'Amount mismatch', $exec);
        throw new Exception('Amount mismatch');
    }
    if (db_trx_exists($trxId, $invoice)) throw new Exception('Duplicate trx blocked');

    // Token/user/password must be the bKash trxID. Example: DE50TT5OJ4
    $token = $trxId;

    // Comment must be ONLY the expiry datetime, counted by hour from payment success time.
    $expiry = date('Y-m-d H:i:s', time() + ((int)$txn['days'] * 24 * 60 * 60));
    $comment = $expiry;

    mikrotik_upsert_hotspot_user($token, $token, $txn['profile'], $comment);
    db_mark_paid($invoice, $paymentID, $trxId, $token, $exec);

    echo auto_login_html($txn['login_url'], $txn['dst'], $token, $token);
} catch (Throwable $e) {
    error_page('Payment failed', $e->getMessage());
}
