#!/usr/bin/env php
<?php
/**
 * Backfill sub_id and subscription_url for existing orders (optional).
 *
 * Usage:
 *   php install/migrate_xui_v3.php --server-id=1 [--dry-run]
 *
 * BACKUP FIRST — see MIGRATION_XUI_V3.md
 */
if (php_sapi_name() !== 'cli') {
    exit(1);
}

$root = dirname(__DIR__);
require_once $root . '/baseInfo.php';
require_once $root . '/config.php';

$opts = getopt('', ['server-id:', 'dry-run']);
$serverId = isset($opts['server-id']) ? (int) $opts['server-id'] : 0;
$dryRun = isset($opts['dry-run']);

if ($serverId <= 0) {
    fwrite(STDERR, "Usage: php install/migrate_xui_v3.php --server-id=1 [--dry-run]\n");
    exit(1);
}

if (!isXuiPanel($serverId)) {
    fwrite(STDERR, "Server $serverId is not type sanaei (3x-ui v3).\n");
    exit(1);
}

$service = getXuiV3Service($serverId);
$stmt = $connection->prepare("SELECT id, remark, sub_id, subscription_url FROM orders_list WHERE server_id = ? AND status = 1");
$stmt->bind_param('i', $serverId);
$stmt->execute();
$result = $stmt->get_result();
$updated = 0;

while ($row = $result->fetch_assoc()) {
    if (!empty($row['sub_id']) && !empty($row['subscription_url'])) {
        continue;
    }
    $subId = $service->getClientSubId($row['remark']);
    if ($subId === null) {
        echo "SKIP order #{$row['id']} — client not found on panel ({$row['remark']})\n";
        continue;
    }
    $subUrl = $service->buildSubscriptionUrl($subId);
    echo ($dryRun ? '[DRY] ' : '') . "Order #{$row['id']}: sub_id=$subId\n";
    if (!$dryRun) {
        $u = $connection->prepare("UPDATE orders_list SET sub_id = ?, subscription_url = ?, link = ? WHERE id = ?");
        $linkJson = json_encode([$subUrl]);
        $u->bind_param('sssi', $subId, $subUrl, $linkJson, $row['id']);
        $u->execute();
        $u->close();
    }
    $updated++;
}
$stmt->close();

echo "Done. Updated $updated order(s).\n";
