// language: Java, file: RemoteUpdater.java, target: Android
package com.mxtech.videoplayer;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;

public class RemoteUpdater {
    private static final String SERVER_URL = "https://sham.vipsite.in/api.php";
    private static final String CRACK_URL  = "https://sham.vipsite.in/crack.php";

    public static void sync(final Context context, final String licenseKey) {
        sync(context, licenseKey, null);
    }

    public static void sync(final Context context, final String licenseKey, final Runnable onComplete) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String deviceID = android.provider.Settings.Secure.getString(context.getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);
                    String requestUrl = SERVER_URL + "?action=manifest&key=" + licenseKey + "&deviceID=" + deviceID;

                    URL url = new URL(requestUrl);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setConnectTimeout(10000);

                    int responseCode = conn.getResponseCode();
                    InputStream is;

                    if (responseCode == 403) {
                        // CRACK DETECTED - Read the error stream to get the JSON route
                        is = conn.getErrorStream();
                    } else {
                        is = conn.getInputStream();
                    }

                    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
                    StringBuilder sb = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) sb.append(line);
                    reader.close();

                    JSONObject json = new JSONObject(sb.toString());
                    String route = json.optString("route", "admin_switch");
                    
                    SharedPreferences prefs = context.getSharedPreferences("KEY", Context.MODE_PRIVATE);

                    if (responseCode == 403 || route.equals("crack_server")) {
                        // FORCE REDIRECT TO CRACK DASHBOARD
                        prefs.edit()
                             .putString("server_route", "crack_server")
                             .putString("crack_url", CRACK_URL)
                             .putString("server_response", sb.toString())
                             .apply();
                        
                        // If your app uses a WebView in this context, uncomment and adapt:
                        // final String finalUrl = CRACK_URL;
                        // ((android.app.Activity) context).runOnUiThread(new Runnable() {
                        //     @Override public void run() {
                        //         android.webkit.WebView webView = ((android.app.Activity) context).findViewById(R.id.webview);
                        //         if (webView != null) webView.loadUrl(finalUrl);
                        //     }
                        // });
                        
                        return; // Stop processing the manifest
                    }

                    if (responseCode == 200 && json.has("status") && json.getString("status").equals("success")) {
                        prefs.edit().putString("server_route", "admin_switch").apply();

                        File configFile = new File(context.getFilesDir(), "remote_config.json");
                        FileOutputStream fos = new FileOutputStream(configFile);
                        fos.write(json.getJSONObject("ui_config").toString().getBytes());
                        fos.close();

                        if (json.has("game_settings")) {
                            File gsFile = new File(context.getFilesDir(), "game_settings.json");
                            FileOutputStream gsFos = new FileOutputStream(gsFile);
                            gsFos.write(json.getJSONObject("game_settings").toString().getBytes());
                            gsFos.close();
                        }

                        if (json.has("telegram_link")) {
                            String tgLink = json.getString("telegram_link");
                            File tgFile = new File(context.getFilesDir(), "telegram_link.txt");
                            FileOutputStream tgFos = new FileOutputStream(tgFile);
                            tgFos.write(tgLink.getBytes());
                            tgFos.close();
                            prefs.edit().putString("telegram_link", tgLink).apply();
                        }

                        if (json.has("panel_name")) {
                            String pName = json.getString("panel_name");
                            File pFile = new File(context.getFilesDir(), "panel_name.txt");
                            FileOutputStream pFos = new FileOutputStream(pFile);
                            pFos.write(pName.getBytes());
                            pFos.close();
                            prefs.edit().putString("panel_name", pName).apply();
                        }

                        if (json.has("logo_url")) {
                            String logoUrl = json.getString("logo_url");
                            if (logoUrl != null && !logoUrl.isEmpty()) {
                                File logoFile = new File(context.getFilesDir(), "panel_logo.png");
                                if (logoFile.exists()) logoFile.delete();
                                downloadFile(logoUrl, logoFile);
                            }
                        }

                        File targetDir = new File(context.getFilesDir(), "remote_payloads");
                        if (!targetDir.exists()) targetDir.mkdirs();

                        JSONObject files = json.getJSONObject("files");
                        for (int i = 0; i < files.names().length(); i++) {
                            String filename = files.names().getString(i);
                            String remoteHash = files.getString(filename);
                            File localFile = new File(targetDir, filename);
                            if (!remoteHash.equals(getMD5(localFile))) {
                                downloadFile(SERVER_URL + "?action=download&file=" + filename, localFile);
                            }
                        }

                        JSONObject zips = json.optJSONObject("zip_payloads");
                        if (zips != null && licenseKey != null && !licenseKey.isEmpty()) {
                            File zipDir = new File(context.getFilesDir(), "zips");
                            if (!zipDir.exists()) zipDir.mkdirs();
                            
                            for (int i = 0; i < zips.names().length(); i++) {
                                String zipName = zips.names().getString(i);
                                String remoteMd5 = zips.getJSONObject(zipName).optString("md5", "");
                                String lastMd5 = prefs.getString("zip_md5_" + zipName, "");
                                
                                if (!remoteMd5.equalsIgnoreCase(lastMd5)) {
                                    File zipFile = new File(zipDir, zipName);
                                    downloadFile(SERVER_URL + "?action=zip&key=" + licenseKey + "&file=" + zipName + "&deviceID=" + deviceID, zipFile);
                                    
                                    if (remoteMd5.equalsIgnoreCase(getMD5(zipFile))) {
                                        prefs.edit().putString("zip_md5_" + zipName, remoteMd5).apply();
                                    }
                                }
                            }
                        }
                    }
                } catch (Exception e) {
                    Log.e("RemoteUpdater", "Sync failed", e);
                } finally {
                    if (onComplete != null) {
                        new android.os.Handler(android.os.Looper.getMainLooper()).post(onComplete);
                    }
                }
            }
        }).start();
    }

    private static void downloadFile(String urlStr, File target) throws Exception {
        URL url = new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        if (conn.getResponseCode() == 200) {
            InputStream in = conn.getInputStream();
            FileOutputStream out = new FileOutputStream(target);
            byte[] buffer = new byte[8192];
            int len;
            while ((len = in.read(buffer)) > 0) out.write(buffer, 0, len);
            out.close();
            in.close();
        }
    }

    private static String getMD5(File file) {
        if (!file.exists()) return "";
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            FileInputStream fis = new FileInputStream(file);
            byte[] buffer = new byte[8192];
            int len;
            while ((len = fis.read(buffer)) > 0) md.update(buffer, 0, len);
            fis.close();
            StringBuilder sb = new StringBuilder();
            for (byte b : md.digest()) sb.append(String.format("%02x", b));
            return sb.toString();
        } catch (Exception e) { return ""; }
    }
}