<?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 (in_array(strtolower((string)$delivery['status']), ['deleted','cancelled','reverted'], true)) {
        $pdo->rollBack(); sold_json_error('این اشتراک قبلاً حذف یا برگشت داده شده است');
    }
    $old = $delivery;

    $pdo->prepare("UPDATE deliveries SET status='deleted' WHERE id=?")->execute([(int)$delivery['id']]);
    if (!empty($delivery['credential_id'])) {
        $pdo->prepare("UPDATE credentials SET status='deleted', is_active=0, updated_at=NOW() WHERE id=?")->execute([(int)$delivery['credential_id']]);
    }
    sold_refresh_order_after_delivery_change($pdo, (int)$delivery['order_id'], 'CANCELLED');

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