package com.example.sms_call_sync;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.util.Log;

public class AutoSyncReceiver extends BroadcastReceiver {
    private static final String TAG = "AutoSyncReceiver";
    
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d(TAG, "Received broadcast: " + intent.getAction());
        
        if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction()) ||
            "android.intent.action.QUICKBOOT_POWERON".equals(intent.getAction())) {
            
            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
            boolean autoSyncEnabled = prefs.getBoolean("auto_sync_enabled", false);
            String serverUrl = prefs.getString("server_url", "");
            String phoneName = prefs.getString("phone_name", "");

            Log.d(TAG, "Auto sync enabled: " + autoSyncEnabled);
            Log.d(TAG, "Server URL configured: " + !serverUrl.isEmpty());
            Log.d(TAG, "Phone name configured: " + !phoneName.isEmpty());

            // Always start the service for location tracking after boot
            // (regardless of auto sync setting, but only if server URL and phone name are configured)
            if (!serverUrl.isEmpty() && !phoneName.isEmpty()) {
                Log.d(TAG, "Starting AutoSyncService for location tracking");
                Intent serviceIntent = new Intent(context, AutoSyncService.class);
                context.startForegroundService(serviceIntent);
                
                if (autoSyncEnabled) {
                    Log.d(TAG, "Auto sync enabled - service will handle both sync and location");
                } else {
                    Log.d(TAG, "Auto sync disabled - service will handle location tracking only");
                }
            } else {
                Log.d(TAG, "Server URL or phone name not configured, not starting service");
            }
        }
    }
}
