<?php
require_once 'admin_sold_credentials_common.php';
try {
    $input = sold_read_input();
    $adminId = sold_require_admin($input);
    vpnEnsureColumns($pdo);

    $deliveryId = (int)($input['delivery_id'] ?? 0);
    $credentialId = (int)($input['credential_id'] ?? 0);
    $confirm = (string)($input['confirm'] ?? '') === '1';
    if (!$confirm) sold_json_error('برای برگشت به موجودی، confirm=1 الزامی است');
    if ($deliveryId <= 0 && $credentialId <= 0) sold_json_error('delivery_id یا credential_id الزامی است');

    $pdo->beginTransaction();
    $delivery = sold_find_delivery_for_update($pdo, $deliveryId, $credentialId);
    if (!$delivery) { $pdo->rollBack(); sold_json_error('تحویل/اشتراک پیدا نشد'); }
    if (strtolower((string)$delivery['status']) === 'reverted') {
        $pdo->rollBack(); sold_json_error('این اشتراک قبلاً به موجودی برگشته است');
    }
    $old = $delivery;

    if (!empty($delivery['credential_id'])) {
        $st = $pdo->prepare("SELECT * FROM credentials WHERE id=? FOR UPDATE");
        $st->execute([(int)$delivery['credential_id']]);
        $cred = $st->fetch(PDO::FETCH_ASSOC);
        if (!$cred) { $pdo->rollBack(); sold_json_error('credential اصلی پیدا نشد'); }

        $pdo->prepare("UPDATE credentials
            SET used_seats=0,
                is_sold=0,
                status='available',
                is_active=1,
                sold_to_user_id=NULL,
                order_id=NULL,
                assigned_user_id=NULL,
                assigned_order_id=NULL,
                sold_at=NULL,
                delivered_at=NULL,
                first_connected_at=NULL,
                expires_at=NULL,
                updated_at=NOW()
            WHERE id=?")->execute([(int)$delivery['credential_id']]);
    }

    $pdo->prepare("UPDATE deliveries SET status='reverted' WHERE id=?")->execute([(int)$delivery['id']]);
    sold_refresh_order_after_delivery_change($pdo, (int)$delivery['order_id'], 'REVERTED');

    sold_admin_log($pdo, $adminId, 'sold_credential_restore_to_inventory', [
        'target_id' => (int)$delivery['id'],
        'old' => $old,
        'new' => ['delivery_status' => 'reverted', 'credential_status' => 'available', 'is_sold' => 0, 'used_seats' => 0],
    ]);
    $pdo->commit();
    gemaccAdminActionNotify('اشتراک فروخته‌شده به موجودی برگشت', ['شناسه تحویل'=>(int)$delivery['id'], 'شناسه سفارش'=>(int)$delivery['order_id'], 'شناسه اشتراک'=>(int)($delivery['credential_id'] ?? 0)], $adminId);
    sold_json_ok(['delivery_id' => (int)$delivery['id'], 'credential_id' => (int)($delivery['credential_id'] ?? 0), 'order_id' => (int)$delivery['order_id']], 'اشتراک به موجودی قابل فروش برگشت');
} catch (Throwable $e) {
    if (isset($pdo) && $pdo instanceof PDO && $pdo->inTransaction()) $pdo->rollBack();
    vpnLogEvent('admin_sold_credential_restore_failed', ['error' => $e->getMessage()]);
    sold_json_error('خطای سرور: ' . $e->getMessage());
}
