<!DOCTYPE html>
<html lang="th">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Cyfence - เข้าสู่ระบบ</title>
    <link href="https://fonts.googleapis.com/css2?family=Sarabun:wght@400;700&display=swap" rel="stylesheet">
    <style>
        * {
            box-sizing: border-box;
            font-family: 'Sarabun', sans-serif;
        }

        body {
            margin: 0;
            padding: 0;
            background-color: #f5f5f5;
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .login-container {
            background: white;
            padding: 2rem;
            border-radius: 10px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            width: 100%;
            max-width: 400px;
            margin: 20px;
        }

        .logo {
            max-width: 200px;
            display: block;
            margin: 0 auto 2rem auto;
        }

        h2 {
            text-align: center;
            color: #333;
            margin-bottom: 2rem;
        }

        .form-group {
            margin-bottom: 1.5rem;
        }

        label {
            display: block;
            margin-bottom: 0.5rem;
            color: #555;
        }

        input {
            width: 100%;
            padding: 0.75rem;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 1rem;
        }

        input:focus {
            outline: none;
            border-color: #4A90E2;
            box-shadow: 0 0 0 2px rgba(74, 144, 226, 0.2);
        }

        button {
            width: 100%;
            padding: 0.75rem;
            background-color: #4A90E2;
            color: white;
            border: none;
            border-radius: 4px;
            font-size: 1rem;
            cursor: pointer;
            transition: background-color 0.3s;
        }

        button:hover {
            background-color: #357ABD;
        }

        .toggle-form {
            text-align: center;
            margin-top: 1rem;
        }

        .toggle-form a {
            color: #4A90E2;
            text-decoration: none;
        }

        .toggle-form a:hover {
            text-decoration: underline;
        }

        #message {
            margin-top: 1rem;
            padding: 0.75rem;
            border-radius: 4px;
            text-align: center;
        }

        .error {
            background-color: #FFE8E8;
            color: #D63031;
            border: 1px solid #FAA5A5;
        }

        .success {
            background-color: #E8F5E9;
            color: #2ECC71;
            border: 1px solid #A5D6A7;
        }

        .loading {
            display: none;
            text-align: center;
            margin-top: 1rem;
        }

        .spinner {
            border: 3px solid #f3f3f3;
            border-radius: 50%;
            border-top: 3px solid #4A90E2;
            width: 24px;
            height: 24px;
            animation: spin 1s linear infinite;
            margin: 0 auto;
        }

        @keyframes spin {
            0% {
                transform: rotate(0deg);
            }

            100% {
                transform: rotate(360deg);
            }
        }
    </style>
</head>

<body>
    <div class="login-container">
        <img src="https://www.cyfence.com/wp-content/uploads/2021/09/%E0%B8%A5%E0%B8%87%E0%B9%80%E0%B8%A7%E0%B9%87%E0%B8%9A%E0%B9%83%E0%B8%AB%E0%B8%A1%E0%B9%88.jpg"
            alt="Cyfence Logo" class="logo">

        <div id="loginForm">
            <h2>เข้าสู่ระบบ</h2>
            <div class="form-group">
                <label for="loginEmail">อีเมล</label>
                <input type="email" id="loginEmail" required placeholder="example@email.com">
            </div>
            <div class="form-group">
                <label for="loginPassword">รหัสผ่าน</label>
                <input type="password" id="loginPassword" required placeholder="รหัสผ่านของคุณ">
            </div>
            <button onclick="handleLogin()">เข้าสู่ระบบ</button>
            <div class="info-text" style="margin-top: 1rem; text-align: center; color: #666;">
                หากต้องการสมัครใช้งาน กรุณาติดต่อ Admin โดยตรง
            </div>
        </div>

        <div id="message"></div>
        <div class="loading">
            <div class="spinner"></div>
        </div>
    </div>



    <!-- Firebase Scripts -->
    <script src="https://www.gstatic.com/firebasejs/10.8.0/firebase-app-compat.js"></script>
    <script src="https://www.gstatic.com/firebasejs/10.8.0/firebase-auth-compat.js"></script>
    <script src="https://www.gstatic.com/firebasejs/10.8.0/firebase-firestore-compat.js"></script>

    <!-- Configuration -->
    <script>
        const firebaseConfig = {
            apiKey: "AIzaSyAcb9q1eX1QM9Gl_W6U9WZNbeg6M-uyhpk",
            authDomain: "cyfencedevbyken.firebaseapp.com",
            projectId: "cyfencedevbyken",
            storageBucket: "cyfencedevbyken.appspot.com",
            messagingSenderId: "632813871756",
            appId: "1:632813871756:web:57d674643f258ddd2e11a9",
            measurementId: "G-1EJNKSHNQ3"
        };

        // Initialize Firebase
        firebase.initializeApp(firebaseConfig);
        const auth = firebase.auth();
        const db = firebase.firestore();

        document.addEventListener('DOMContentLoaded', () => {
            const urlParams = new URLSearchParams(window.location.search);
            const error = urlParams.get('error');
            if (error) {
                alert('Error from URL: ' + error);
            }
        });

    </script>

    <script>
        // ตรวจสอบสถานะการล็อกอิน
        auth.onAuthStateChanged(user => {
            if (user) {
                window.location.href = 'dashboard.html';
            }
        });

        // ฟังก์ชันสลับฟอร์ม
        function toggleForm(formType) {
            const loginForm = document.getElementById('loginForm');
            const registerForm = document.getElementById('registerForm');

            if (formType === 'register') {
                loginForm.style.display = 'none';
                registerForm.style.display = 'block';
            } else {
                loginForm.style.display = 'block';
                registerForm.style.display = 'none';
            }

            // เคลียร์ข้อความแจ้งเตือน
            showMessage('', '');
        }

        // ฟังก์ชันแสดงข้อความ
        function showMessage(message, type) {
            const messageDiv = document.getElementById('message');
            messageDiv.textContent = message;
            messageDiv.className = type;
            messageDiv.style.display = message ? 'block' : 'none';
        }

        // แสดง/ซ่อน Loading
        function toggleLoading(show) {
            document.querySelector('.loading').style.display = show ? 'block' : 'none';
        }

        // ฟังก์ชันล็อกอิน
        async function handleLogin() {
            const email = document.getElementById('loginEmail').value;
            const password = document.getElementById('loginPassword').value;

            console.log('Attempting login...'); // เพิ่ม log

            if (!email || !password) {
                showMessage('กรุณากรอกอีเมลและรหัสผ่าน', 'error');
                return;
            }

            toggleLoading(true);
            try {
                console.log('Signing in...'); // เพิ่ม log
                const userCredential = await auth.signInWithEmailAndPassword(email, password);
                console.log('Sign in successful:', userCredential); // เพิ่ม log

                showMessage('เข้าสู่ระบบสำเร็จ กำลังนำคุณไปยังหน้าหลัก...', 'success');

                // เพิ่มการหน่วงเวลาเพื่อให้เห็น log
                setTimeout(async () => {
                    await logActivity(auth.currentUser.uid, 'login');
                    window.location.href = 'dashboard.html';
                }, 2000);

            } catch (error) {
                console.error('Login error:', error);
                let errorMessage = 'เกิดข้อผิดพลาดในการเข้าสู่ระบบ';
                // ... ส่วนจัดการ error อื่นๆ ...
                showMessage(errorMessage, 'error');
            }
            toggleLoading(false);
        }

        // ฟังก์ชันสมัครสมาชิก
        async function handleRegister() {
            const email = document.getElementById('registerEmail').value;
            const password = document.getElementById('registerPassword').value;
            const displayName = document.getElementById('registerDisplayName').value;

            if (!email || !password || !displayName) {
                showMessage('กรุณากรอกข้อมูลให้ครบถ้วน', 'error');
                return;
            }

            toggleLoading(true);
            try {
                // สร้างบัญชีผู้ใช้
                const userCredential = await auth.createUserWithEmailAndPassword(email, password);
                const user = userCredential.user;

                // เพิ่มข้อมูลผู้ใช้ใน Firestore พร้อมสถานะการอนุมัติ
                await db.collection('users').doc(user.uid).set({
                    email: email,
                    displayName: displayName,
                    createdAt: new Date(),
                    isApproved: false, // เพิ่มสถานะการอนุมัติ
                    role: 'user'
                });

                // บันทึก log
                await logActivity(user.uid, 'register');

                showMessage('สมัครสมาชิกสำเร็จ กรุณารอการอนุมัติจากผู้ดูแลระบบ', 'success');

                // ทำการ sign out หลังจากลงทะเบียน
                await auth.signOut();

                setTimeout(() => {
                    window.location.href = 'login.html';
                }, 3000);
            } catch (error) {
                let errorMessage = 'เกิดข้อผิดพลาดในการสมัครสมาชิก';
                if (error.code === 'auth/email-already-in-use') {
                    errorMessage = 'อีเมลนี้ถูกใช้งานแล้ว';
                } else if (error.code === 'auth/weak-password') {
                    errorMessage = 'รหัสผ่านต้องมีความยาวอย่างน้อย 6 ตัวอักษร';
                }
                showMessage(errorMessage, 'error');
            }
            toggleLoading(false);
        }

        // ฟังก์ชันบันทึก Log
        async function logActivity(userId, action, details = null) {
            try {
                await db.collection('logs').add({
                    userId: userId,
                    action: action,
                    details: details,
                    timestamp: new Date(),
                    userAgent: navigator.userAgent
                });
            } catch (error) {
                console.error('Error logging activity:', error);
            }
        }

        // เพิ่ม Event Listener สำหรับการกด Enter
        document.addEventListener('keypress', function (e) {
            if (e.key === 'Enter') {
                if (document.getElementById('loginForm').style.display !== 'none') {
                    handleLogin();
                } else {
                    handleRegister();
                }
            }
        });
    </script>
</body>

</html>