<?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);
    $pair = trim((string)($input['username_password'] ?? $input['pair'] ?? ''));
    $username = sold_clean_text($input['username'] ?? '');
    $password = sold_clean_text($input['password'] ?? '');
    $updateCredential = (int)($input['update_credential'] ?? 1) === 1;
    if ($pair !== '' && strpos($pair, ':') !== false) {
        [$username, $password] = array_map('trim', explode(':', $pair, 2));
    }
    if ($username === '' || $password === '') sold_json_error('username و password الزامی است');
    if (!preg_match('/^[A-Za-z0-9_.@\-]{3,128}$/', $username)) sold_json_error('یوزرنیم نامعتبر است');
    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_id' => (int)$delivery['id'],
        'credential_id' => (int)($delivery['credential_id'] ?? 0),
        'username' => $delivery['username'],
        'password' => $delivery['password'],
        'delivery_status' => $delivery['status'],
        'credential_status' => $delivery['credential_status'] ?? null,
    ];

    $pdo->prepare("UPDATE deliveries SET username=?, password=? WHERE id=?")->execute([$username, $password, (int)$delivery['id']]);

    if ($updateCredential && !empty($delivery['credential_id'])) {
        // The delivery row is already linked to this credential and locked in the same transaction.
        // Updating the original credential keeps admin inventory views consistent with the immutable delivery snapshot.
        $pdo->prepare("UPDATE credentials SET email=?, username=?, password=?, updated_at=NOW() WHERE id=?")
            ->execute([$username, $username, $password, (int)$delivery['credential_id']]);
    }

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