package com.example.time_tracking

import android.content.Intent
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.google.firebase.firestore.FirebaseFirestore

class LoginActivity : AppCompatActivity() {

    private lateinit var btnLogin: Button
    private lateinit var etPassword: EditText
    private lateinit var etUsername: EditText
    private lateinit var db: FirebaseFirestore

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)

        btnLogin = findViewById(R.id.btnLogin)
        etPassword = findViewById(R.id.etPassword)
        etUsername = findViewById(R.id.etUsername)

        db = FirebaseFirestore.getInstance()

        btnLogin.setOnClickListener {
            val username = etUsername.text.toString()
            val password = etPassword.text.toString()

            if (isValidUsername(username) && isValidPassword(password)) {
                addUserToDatabase(username, password)
                // Navigate to MenuActivity
                startActivity(Intent(this, MenuActivity::class.java))
                finish()
            } else {
                // Show error message
                Toast.makeText(this, "Invalid username or password", Toast.LENGTH_SHORT).show()
            }
        }
    }

    private fun isValidUsername(username: String): Boolean {
        // Implement username validation logic here
        return username.length > 5
    }

    private fun isValidPassword(password: String): Boolean {
        // Implement password validation logic here
        val containsNumber = password.any { it.isDigit() }
        if (!containsNumber) {
            // Display error message for password without a number
            Toast.makeText(this, "No digits found in password", Toast.LENGTH_SHORT).show()
            return false
        }
        val passwordRegex = "^(?=.*[!@#\$%^&*])(?=\\S+\$).{8,}\$".toRegex()
        return passwordRegex.matches(password)
    }

    private fun addUserToDatabase(username: String, password: String) {
        val user = hashMapOf(
            "username" to username,
            "password" to password
        )

        db.collection("users")
            .add(user)
            .addOnSuccessListener { documentReference ->
                Toast.makeText(this, "User added successfully with ID: ${documentReference.id}", Toast.LENGTH_SHORT).show()
            }
            .addOnFailureListener { e ->
                Toast.makeText(this, "Error adding user: $e", Toast.LENGTH_SHORT).show()
            }
    }
}



