package com.gramiatechnologies.gramia import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import okhttp3.Call import okhttp3.Callback import okhttp3.FormBody import okhttp3.OkHttpClient import okhttp3.Request import android.util.Log import androidx.work.Worker import androidx.work.WorkerParameters import androidx.work.impl.utils.ForceStopRunnable import okhttp3.* import org.json.JSONObject import java.io.IOException class NotificationClickReceiver : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { val notificationId = intent.getIntExtra("notificationId", -1) if (notificationId != -1) { clearNotificationOnServer(context, notificationId) } launchApp(context) } private fun launchApp(context: Context) { val launchIntent = context.packageManager.getLaunchIntentForPackage(context.packageName) ?: Intent(context, MainActivity::class.java) launchIntent.apply { action = Intent.ACTION_MAIN addCategory(Intent.CATEGORY_LAUNCHER) putExtra("opened_from_notification", true) addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP) } context.startActivity(launchIntent) } private fun clearNotificationOnServer(context: Context, notificationId: Int) { val client = OkHttpClient() val url = "${ApiConfig.BASE_URL}/clear-notification" val prefs = context.getSharedPreferences("easiwrap_prefs", Context.MODE_PRIVATE) val apiToken = prefs.getString("api_token", "").orEmpty() val formBody = FormBody.Builder() .add("notification_id", notificationId.toString()) .add("api", "true") .build() val requestBuilder = Request.Builder().url(url).post(formBody) if (apiToken.isNotBlank()) { requestBuilder.addHeader("X-Gramia-Api-Token", apiToken) } val request = requestBuilder.build() client.newCall(request).enqueue(object : Callback { override fun onFailure(call: Call, e: IOException) { Log.e("ClearNotif", "Failed to notify server", e) } override fun onResponse(call: Call, response: Response) { Log.i("ClearNotif", "Server acknowledged notification clear") } }) } }