package com.example.weighttracker;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.telephony.SmsManager;
import android.widget.Toast;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

// I moved SMS logic here so WeightLogActivity is not responsible for everything.
public class SmsHelper {

    public static final int SMS_PERMISSION_CODE = 101;

    // Change this to a real number only when testing on a real Android device.
    // The emulator may show the SMS toast without actually sending a real text.
    private static final String TEST_PHONE_NUMBER = "5551234567";

    // Checks whether SMS permission is already granted.
    public static boolean hasSmsPermission(Context context) {
        return ContextCompat.checkSelfPermission(
                context,
                Manifest.permission.SEND_SMS
        ) == PackageManager.PERMISSION_GRANTED;
    }

    // Requests SMS permission only if the app does not already have it.
    public static void checkSmsPermission(Activity activity) {
        if (!hasSmsPermission(activity)) {
            ActivityCompat.requestPermissions(
                    activity,
                    new String[]{Manifest.permission.SEND_SMS},
                    SMS_PERMISSION_CODE
            );
        }
    }

    // Sends the goal text only if permission was granted.
    // If permission was denied, the rest of the app still works.
    public static void sendGoalText(Context context) {
        if (!hasSmsPermission(context)) {
            return;
        }

        String message = "Goal reached. Nice work.";

        try {
            SmsManager smsManager = SmsManager.getDefault();
            smsManager.sendTextMessage(TEST_PHONE_NUMBER, null, message, null, null);

            Toast.makeText(context, "Goal reached SMS sent", Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            Toast.makeText(context, "SMS failed to send", Toast.LENGTH_SHORT).show();
        }
    }
}