package com.arvindcodex.codexvertex;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.service.notification.NotificationListenerService;
import android.service.notification.StatusBarNotification;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.os.Build;
import android.content.pm.ServiceInfo;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.json.JSONObject;

public class NotificationService extends NotificationListenerService {

    private static final String TAG = "CodexVertex_Listener";
    private static final String API_URL = "https://payment.winto.in/backend/payment.php";
    private static final String CHANNEL_ID = "CodexVertex_Service_Channel";

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        startMyForeground();
        return START_STICKY;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        createNotificationChannel();
        startMyForeground();
    }

    private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel serviceChannel = new NotificationChannel(
                    CHANNEL_ID,
                    "CodexVertex Background Service",
                    NotificationManager.IMPORTANCE_LOW);
            NotificationManager manager = getSystemService(NotificationManager.class);
            if (manager != null) {
                manager.createNotificationChannel(serviceChannel);
            }
        }
    }

    private void startMyForeground() {
        Intent notificationIntent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this,
                0, notificationIntent, PendingIntent.FLAG_IMMUTABLE);

        Notification.Builder builder;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            builder = new Notification.Builder(this, CHANNEL_ID);
        } else {
            builder = new Notification.Builder(this);
        }

        Notification notification = builder
                .setContentTitle("CodexVertex Active")
                .setContentText("Listening for UPI/Bank Notifications...")
                .setSmallIcon(android.R.drawable.ic_dialog_info)
                .setContentIntent(pendingIntent)
                .setOngoing(true)
                .build();

        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
                startForeground(1, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_REMOTE_MESSAGING);
            } else {
                startForeground(1, notification);
            }
        } catch (Exception e) {
            Log.e(TAG, "Foreground Error: " + e.getMessage());
        }
    }

    @Override
    public void onNotificationPosted(StatusBarNotification sbn) {
        String packageName = sbn.getPackageName();
        if (packageName == null)
            return;

        // Catch ALL messaging apps to be safe
        if (packageName.contains("sms") || packageName.contains("messaging") ||
                packageName.contains("mms") || packageName.contains("paisa") ||
                packageName.contains("phonepe") || packageName.contains("paytm")) {

            Log.d(TAG, "HIT: Notification from " + packageName);
            Bundle extras = sbn.getNotification().extras;
            String text = extras.getString(Notification.EXTRA_TEXT);

            if (text != null) {
                // AGGRESSIVE: Send ALL raw text to backend for debugging if needed
                sendToBackend(text, "RAW_LOG", "RAW");
                parseNotification(text);
            }
        }
    }

    private void parseNotification(String text) {
        try {
            Pattern amountPattern = Pattern.compile(
                    "(?:₹|Rs\\.?|INR|credited by|received|by)\\s?(\\d+(?:\\.\\d{1,2})?)", Pattern.CASE_INSENSITIVE);
            Pattern utrPattern = Pattern.compile("(?:Ref\\. no\\.|Ref No|UTR|Transaction ID)[:\\s]*(\\d{10,15})",
                    Pattern.CASE_INSENSITIVE);

            Matcher amountMatcher = amountPattern.matcher(text);
            Matcher utrMatcher = utrPattern.matcher(text);

            if (amountMatcher.find() && utrMatcher.find()) {
                String amountStr = amountMatcher.group(1);
                String utrStr = utrMatcher.group(1);
                sendToBackend(amountStr, utrStr, "SUCCESS");
            }
        } catch (Exception e) {
            Log.e(TAG, "Parse Error: " + e.getMessage());
        }
    }

    private void sendToBackend(final String amount, final String utr, final String type) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    URL url = new URL(API_URL);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("POST");
                    conn.setRequestProperty("Content-Type", "application/json; utf-8");
                    conn.setDoOutput(true);

                    JSONObject json = new JSONObject();
                    json.put("user_id", "cb45fb09-d585-407d-bb8b-bb494a551623");
                    json.put("amount", amount);
                    json.put("utr", utr);
                    json.put("log_type", type);

                    try (OutputStream os = conn.getOutputStream()) {
                        byte[] input = json.toString().getBytes("utf-8");
                        os.write(input, 0, input.length);
                    }

                    int code = conn.getResponseCode();
                    Log.d(TAG, "Backend Response Code: " + code);
                } catch (Exception e) {
                    Log.e(TAG, "Connect Error: " + e.getMessage());
                }
            }
        }).start();
    }
}
