package com.example.sms_call_sync;

import android.content.ContentValues;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.preference.PreferenceManager; // For PreferenceManager
import android.util.Log;

import java.util.HashSet;
import java.util.Set;

public class DatabaseHelper extends SQLiteOpenHelper {
    private static final String DATABASE_NAME = "app_data.db";
    private static final int DATABASE_VERSION = 1;

    // Table for blocked numbers
    private static final String TABLE_BLOCKED_NUMBERS = "blocked_numbers";
    private static final String COLUMN_ID = "id";
    private static final String COLUMN_NUMBER = "number";

    private Context context; // Store context to access SharedPreferences

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        this.context = context; // Initialize context
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // Create blocked numbers table
        String CREATE_BLOCKED_NUMBERS_TABLE = "CREATE TABLE " + TABLE_BLOCKED_NUMBERS + "("
                + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
                + COLUMN_NUMBER + " TEXT UNIQUE" // Ensure numbers are unique
                + ")";
        db.execSQL(CREATE_BLOCKED_NUMBERS_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_BLOCKED_NUMBERS);
        onCreate(db);
    }

    public void addBlockedNumber(String number) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(COLUMN_NUMBER, number);
        try {
            db.insert(TABLE_BLOCKED_NUMBERS, null, values);
            Log.d("DatabaseHelper", "Blocked number added: " + number);
        } catch (Exception e) {
            Log.e("DatabaseHelper", "Error adding blocked number: " + e.getMessage());
        } finally {
            db.close();
        }
    }

    public void removeBlockedNumber(String number) {
        SQLiteDatabase db = this.getWritableDatabase();
        try {
            db.delete(TABLE_BLOCKED_NUMBERS, COLUMN_NUMBER + " = ?", new String[]{number});
            Log.d("DatabaseHelper", "Blocked number removed: " + number);
        } catch (Exception e) {
            Log.e("DatabaseHelper", "Error removing blocked number: " + e.getMessage());
        } finally {
            db.close();
        }
    }

    public Set<String> getBlockedNumbers() {
        Set<String> blockedNumbers = new HashSet<>();
        String selectQuery = "SELECT * FROM " + TABLE_BLOCKED_NUMBERS;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = null;
        try {
            cursor = db.rawQuery(selectQuery, null);
            if (cursor.moveToFirst()) {
                int numberColumnIndex = cursor.getColumnIndex(COLUMN_NUMBER);
                if (numberColumnIndex != -1) {
                    do {
                        blockedNumbers.add(cursor.getString(numberColumnIndex));
                    } while (cursor.moveToNext());
                } else {
                    Log.e("DatabaseHelper", "Column 'number' not found in blocked_numbers table.");
                }
            }
        } catch (Exception e) {
            Log.e("DatabaseHelper", "Error getting blocked numbers: " + e.getMessage());
        } finally {
            if (cursor != null) {
                cursor.close();
            }
            db.close();
        }
        return blockedNumbers;
    }

    /**
     * Retrieves the saved phone name from SharedPreferences.
     * This method is added to resolve the 'getPhoneName()' error in SyncManager.
     * @return The saved phone name, or an empty string if not found.
     */
    public String getPhoneName() {
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
        return sharedPreferences.getString("phone_name", ""); // "phone_name" is the key used in MainActivity
    }
}
