
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Welcome</title>
    <link rel="stylesheet" href="style.css">
    <style>
        /* Modal popup styling */
        .modal {
            display: none; /* Hidden by default */
            position: fixed;
            z-index: 1;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5); /* Semi-transparent black */
        }

        .modal-content {
            background-color: yellow;
            margin: 8% auto;
            padding: 20px;
            padding-right: 40px;
            border: 2px solid brown;
            border-radius: 10px;
            width: 90%;
            max-width: 580px;
            max-height: 80vh; /* limit height so it can scroll on small screens */
            overflow-y: auto; /* enable vertical scrolling inside modal */
            text-align: center;
            box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.3);
        }

        .modal-content h2 {
            color: brown;
            margin-bottom: 20px;
        }

        .modal-content p {
            color: brown;
            margin-bottom: 20px;
            font-size: 16px;
        }

        .login-btn {
            background-color: brown;
            color: white;
            padding: 12px 30px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
            text-decoration: none;
            display: inline-block;
        }

        .login-btn:hover {
            background-color: darkbrown;
        }

        .landing-content {
            background-color: yellow;
            color: brown;
            width: 100%;
            height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 24px;
        }
    </style>
</head>
<body>
    <!-- Landing Page Content -->
    <div class="landing-content">
        <div>
            <h1>Welcome to Our Website</h1>
            <p>Explore amazing features and content</p>
        </div>
    </div>

    <!-- Login Popup Modal -->
    <div id="loginModal" class="modal">
        <div class="modal-content">
            <!-- initial view -->
            <div id="initialContent">
                <h2>Login Required</h2>
                <p>You need to login to continue using our website</p>
                <button id="showLoginBtn" class="login-btn">Login Now</button>
            </div>

            <!-- login form (hidden initially) -->
            <div id="loginForm" style="display:none; text-align:left;">
                <h2 style="text-align:center;">Login</h2>
                <div id="loginError" style="color: brown; margin-bottom:10px; display:none;"></div>
                <form id="modalLoginForm">
                    <input type="text" id="m_name" name="name" placeholder="name" required style="width:100%; margin:6px 0; padding:8px;">
                    <input type="password" id="m_password" name="password" placeholder="password" required style="width:100%; margin:6px 0; padding:8px;">
                    <div style="margin-top:6px; text-align:right;">
                        <button type="button" id="showForgotInline" style="background:none; border:none; color:brown; text-decoration:underline; cursor:pointer;">Forgot your password?</button>
                    </div>
                    <div style="text-align:center; margin-top:10px;">
                        <button type="submit" class="login-btn">Sign in</button>
                        <button type="button" id="showSignupFromLogin" style="margin-left:8px;" class="login-btn">Register</button>
                    </div>
                </form>
            </div>

            <!-- password help options (shown after login fails) -->
            <div id="passwordHelpForm" style="display:none; text-align:center;">
                <h2 style="color: brown;">How can we help?</h2>
                <p style="color: brown; margin-bottom:20px;">Did you forget your password or don't have an account?</p>
                <div style="display:flex; gap:10px; justify-content:center;">
                    <button type="button" id="showForgotPasswordForm" class="login-btn">Forgot Password</button>
                    <button type="button" id="showSignupFromHelp" class="login-btn">Register New Account</button>
                </div>
            </div>

            <!-- forgot password form (hidden initially) -->
            <div id="forgotPasswordForm" style="display:none; text-align:left;">
                <h2 style="text-align:center;">Reset Password</h2>
                <div id="forgotPasswordError" style="color: brown; margin-bottom:10px; display:none;"></div>
                <div id="forgotPasswordSuccess" style="color: green; background-color:#90EE90; margin-bottom:10px; padding:10px; border-radius:5px; display:none;"></div>
                <form id="forgotPasswordFormElement">
                    <p style="color: brown; margin-bottom:10px;">Enter the email address associated with your account. We'll send you a link to reset your password.</p>
                    <input type="email" id="forgot_email" name="email" placeholder="Enter your email" required style="width:100%; margin:10px 0; padding:8px; box-sizing:border-box;">
                    <div style="text-align:center; margin-top:15px;">
                        <button type="submit" class="login-btn">Send Reset Link</button>
                        <button type="button" id="backToLoginFromForgot" style="margin-left:8px;" class="login-btn">Back to Login</button>
                    </div>
                </form>
            </div>

            <!-- reset password form (shown after email is verified) -->
            <div id="resetPasswordForm" style="display:none; text-align:left;">
                <h2 style="text-align:center;">Create New Password</h2>
                <div id="resetPasswordError" style="color: brown; margin-bottom:10px; display:none;"></div>
                <form id="resetPasswordFormElement">
                    <input type="hidden" id="reset_token" name="token">
                    <input type="hidden" id="reset_email" name="email">
                    <p style="color: brown; margin-bottom:10px;">Enter your new password below.</p>
                    <input type="password" id="reset_new_password" name="new_password" placeholder="New password" required style="width:100%; margin:6px 0; padding:8px; box-sizing:border-box;">
                    <input type="password" id="reset_confirm_password" name="confirm_password" placeholder="Confirm password" required style="width:100%; margin:6px 0; padding:8px; box-sizing:border-box;">
                    <div style="text-align:center; margin-top:15px;">
                        <button type="submit" class="login-btn">Reset Password</button>
                    </div>
                </form>
            </div>

            <!-- signup form (hidden initially) -->
            <div id="signupForm" style="display:none; text-align:left;">
                <h2 style="text-align:center;">Sign up</h2>
                <div id="signupError" style="color: brown; margin-bottom:10px; display:none;"></div>
                <form id="modalSignupForm">
                    <input type="text" id="s_name" name="name" placeholder="name" required style="width:100%; margin:6px 0; padding:8px;">
                    <input type="password" id="s_password" name="password" placeholder="password (min 8 chars: letters, numbers, symbols)" required style="width:100%; margin:6px 0; padding:8px;">
                    <div id="passwordRules" style="display:none; color: brown; font-size: 12px; margin-bottom: 10px; padding: 8px; background-color: rgba(255,255,255,0.7); border-radius: 3px;">
                        <strong>Password must contain:</strong><br>
                        ✓ At least 8 characters<br>
                        ✓ At least one letter (a-z or A-Z)<br>
                        ✓ At least one number (0-9)<br>
                        ✓ At least one symbol (!@#$%^&*)<br>
                    </div>
                    <input type="email" id="s_email" name="email" placeholder="email" required style="width:100%; margin:6px 0; padding:8px;">
                    <input type="text" id="s_age" name="age" placeholder="age" required style="width:100%; margin:6px 0; padding:8px;">
                    <input type="text" id="s_phone" name="phone" placeholder="phone number" required style="width:100%; margin:6px 0; padding:8px;">
                    <input type="text" id="s_gender" name="gender" placeholder="gender" required style="width:100%; margin:6px 0; padding:8px;">
                    <div style="text-align:center; margin-top:10px;">
                        <button type="submit" class="login-btn">Create Account</button>
                        <button type="button" id="backToLoginFromSignup" style="margin-left:8px;" class="login-btn">Back to Login</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script>
        // Check if user is already logged in
        let isLoggedIn = localStorage.getItem('userLoggedIn') === 'true';

        // Dev helper: log current stored value
        try { console.log('userLoggedIn flag:', localStorage.getItem('userLoggedIn')); } catch(e) {}

        // Show login popup after 4 seconds ONLY if user is not logged in
        if (!isLoggedIn) {
            setTimeout(function() {
                document.getElementById('loginModal').style.display = 'block';
            }, 4000);
        }

        const initialContent = document.getElementById('initialContent');
        const loginForm = document.getElementById('loginForm');
        const signupForm = document.getElementById('signupForm');
        const passwordHelpForm = document.getElementById('passwordHelpForm');
        const forgotPasswordForm = document.getElementById('forgotPasswordForm');
        const resetPasswordForm = document.getElementById('resetPasswordForm');
        const loginError = document.getElementById('loginError');
        const signupError = document.getElementById('signupError');
        const forgotPasswordError = document.getElementById('forgotPasswordError');
        const forgotPasswordSuccess = document.getElementById('forgotPasswordSuccess');
        const resetPasswordError = document.getElementById('resetPasswordError');

        // Show login form
        function showLogin() {
            initialContent.style.display = 'none';
            loginForm.style.display = 'block';
            signupForm.style.display = 'none';
            passwordHelpForm.style.display = 'none';
            forgotPasswordForm.style.display = 'none';
            resetPasswordForm.style.display = 'none';
            loginError.style.display = 'none';
        }

        // Show signup form
        function showSignup() {
            initialContent.style.display = 'none';
            loginForm.style.display = 'none';
            signupForm.style.display = 'block';
            passwordHelpForm.style.display = 'none';
            forgotPasswordForm.style.display = 'none';
            resetPasswordForm.style.display = 'none';
            signupError.style.display = 'none';
        }

        // Show password help options
        function showPasswordHelp() {
            initialContent.style.display = 'none';
            loginForm.style.display = 'none';
            signupForm.style.display = 'none';
            passwordHelpForm.style.display = 'block';
            forgotPasswordForm.style.display = 'none';
            resetPasswordForm.style.display = 'none';
        }

        // Show forgot password form
        function showForgotPassword() {
            initialContent.style.display = 'none';
            loginForm.style.display = 'none';
            signupForm.style.display = 'none';
            passwordHelpForm.style.display = 'none';
            forgotPasswordForm.style.display = 'block';
            resetPasswordForm.style.display = 'none';
            forgotPasswordError.style.display = 'none';
            forgotPasswordSuccess.style.display = 'none';
        }

        // Show reset password form
        function showResetPassword(token, email) {
            document.getElementById('reset_token').value = token;
            document.getElementById('reset_email').value = email;
            initialContent.style.display = 'none';
            loginForm.style.display = 'none';
            signupForm.style.display = 'none';
            passwordHelpForm.style.display = 'none';
            forgotPasswordForm.style.display = 'none';
            resetPasswordForm.style.display = 'block';
            resetPasswordError.style.display = 'none';
        }

        // Event listeners for buttons
        document.getElementById('showLoginBtn').addEventListener('click', showLogin);
        document.getElementById('showSignupFromLogin').addEventListener('click', showSignup);
        document.getElementById('showSignupFromHelp').addEventListener('click', showSignup);
        document.getElementById('showForgotPasswordForm').addEventListener('click', showForgotPassword);
        document.getElementById('backToLoginFromForgot').addEventListener('click', showLogin);
        document.getElementById('backToLoginFromSignup').addEventListener('click', showLogin);

        // Handle login submit via AJAX
        document.getElementById('modalLoginForm').addEventListener('submit', function(e){
            e.preventDefault();
            loginError.style.display = 'none';
            const name = document.getElementById('m_name').value;
            const pass = document.getElementById('m_password').value;

            fetch('api_login.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: new URLSearchParams({ name: name, password: pass })
            }).then(async r => {
                const text = await r.text();
                let data;
                try { data = JSON.parse(text); } catch (e) { throw new Error('Server error: ' + text); }
                if (data.success) {
                    localStorage.setItem('userLoggedIn', 'true');
                    window.location = data.redirect || 'home.php';
                } else {
                    loginError.textContent = (data.message === 'not_found') ? 'No account found with this name.' : 'Wrong username or password.';
                    loginError.style.display = 'block';
                    // Do not auto-show password help. User can click the inline "Forgot your password?" link.
                }
            }).catch(err => {
                loginError.textContent = err.message || 'Network error';
                loginError.style.display = 'block';
            });
        });

        // Handle forgot password email submit
        document.getElementById('forgotPasswordFormElement').addEventListener('submit', function(e){
            e.preventDefault();
            forgotPasswordError.style.display = 'none';
            forgotPasswordSuccess.style.display = 'none';
            const email = document.getElementById('forgot_email').value;

            fetch('api_forgot_password.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: new URLSearchParams({ email: email })
            }).then(async r => {
                const text = await r.text();
                let data;
                try { data = JSON.parse(text); } catch (e) { throw new Error('Server error: ' + text); }
                if (data.success) {
                    forgotPasswordSuccess.textContent = data.message;
                    forgotPasswordSuccess.style.display = 'block';
                    document.getElementById('forgot_email').value = '';
                } else if (data.message === 'no_account') {
                    forgotPasswordError.textContent = 'No account found with this email address.';
                    forgotPasswordError.style.display = 'block';
                } else {
                    forgotPasswordError.textContent = data.message || 'Error processing request';
                    forgotPasswordError.style.display = 'block';
                }
            }).catch(err => {
                forgotPasswordError.textContent = err.message || 'Network error';
                forgotPasswordError.style.display = 'block';
            });
        });

        // Handle reset password submit
        document.getElementById('resetPasswordFormElement').addEventListener('submit', function(e){
            e.preventDefault();
            resetPasswordError.style.display = 'none';
            const token = document.getElementById('reset_token').value;
            const email = document.getElementById('reset_email').value;
            const newPassword = document.getElementById('reset_new_password').value;
            const confirmPassword = document.getElementById('reset_confirm_password').value;

            fetch('api_reset_password.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: new URLSearchParams({ 
                    token: token, 
                    email: email, 
                    new_password: newPassword, 
                    confirm_password: confirmPassword 
                })
            }).then(async r => {
                const text = await r.text();
                let data;
                try { data = JSON.parse(text); } catch (e) { throw new Error('Server error: ' + text); }
                if (data.success) {
                    resetPasswordError.style.color = 'green';
                    resetPasswordError.textContent = data.message;
                    resetPasswordError.style.display = 'block';
                    setTimeout(() => {
                        document.getElementById('reset_new_password').value = '';
                        document.getElementById('reset_confirm_password').value = '';
                        showLogin();
                    }, 2000);
                } else {
                    resetPasswordError.textContent = data.message || 'Error resetting password';
                    resetPasswordError.style.display = 'block';
                }
            }).catch(err => {
                resetPasswordError.textContent = err.message || 'Network error';
                resetPasswordError.style.display = 'block';
            });
        });

        // Handle signup submit via AJAX
        document.getElementById('modalSignupForm').addEventListener('submit', function(e){
            e.preventDefault();
            signupError.style.display = 'none';
            const passwordVal = document.getElementById('s_password').value;
            // Client-side password validation
            const passMin = passwordVal.length >= 8;
            const passLetter = /[a-zA-Z]/.test(passwordVal);
            const passNumber = /[0-9]/.test(passwordVal);
            const passSymbol = /[!@#$%^&*()_+\-=[\]{};:'"\\|,.<>\/?`~]/.test(passwordVal);
            if (!passMin || !passLetter || !passNumber || !passSymbol) {
                // Show password rules and a helpful error message
                document.getElementById('passwordRules').style.display = 'block';
                signupError.textContent = 'Password does not meet the required format.';
                signupError.style.display = 'block';
                return;
            }

            // Hide password rules if valid
            document.getElementById('passwordRules').style.display = 'none';

            const data = new URLSearchParams({
                name: document.getElementById('s_name').value,
                password: passwordVal,
                email: document.getElementById('s_email').value,
                age: document.getElementById('s_age').value,
                phone: document.getElementById('s_phone').value,
                gender: document.getElementById('s_gender').value
            });

            fetch('api_signup.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: data
            }).then(async r => {
                const text = await r.text();
                let data;
                try { data = JSON.parse(text); } catch (e) { throw new Error('Server error: ' + text); }
                if (data.success) {
                    // Do NOT mark user as logged in. Redirect to landing and show login modal so user can sign in.
                    window.location = data.redirect ? (data.redirect + (data.redirect.indexOf('?') === -1 ? '?showLogin=1' : '&showLogin=1')) : 'landing.php?showLogin=1';
                } else if (data.message === 'conflict' && data.conflicts) {
                    signupError.innerHTML = 'Conflicting fields: ' + data.conflicts.join(', ');
                    signupError.style.display = 'block';
                } else {
                    signupError.textContent = data.message || 'Signup failed';
                    signupError.style.display = 'block';
                }
            }).catch(err => {
                signupError.textContent = err.message || 'Network error';
                signupError.style.display = 'block';
            });
        });

        // Check for reset token in URL (from email link)
        const urlParams = new URLSearchParams(window.location.search);
        const resetToken = urlParams.get('token');
        const resetEmail = urlParams.get('email');
        const showLoginParam = urlParams.get('showLogin');
        
        if (resetToken && resetEmail) {
            // Verify token on page load and show reset form
            setTimeout(function() {
                showResetPassword(resetToken, resetEmail);
                document.getElementById('loginModal').style.display = 'block';
                window.history.replaceState({}, document.title, window.location.pathname);
            }, 500);
        }

        // If redirected after signup, show login modal
        if (showLoginParam === '1') {
            setTimeout(function() {
                showLogin();
                document.getElementById('loginModal').style.display = 'block';
                // Clean URL
                window.history.replaceState({}, document.title, window.location.pathname);
            }, 500);
        }

        // Handle logout by clearing the login flag
        const logoutLink = document.querySelector('a[href="logout.php"]');
        if (logoutLink) {
            logoutLink.addEventListener('click', function(e) {
                localStorage.setItem('userLoggedIn', 'false');
            });
        }

        // Inline forgot password link from login form
        const showForgotInlineBtn = document.getElementById('showForgotInline');
        if (showForgotInlineBtn) {
            showForgotInlineBtn.addEventListener('click', function() {
                showForgotPassword();
            });
        }
    </script>
    <!-- Dev helper button: reset popup state -->
    <!-- <button id="resetPopupBtn" title="Reset popup state" style="position:fixed;right:12px;bottom:12px;padding:8px 12px;background:brown;color:white;border:none;border-radius:6px;cursor:pointer;z-index:9999;">Reset Popup</button> -->
    <script>
        // Reset popup button handler (clears stored login flag and reloads page)
        (function(){
            var btn = document.getElementById('resetPopupBtn');
            if (!btn) return;
            btn.addEventListener('click', function(){
                try { localStorage.removeItem('userLoggedIn'); } catch(e) {}
                // reload so modal logic runs again
                location.reload();
            });
        })();
    </script>
</body>
</html>
