package com.howon.lifepass;

import android.os.Bundle;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.firebase.firestore.FieldValue;
import com.google.firebase.firestore.FirebaseFirestore;

import java.util.HashMap;
import java.util.Map;

public class AddNoticeActivity extends AppCompatActivity {

    private EditText titleEditText, authorEditText, contentEditText;
    private FirebaseFirestore db;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_notice);

        // View 초기화
        titleEditText = findViewById(R.id.edit_text_title);
        authorEditText = findViewById(R.id.edit_text_author);
        contentEditText = findViewById(R.id.edit_text_content);
        FloatingActionButton fabSubmit = findViewById(R.id.fab_submit);

        // Firebase Firestore 초기화
        db = FirebaseFirestore.getInstance();

        // fabSubmit 버튼 클릭 리스너
        fabSubmit.setOnClickListener(v -> {
            String title = titleEditText.getText().toString().trim();
            String author = authorEditText.getText().toString().trim();
            String content = contentEditText.getText().toString().trim();

            if (title.isEmpty() || author.isEmpty() || content.isEmpty()) {
                Toast.makeText(AddNoticeActivity.this, "모든 필드를 입력하세요.", Toast.LENGTH_SHORT).show();
                return;
            }

            // Firebase에 공지사항 추가
            Map<String, Object> notice = new HashMap<>();
            notice.put("title", title);
            notice.put("author", author);
            notice.put("content", content);
            notice.put("timestamp", FieldValue.serverTimestamp());

            db.collection("notices")
                    .add(notice)
                    .addOnSuccessListener(documentReference -> {
                        Toast.makeText(AddNoticeActivity.this, "공지사항이 추가되었습니다.", Toast.LENGTH_SHORT).show();
                        finish(); // 액티비티 종료
                    })
                    .addOnFailureListener(e -> {
                        Toast.makeText(AddNoticeActivity.this, "오류가 발생했습니다. 다시 시도하세요.", Toast.LENGTH_SHORT).show();
                    });
        });
    }
}