<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Profile Page</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href='https://unpkg.com/boxicons@2.1.4/css/boxicons.min.css' rel='stylesheet'>
    <link rel="shortcut icon" href="logo.webp" type="image/x-icon">
    <style>
        body {
            background: linear-gradient(to bottom, #f0f4f8, #d9e4ec);
            font-family: 'Arial', sans-serif;
            margin: 0;
            padding: 0;
        }

        .profile-container {
            max-width: 800px;
            margin: 2rem auto;
            padding: 2rem;
            background: white;
            border-radius: 15px;
            box-shadow: 0 4px 30px rgba(0, 0, 0, 0.1);
        }

        .profile-header {
            display: grid;
            grid-template-columns: auto 1fr auto;
            align-items: center;
            gap: 1.5rem;
            margin-bottom: 1.5rem;
        }

        .profile-avatar {
            width: 100px;
            height: 100px;
            border-radius: 50%;
            overflow: hidden;
            position: relative;
        }

        .profile-avatar img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        .profile-info h1 {
            margin: 0;
            font-size: 1.8rem;
            font-weight: 600;
            color: #34495e;
        }

        .profile-info p {
            margin: 0;
            color: #7f8c8d;
            font-size: 0.95rem;
        }

        .profile-actions {
            display: flex;
            gap: 1rem;
        }

        .btn-edit, .btn-logout {
            padding: 0.5rem 1rem;
            border: none;
            border-radius: 20px;
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 0.5rem;
            font-size: 0.9rem;
            transition: all 0.3s;
        }

        .btn-edit {
            background: #3498db;
            color: white;
        }

        .btn-logout {
            background: #e74c3c;
            color: white;
        }

        .btn-edit:hover {
            background: #2980b9;
        }

        .btn-logout:hover {
            background: #c0392b;
        }

        .profile-details {
            background: #ecf0f1;
            padding: 1.5rem;
            border-radius: 10px;
            margin-top: 1.5rem;
        }

        .detail-item {
            margin-bottom: 1rem;
        }

        .detail-item label {
            display: block;
            color: #95a5a6;
            margin-bottom: 0.3rem;
            font-size: 0.9rem;
        }

        .detail-item p {
            margin: 0;
            color: #34495e;
            font-size: 1rem;
        }

        .profile-initial {
            width: 100%;
            height: 100%;
            background: #3498db;
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 2.5rem;
            font-weight: 500;
        }

        @media (max-width: 768px) {
            .profile-container {
                padding: 1.5rem;
            }

            .profile-header {
                grid-template-columns: auto 1fr;
                gap: 1rem;
            }

            .profile-actions {
                flex-direction: column;
                gap: 0.5rem;
            }
        }
    </style>
</head>
<body>
    <div class="profile-container">
        <div class="profile-header">
            <div class="profile-avatar" id="avatarContainer">
                <!-- Profile image or initial will be inserted here -->
            </div>
            <div class="profile-info">
                <h1 id="userName">Loading...</h1>
                <p id="userEmail" class="text-muted">Loading...</p>
            </div>
            <div class="profile-actions">
                <button class="btn-edit" onclick="showEditProfile()">
                    <i class='bx bx-edit'></i>
                    Edit Profile
                </button>
                <button class="btn-logout" onclick="handleSignOut()">
                    <i class='bx bx-log-out'></i>
                    Logout
                </button>
            </div>
        </div>

        <div class="profile-details">
            <div class="detail-item">
                <label>Full Name</label>
                <p id="displayName">Loading...</p>
            </div>
            <div class="detail-item">
                <label>Email Address</label>
                <p id="displayEmail">Loading...</p>
            </div>
            <div class="detail-item">
                <label>Phone Number</label>
                <p id="displayPhone">Loading...</p>
            </div>
            <div class="detail-item">
                <label>Member Since</label>
                <p id="memberSince">Loading...</p>
            </div>
        </div>
    </div>

    <!-- Edit Profile Modal -->
    <div class="modal fade" id="editProfileModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Edit Profile</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <form id="editProfileForm">
                        <div class="mb-3">
                            <label class="form-label">Full Name</label>
                            <input type="text" class="form-control" id="editName" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Email</label>
                            <input type="email" class="form-control" id="editEmail" readonly>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Phone Number</label>
                            <input type="tel" class="form-control" id="editPhone" pattern="[0-9]{10}" title="Please enter a valid 10-digit phone number">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Profile Image</label>
                            <input type="file" class="form-control" id="editImage" accept="image/*">
                        </div>
                        <button type="submit" class="btn btn-primary w-100">Save Changes</button>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <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>
    <!-- Add Firebase Database SDK -->
    <script src="https://www.gstatic.com/firebasejs/10.8.0/firebase-database-compat.js"></script>

    <script>
        // Initialize Firebase
        const firebaseConfig = {
            // Your Firebase config here
            apiKey: "AIzaSyB4BNpLQK0RHUmklOMh2HiNMzwFP5uDE5s",
            authDomain: "hosteller-efdb5.firebaseapp.com",
            databaseURL: "https://hosteller-efdb5-default-rtdb.firebaseio.com",
            projectId: "hosteller-efdb5",
            storageBucket: "hosteller-efdb5.firebasestorage.app",
            messagingSenderId: "250843951769",
            appId: "1:250843951769:web:01f0d52d2b1724816cbe08"
        };
        firebase.initializeApp(firebaseConfig);

        const auth = firebase.auth();
        const database = firebase.database(); // Initialize database

        // Check authentication state
        auth.onAuthStateChanged((user) => {
            if (user) {
                updateProfileUI(user);
            } else {
                window.location.href = 'index.html'; // Redirect to home if not logged in
            }
        });

        // Update UI with user data
        async function updateProfileUI(user) {
            const avatarContainer = document.getElementById('avatarContainer');
            const storedImage = localStorage.getItem('userImage');
            
            // Get user data from Firebase
            const snapshot = await database.ref('users/' + user.uid).once('value');
            const userData = snapshot.val() || {};
            const phoneNumber = userData.phone || 'Not set';
            const displayName = userData.name || user.displayName || 'User';

            if (storedImage) {
                avatarContainer.innerHTML = `<img src="${storedImage}" alt="Profile">`;
            } else if (user.photoURL) {
                avatarContainer.innerHTML = `<img src="${user.photoURL}" alt="Profile">`;
            } else {
                avatarContainer.innerHTML = `
                    <div class="profile-initial">
                        ${(displayName || user.email || '?')[0].toUpperCase()}
                    </div>
                `;
            }

            document.getElementById('userName').textContent = displayName;
            document.getElementById('userEmail').textContent = user.email;
            document.getElementById('displayName').textContent = displayName;
            document.getElementById('displayEmail').textContent = user.email;
            document.getElementById('displayPhone').textContent = phoneNumber;
            document.getElementById('memberSince').textContent = new Date(user.metadata.creationTime).toLocaleDateString();
        }

        // Show edit profile modal
        async function showEditProfile() {
            const user = auth.currentUser;
            if (user) {
                // Get user data from Firebase
                const snapshot = await database.ref('users/' + user.uid).once('value');
                const userData = snapshot.val() || {};
                
                document.getElementById('editName').value = userData.name || user.displayName || '';
                document.getElementById('editEmail').value = user.email;
                document.getElementById('editPhone').value = userData.phone || '';
                
                const modal = new bootstrap.Modal(document.getElementById('editProfileModal'));
                modal.show();
            }
        }

        // Handle profile update
        document.getElementById('editProfileForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            const user = auth.currentUser;
            if (!user) return;

            const newName = document.getElementById('editName').value;
            const newPhone = document.getElementById('editPhone').value;
            const imageFile = document.getElementById('editImage').files[0];

            try {
                if (imageFile) {
                    const reader = new FileReader();
                    reader.onload = function () {
                        localStorage.setItem('userImage', reader.result);
                        updateProfileUI(user);
                    };
                    reader.readAsDataURL(imageFile);
                }

                // Store both name and phone in Firebase
                await database.ref('users/' + user.uid).update({
                    name: newName,
                    phone: newPhone
                });

                // Also update Firebase Auth display name to keep it in sync
                await user.updateProfile({
                    displayName: newName
                });

                updateProfileUI(user);

                const modal = bootstrap.Modal.getInstance(document.getElementById('editProfileModal'));
                modal.hide();

                alert('Profile updated successfully!');
            } catch (error) {
                console.error('Error updating profile:', error);
                alert('Error updating profile: ' + error.message);
            }
        });

        // Handle sign out
        function handleSignOut() {
            auth.signOut().then(() => {
                window.location.href = 'index.html';
            }).catch((error) => {
                console.error('Error signing out:', error);
                alert('Error signing out: ' + error.message);
            });
        }
    </script>
</body>
</html>
