<?php
//Developer: core tech web design
//Whatsapp: +234 9162671360
//Telegram: @jeditech

error_reporting(E_ERROR | E_PARSE); // log fatal errors but not notices/warnings that corrupt JSON
define('FIVESIM_LOG', dirname(__DIR__) . '/ajax/error_log'); // write to the app's own log

function fs_log(string $msg): void {
    error_log('[' . date('d-M-Y H:i:s') . ' UTC] ' . $msg . "\n", 3, FIVESIM_LOG);
}
ob_start();
require_once dirname(__DIR__) . '/include/config.php';
require_once dirname(__DIR__) . '/include/FiveSim.php';

ob_clean();
header('Content-Type: application/json; charset=utf-8');

// Auth: load user from session (same pattern as user/header.php)
if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true || empty($_SESSION['user_id'])) {
    echo json_encode(['status' => '0', 'msg' => 'Not authenticated.']); exit();
}
$user = null;
try {
    $stmt = $pdo->prepare("SELECT id, main_balance FROM users WHERE id = :uid AND status = '1' LIMIT 1");
    $stmt->execute([':uid' => (int)$_SESSION['user_id']]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
} catch (PDOException $e) {}
if (!$user || empty($user['id'])) {
    echo json_encode(['status' => '0', 'msg' => 'Not authenticated.']); exit();
}

$user_id  = (int)$user['id'];
$action   = trim($_POST['action'] ?? $_GET['action'] ?? '');

// Load 5SIM credentials fresh from settings (fivesim columns added later)
$token    = '';
$base_url = 'https://5sim.net/v1';
$markup   = 35.0;
try {
    $fs = $pdo->query("SELECT fivesim_api_token, fivesim_api_url, fivesim_markup FROM settings WHERE id=1")->fetch(PDO::FETCH_ASSOC);
    if ($fs) {
        $token    = trim($fs['fivesim_api_token'] ?? '');
        $base_url = !empty($fs['fivesim_api_url']) ? $fs['fivesim_api_url'] : 'https://5sim.net/v1';
        $markup   = (float)($fs['fivesim_markup'] ?? 35);
    }
} catch (PDOException $e) {}

// Also try price_settings for usd_to_ngn (same as smsman)
$usd_ngn  = 1600.0;
try {
    $r2 = $pdo->query("SELECT setting_value FROM price_settings WHERE setting_key='usd_to_ngn' LIMIT 1")->fetch(PDO::FETCH_ASSOC);
    if ($r2 && (float)$r2['setting_value'] > 0) $usd_ngn = (float)$r2['setting_value'];
} catch (Exception $e) {}

if (empty($token)) {
    echo json_encode(['status' => '0', 'msg' => 'Service temporarily unavailable. Please try again later.']); exit();
}

$api = new FiveSim($token, $base_url);

// â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€
// get_countries â€” load all synced countries for the dropdown
// â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€
if ($action === 'get_countries') {
    try {
        $rows = $pdo->query(
            "SELECT country_key, title FROM fivesim_countries ORDER BY title ASC"
        )->fetchAll(PDO::FETCH_ASSOC);
        echo json_encode(['status' => '1', 'countries' => $rows]);
    } catch (PDOException $e) {
        echo json_encode(['status' => '0', 'msg' => 'Database error: ' . $e->getMessage()]);
    }
    exit();
}

// â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€
// get_country_products â€” live products+prices for a chosen country
// â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€
if ($action === 'get_country_products') {
    $country_key = trim($_POST['country_key'] ?? '');
    if (empty($country_key)) {
        echo json_encode(['status' => '0', 'msg' => 'Missing country.']); exit();
    }

    // Try synced DB cache first; fall back to live API
    try {
        $rows = $pdo->prepare(
            "SELECT product, qty, cost_usd, our_price
               FROM fivesim_products
              WHERE country_key = :ckey AND category = 'activation' AND qty > 0
              ORDER BY product ASC"
        );
        $rows->execute(['ckey' => $country_key]);
        $cached = $rows->fetchAll(PDO::FETCH_ASSOC);

        if (!empty($cached)) {
            $products = [];
            foreach ($cached as $row) {
                // Recalculate our_price live with current exchange rate
                $our_price = round((float)$row['cost_usd'] * $usd_ngn * (1 + $markup / 100), 2);
                $products[$row['product']] = [
                    'qty'       => (int)$row['qty'],
                    'cost_usd'  => (float)$row['cost_usd'],
                    'our_price' => $our_price,
                ];
            }
            echo json_encode(['status' => '1', 'products' => $products, 'source' => 'cache']);
            exit();
        }
    } catch (PDOException $e) {
        // Fall through to live API
    }

    // Live API call
    $r = $api->getProducts($country_key, 'any');
    if (!$r['success']) {
        echo json_encode(['status' => '0', 'msg' => 'Could not load services. Please try again.']); exit();
    }

    $products = [];
    if (is_array($r['data'])) {
        foreach ($r['data'] as $product => $info) {
            if (!is_array($info)) continue;
            $cat = strtolower($info['Category'] ?? 'activation');
            if ($cat !== 'activation') continue;
            $qty      = (int)($info['Qty']   ?? 0);
            $cost_usd = (float)($info['Price'] ?? 0);
            if ($cost_usd <= 0) continue;

            $our_price = round($cost_usd * $usd_ngn * (1 + $markup / 100), 2);
            $products[(string)$product] = [
                'qty'       => $qty,
                'cost_usd'  => $cost_usd,
                'our_price' => $our_price,
            ];
        }
    }

    echo json_encode(['status' => '1', 'products' => $products, 'source' => 'live']);
    exit();
}

// â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€
// buy_number â€” purchase & deduct balance
// â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€
if ($action === 'buy_number') {
    $country_key = trim($_POST['country_key'] ?? '');
    $product     = trim($_POST['product']     ?? '');

    if (empty($country_key) || empty($product)) {
        echo json_encode(['status' => '0', 'msg' => 'Invalid parameters.']); exit();
    }

    // Recalculate price server-side from live API
    $r_price = $api->getProducts($country_key, 'any');
    if (!$r_price['success'] || !isset($r_price['data'][$product])) {
        echo json_encode(['status' => '0', 'msg' => 'Product not available in this country right now.']); exit();
    }
    $info      = $r_price['data'][$product];
    $cost_usd  = (float)($info['Price'] ?? 0);
    $qty       = (int)($info['Qty']   ?? 0);

    if ($cost_usd <= 0 || $qty <= 0) {
        echo json_encode(['status' => '0', 'msg' => 'Service not available in this country right now.']); exit();
    }

    $our_price = round($cost_usd * $usd_ngn * (1 + $markup / 100), 2);

    // Check user balance
    $u = $pdo->prepare("SELECT main_balance FROM users WHERE id = :id");
    $u->execute(['id' => $user_id]);
    $balance = (float)$u->fetchColumn();

    if ($balance < $our_price) {
        echo json_encode(['status' => '0', 'msg' => 'Insufficient balance. Please fund your wallet.']); exit();
    }

    // Country display name
    $cr = $pdo->prepare("SELECT title FROM fivesim_countries WHERE country_key = :ckey");
    $cr->execute(['ckey' => $country_key]);
    $country_name = $cr->fetchColumn() ?: ucfirst($country_key);

    // Buy from 5SIM
    $result = $api->buyNumber($country_key, $product);

    // Log the raw response for debugging
    fs_log('[5SIM buy] country=' . $country_key . ' product=' . $product .
              ' success=' . ($result['success'] ? 'true' : 'false') .
              ' http=' . ($result['http_code'] ?? '?') .
              ' error=' . ($result['error'] ?? '') .
              ' data=' . json_encode($result['data'] ?? null));

    if (!$result['success']) {
        echo json_encode(['status' => '0', 'msg' => 'Unable to get number. Please try again.']); exit();
    }

    $data      = $result['data'];
    $order_id5 = isset($data['id']) ? (string)(int)$data['id'] : '0'; // keep as large int string
    // On 64-bit PHP, cast to int safely; use raw value for DB
    $order_id5_int = PHP_INT_SIZE >= 8 ? (int)$data['id'] : (float)$data['id'];
    $phone     = (string)($data['phone'] ?? '');
    $operator  = (string)($data['operator'] ?? 'any');
    $expires_at = date('Y-m-d H:i:s', strtotime('+5 minutes'));

    fs_log('[5SIM buy] parsed: order_id5=' . $order_id5_int . ' phone=' . $phone . ' expires=' . $expires_at);

    if (!$order_id5_int || !$phone) {
        // Cancel the order at 5SIM since we can't save it
        if (!empty($data['id'])) {
            $api->cancelOrder((int)$data['id']);
            fs_log('[5SIM buy] cancelled order ' . $data['id'] . ' â€” no phone/id in response. Raw data: ' . json_encode($data));
        }
        echo json_encode(['status' => '0', 'msg' => 'Could not fetch number. Please try again.']); exit();
    }

    // Ensure orders table exists
    try {
        $pdo->exec("CREATE TABLE IF NOT EXISTS fivesim_orders (
            id           INT AUTO_INCREMENT PRIMARY KEY,
            user_id      INT           NOT NULL,
            order_id5    BIGINT        NOT NULL UNIQUE,
            phone        VARCHAR(30)   NOT NULL,
            country_key  VARCHAR(100)  NOT NULL,
            country_name VARCHAR(150)  NOT NULL DEFAULT '',
            product      VARCHAR(150)  NOT NULL,
            operator     VARCHAR(100)  NOT NULL DEFAULT 'any',
            cost_usd     FLOAT         NOT NULL DEFAULT 0,
            our_price    DECIMAL(12,2) NOT NULL DEFAULT 0,
            status       VARCHAR(30)   NOT NULL DEFAULT 'waiting',
            sms_code     VARCHAR(50)   NOT NULL DEFAULT '',
            sms_text     TEXT,
            expires_at   DATETIME,
            received_at  DATETIME,
            created_at   TIMESTAMP     NOT NULL DEFAULT CURRENT_TIMESTAMP
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
        // Ensure BIGINT on existing tables (safe on re-run)
        $pdo->exec("ALTER TABLE fivesim_orders MODIFY COLUMN order_id5 BIGINT NOT NULL");
    } catch (PDOException $e) {}

    try {
        $pdo->beginTransaction();

        $upd = $pdo->prepare(
            "UPDATE users SET main_balance = main_balance - :amt WHERE id = :id AND main_balance >= :amt2"
        );
        $upd->execute(['amt' => $our_price, 'id' => $user_id, 'amt2' => $our_price]);

        if ($upd->rowCount() === 0) {
            $pdo->rollBack();
            echo json_encode(['status' => '0', 'msg' => 'Balance changed. Please retry.']); exit();
        }

        $ins = $pdo->prepare(
            "INSERT INTO fivesim_orders
             (user_id, order_id5, phone, country_key, country_name, product, operator, cost_usd, our_price, status, expires_at)
             VALUES (:uid,:oid5,:phone,:ckey,:cname,:prod,:op,:cusd,:oprice,'waiting',:exp)"
        );
        $ins->execute([
            'uid'    => $user_id,
            'oid5'   => $order_id5_int,
            'phone'  => $phone,
            'ckey'   => $country_key,
            'cname'  => $country_name,
            'prod'   => $product,
            'op'     => $operator,
            'cusd'   => $cost_usd,
            'oprice' => $our_price,
            'exp'    => $expires_at,
        ]);
        $local_order_id = (int)$pdo->lastInsertId();

        $txn_ref = 'FS_' . strtoupper(substr(md5(uniqid()), 0, 12));
        $pdo->prepare(
            "INSERT INTO transactions (user_id, transaction_ref, payment_gateway, transaction_type, amount, currency, status, metadata)
             VALUES (:uid, :ref, 'virtual_number', 'number_purchase', :amt, 'NGN', 'successful', :meta)"
        )->execute([
            'uid'  => $user_id,
            'ref'  => $txn_ref,
            'amt'  => $our_price,
            'meta' => json_encode(['product' => $product, 'country' => $country_name, 'phone' => $phone, 'order_id5' => $order_id5_int]),
        ]);

        $pdo->commit();

        fs_log('[5SIM buy] SUCCESS — local_order_id=' . $local_order_id . ' order_id5=' . $order_id5_int . ' phone=' . $phone . ' product=' . $product . ' user=' . $user_id);

        echo json_encode([
            'status'      => '1',
            'msg'         => 'Number purchased!',
            'order_id'    => $local_order_id,
            'order_id5'   => $order_id5_int,
            'phone'       => $phone,
            'expires_at'  => $expires_at,
            'new_balance' => number_format($balance - $our_price, 2),
        ]);

    } catch (Exception $e) {
        if ($pdo->inTransaction()) $pdo->rollBack();
        if ($order_id5_int > 0) {
            $api->cancelOrder($order_id5_int);
            fs_log('[5SIM] DB error after buyNumber â€” cancelled order ' . $order_id5_int . ': ' . $e->getMessage());
            echo json_encode(['status' => '0', 'msg' => 'Database error. Your number has been cancelled and balance was not charged.']);
        } else {
            fs_log('[5SIM] DB error before buyNumber: ' . $e->getMessage());
            echo json_encode(['status' => '0', 'msg' => 'Database error. Please try again.']);
        }
    }
    exit();
}

// â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€
// check_sms â€” poll 5SIM for OTP
// â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€
if ($action === 'check_sms') {
    $order_id = (int)($_POST['order_id'] ?? 0);

    $ord = $pdo->prepare("SELECT * FROM fivesim_orders WHERE id=:id AND user_id=:uid");
    $ord->execute(['id' => $order_id, 'uid' => $user_id]);
    $row = $ord->fetch(PDO::FETCH_ASSOC);

    if (!$row) {
        echo json_encode(['status' => '0', 'msg' => 'Order not found.']); exit();
    }
    if ($row['status'] === 'received') {
        echo json_encode(['status' => '1', 'sms_code' => $row['sms_code'], 'sms_text' => $row['sms_text']]); exit();
    }
    if (in_array($row['status'], ['cancelled', 'banned', 'timeout'], true)) {
        echo json_encode(['status' => '0', 'msg' => 'Order was ' . $row['status'] . '.']); exit();
    }
    if (!empty($row['expires_at']) && strtotime($row['expires_at']) < time()) {
        $pdo->prepare("UPDATE fivesim_orders SET status='timeout' WHERE id=:id")->execute(['id' => $order_id]);
        echo json_encode(['status' => '0', 'msg' => 'Number expired.']); exit();
    }

    $r = $api->checkOrder((int)$row['order_id5']);

    if (!$r['success']) {
        echo json_encode(['status' => 'waiting', 'msg' => 'Waiting for SMS...']); exit();
    }

    $data   = $r['data'];
    $status = strtoupper($data['status'] ?? '');
    $sms    = $data['sms'] ?? [];

    // Log what we got for debugging
    fs_log('[5SIM poll] order_id=' . $order_id . ' order_id5=' . $row['order_id5'] . ' status=' . $status . ' sms_count=' . count($sms));

    // 5SIM status: PENDING=waiting, RECEIVED=sms arrived, CANCELED/TIMEOUT/BANNED=done
    if (($status === 'RECEIVED' || !empty($sms)) && is_array($sms) && count($sms) > 0) {
        $last     = end($sms);
        $sms_text = (string)($last['text'] ?? '');
        $sms_code = (string)($last['code'] ?? '');

        // Extract code from text if code field is empty
        if (empty($sms_code) && !empty($sms_text)) {
            if (preg_match_all('/\b(\d{4,8})\b/', $sms_text, $m)) {
                $sms_code = end($m[1]);
            }
        }

        fs_log('[5SIM poll] SMS received! code=' . $sms_code . ' text=' . substr($sms_text, 0, 60));

        $pdo->prepare(
            "UPDATE fivesim_orders SET status='received', sms_code=:code, sms_text=:txt, received_at=NOW() WHERE id=:id"
        )->execute(['code' => $sms_code, 'txt' => $sms_text, 'id' => $order_id]);

        echo json_encode(['status' => '1', 'sms_code' => $sms_code, 'sms_text' => $sms_text]);

    } elseif (in_array($status, ['CANCELED', 'TIMEOUT', 'BANNED'], true)) {
        $new_status = strtolower($status);
        $pdo->prepare("UPDATE fivesim_orders SET status=:s WHERE id=:id")->execute(['s' => $new_status, 'id' => $order_id]);

        // Auto-refund user when 5SIM cancels/times out the order
        $pdo->prepare("UPDATE users SET main_balance = main_balance + :amt WHERE id=:uid")
            ->execute(['amt' => $row['our_price'], 'uid' => $user_id]);
        $refund_ref = 'FSAUTO_' . strtoupper(substr(md5(uniqid()), 0, 8));
        $pdo->prepare("INSERT INTO transactions (user_id, transaction_ref, payment_gateway, transaction_type, amount, currency, status, metadata) VALUES (:uid,:ref,'virtual_number','refund',:amt,'NGN','successful',:meta)")
            ->execute(['uid' => $user_id, 'ref' => $refund_ref, 'amt' => $row['our_price'],
                       'meta' => json_encode(['reason' => 'Auto-refund: number expired', 'order_id5' => $row['order_id5']])]);

        $nb = $pdo->prepare("SELECT main_balance FROM users WHERE id=:uid");
        $nb->execute(['uid' => $user_id]);
        fs_log('[5SIM poll] Auto-refund: order_id=' . $order_id . ' status=' . $status . ' amount=' . $row['our_price']);

        echo json_encode([
            'status'      => '0',
            'msg'         => 'Number ' . $status . '. ₦' . number_format($row['our_price'], 2) . ' refunded to your wallet.',
            'refunded'    => true,
            'new_balance' => number_format((float)$nb->fetchColumn(), 2),
        ]);

    } else {
        echo json_encode(['status' => 'waiting', 'msg' => 'Waiting for SMS...']);
    }
    exit();
}

// â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€
// cancel_number â€” cancel + refund
// â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€
if ($action === 'cancel_number') {
    $order_id = (int)($_POST['order_id'] ?? 0);

    $ord = $pdo->prepare("SELECT * FROM fivesim_orders WHERE id=:id AND user_id=:uid");
    $ord->execute(['id' => $order_id, 'uid' => $user_id]);
    $row = $ord->fetch(PDO::FETCH_ASSOC);

    if (!$row) {
        echo json_encode(['status' => '0', 'msg' => 'Order not found.']); exit();
    }
    if ($row['status'] !== 'waiting') {
        echo json_encode(['status' => '0', 'msg' => 'Can only cancel numbers still waiting for SMS.']); exit();
    }

    $r = $api->cancelOrder((int)$row['order_id5']);
    fs_log('[5SIM cancel] order_id=' . $order_id . ' order_id5=' . $row['order_id5'] . ' api_success=' . ($r['success'] ? 'true' : 'false') . ' http=' . ($r['http_code'] ?? '?') . ' error=' . ($r['error'] ?? ''));

    // Refund and update local DB even if 5SIM returns an error
    // (order may have already expired/closed at 5SIM side)
    $pdo->prepare("UPDATE users SET main_balance = main_balance + :amt WHERE id=:uid")
        ->execute(['amt' => $row['our_price'], 'uid' => $user_id]);
    $pdo->prepare("UPDATE fivesim_orders SET status='cancelled' WHERE id=:id")
        ->execute(['id' => $order_id]);
    $refund_ref = 'FSREF_' . strtoupper(substr(md5(uniqid()), 0, 10));
    $pdo->prepare("INSERT INTO transactions (user_id, transaction_ref, payment_gateway, transaction_type, amount, currency, status, metadata) VALUES (:uid,:ref,'virtual_number','refund',:amt,'NGN','successful',:meta)")
        ->execute(['uid' => $user_id, 'ref' => $refund_ref, 'amt' => $row['our_price'], 'meta' => json_encode(['reason' => 'Number cancelled', 'order_id5' => $row['order_id5']])]);

    $nb = $pdo->prepare("SELECT main_balance FROM users WHERE id=:uid");
    $nb->execute(['uid' => $user_id]);
    echo json_encode([
        'status'      => '1',
        'msg'         => '&#8358;' . number_format($row['our_price'], 2) . ' refunded to your wallet.',
        'new_balance' => number_format((float)$nb->fetchColumn(), 2),
    ]);
    exit();
}

// â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€
// finish_number â€” mark complete, no refund
// â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€
if ($action === 'finish_number') {
    $order_id = (int)($_POST['order_id'] ?? 0);

    $ord = $pdo->prepare("SELECT * FROM fivesim_orders WHERE id=:id AND user_id=:uid");
    $ord->execute(['id' => $order_id, 'uid' => $user_id]);
    $row = $ord->fetch(PDO::FETCH_ASSOC);

    if (!$row) {
        echo json_encode(['status' => '0', 'msg' => 'Order not found.']); exit();
    }

    $api->finishOrder((int)$row['order_id5']);
    $pdo->prepare("UPDATE fivesim_orders SET status='finished' WHERE id=:id")->execute(['id' => $order_id]);
    echo json_encode(['status' => '1', 'msg' => 'Number released. Thank you!']);
    exit();
}

// â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€
// get_active_orders â€” waiting/received orders on page load
// â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€â”€
if ($action === 'get_active_orders') {
    try {
        $rows = $pdo->prepare(
            "SELECT * FROM fivesim_orders WHERE user_id=:uid AND status = 'waiting' ORDER BY created_at DESC"
        );
        $rows->execute(['uid' => $user_id]);
        echo json_encode(['status' => '1', 'orders' => $rows->fetchAll(PDO::FETCH_ASSOC)]);
    } catch (PDOException $e) {
        echo json_encode(['status' => '1', 'orders' => []]);
    }
    exit();
}

echo json_encode(['status' => '0', 'msg' => 'Unknown action.']);
