// 云验证 · Android 示例
// 请在 AndroidManifest.xml 中声明网络权限：
// <uses-permission android:name="android.permission.INTERNET" />

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

public final class CloudVerify {

    // 替换成你在后台「我的应用」页面中的信息
    private static final String API_KEY = "pk_请替换成你的APIKey";
    private static final String API_URL = "https://你的域名/api/verify.php";

    private CloudVerify() {
    }

    /**
     * 验证卡密，成功会扣减 1 次。
     * 必须在子线程中调用（Android 不允许主线程发起网络请求）。
     */
    public static JSONObject verify(String card, String deviceId) throws Exception {
        URL url = new URL(API_URL);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        try {
            conn.setRequestMethod("POST");
            conn.setConnectTimeout(8000);
            conn.setReadTimeout(8000);
            conn.setDoOutput(true);
            conn.setRequestProperty("Content-Type", "application/json");

            JSONObject payload = new JSONObject();
            payload.put("key", API_KEY);
            payload.put("card", card);
            payload.put("device", deviceId);

            try (OutputStream out = conn.getOutputStream()) {
                out.write(payload.toString().getBytes(StandardCharsets.UTF_8));
            }

            int status = conn.getResponseCode();
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    (status >= 200 && status < 300) ? conn.getInputStream() : conn.getErrorStream(),
                    StandardCharsets.UTF_8));

            StringBuilder body = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                body.append(line);
            }
            reader.close();

            return new JSONObject(body.toString());
        } finally {
            conn.disconnect();
        }
    }
}

// ---------------- 调用示例 ----------------
// String deviceId = Settings.Secure.getString(
//         getContentResolver(), Settings.Secure.ANDROID_ID);
//
// new Thread(() -> {
//     try {
//         JSONObject result = CloudVerify.verify(card, deviceId);
//         if (result.optBoolean("ok")) {
//             int remaining = result.getJSONObject("data").optInt("remaining");
//             runOnUiThread(() -> Toast.makeText(this,
//                     "验证成功，剩余 " + remaining + " 次", Toast.LENGTH_SHORT).show());
//         } else {
//             String msg = result.optString("msg", "验证失败");
//             runOnUiThread(() -> Toast.makeText(this, msg, Toast.LENGTH_SHORT).show());
//         }
//     } catch (Exception e) {
//         e.printStackTrace();
//     }
// }).start();
