// frontend

<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" type="text/css" href="your_stylesheet.css">
  <title>Login Page</title>
</head>
<body>
  <div class="container" style="text-align: center;">
    <h1>Welcome to Sri's Blog</h1>
    <input id="usernameInput" type="text" class="input-text" placeholder="Username">
    <input id="passwordInput" type="password" class="input-text" placeholder="Password">
    <button id="loginButton" class="button" onclick="loginUser()">Login</button>
    <button id="registerButton" class="button register-button" onclick="showRegistrationForm()">Register New User</button>

    <!-- Registration Form (Hidden by default) -->
    <div id="registrationForm" style="display: none;">
      <h2>Register New User</h2>
      <input id="newUsernameInput" type="text" class="input-text" placeholder="New Username">
      <input id="newPasswordInput" type="password" class="input-text" placeholder="New Password">
      <button id="registerNewUserButton" class="button" onclick="registerUser()">Register</button>
    </div>
  </div>

  <script>
    function showRegistrationForm() {
      document.getElementById("registrationForm").style.display = "block";
    }

    function registerUser() {
      const newUsername = document.getElementById("newUsernameInput").value;
      const newPassword = document.getElementById("newPasswordInput").value;

      // Make a POST request to register a new user
      fetch('http://127.0.0.1:5000/users', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          username: newUsername,
          password: newPassword,
        }),
      })
      .then(response => response.json())
      .then(data => {
        console.log('User registration successful:', data);
        alert('Registration successful!');
        // Optionally, you can show a success message or redirect the user
      })
      .catch(error => {
        console.error('Error registering user:', error);
        alert('Registration failed. Please try again.');
        // Handle error, show error message, etc.
      });
    }

    function loginUser() {
      const username = document.getElementById("usernameInput").value;
      const password = document.getElementById("passwordInput").value;

      // Make a POST request to check login credentials
      fetch('http://127.0.0.1:5000/login', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          username: username,
          password: password,
        }),
      })
      .then(response => {
        if (response.ok) {
          console.log('Login successful');
          alert('Login succesful, redirecting you to the main page');
          // Optionally, you can redirect the user to another link
          window.location.href = 'https://srivaidyas.github.io/student2.0/AD_compsci.html';
        } else {
          console.log('Login failed');
          alert('Login failed, please check you credentials');
          // Optionally, you can show an error message
        }
      })
      .catch(error => {
        console.error('Error:', error);
        // Handle error, show error message, etc.
      });
    }
  </script>
</body>
</html>
// backend

from flask import Flask, jsonify, request
from flask_sqlalchemy import SQLAlchemy
from flask_restful import Resource, Api
from flask_cors import CORS

app = Flask(__name__)
CORS(app, resources={ r"/users/*": {"origins": ["http://127.0.0.1:4100", "https://srivaidyas.github.io"]},
    r"/login/*": {"origins": ["http://127.0.0.1:4100", "https://srivaidyas.github.io"]},
    r"/users": {"origins": ["http://127.0.0.1:4100", "https://srivaidyas.github.io"]}})
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///users.db'  # SQLite database file named users.db
db = SQLAlchemy(app)
api = Api(app)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(128), unique=True, nullable=False)
    password = db.Column(db.String(128), nullable=False)

    def serialize(self):
        return {
            "id": self.id,
            "username": self.username,
            "password": self.password
        }

class UserListResource(Resource):
    def get(self):
        users = User.query.all()
        return jsonify([user.serialize() for user in users])
    
    def post(self):
        data = request.get_json()
        print("Received data:", data)  # Add this line for debugging
        new_user = User(username=data['username'], password=data['password'])
        db.session.add(new_user)
        db.session.commit()
        return jsonify(new_user.serialize())


class UserResource(Resource):
    def get(self, user_id):
        user = User.query.get_or_404(user_id)
        return jsonify(user.serialize())

class LoginResource(Resource):
    def post(self):
        data = request.get_json()
        username = data.get('username')
        password = data.get('password')

        user = User.query.filter_by(username=username, password=password).first()
        if user:
            return jsonify({"message": "Login successful"})
        else:
            return jsonify({"message": "Login failed"}), 401

api.add_resource(UserListResource, '/users')
api.add_resource(UserResource, '/users/<int:user_id>')
api.add_resource(LoginResource, '/login')

if __name__ == '__main__':
    with app.app_context():
        db.create_all()
    app.run(debug=True)