from flask import Flask, render_template, redirect, url_for, request, flash
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user
from werkzeug.security import generate_password_hash, check_password_hash
import getpass,datetime 

app = Flask(__name__)
app.secret_key = 'your_secret_key'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///app.db'
db = SQLAlchemy(app)
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'

class User(UserMixin, db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(150), unique=True, nullable=False)
    password_hash = db.Column(db.String(150), nullable=False)
    must_change_password = db.Column(db.Boolean, default=True, nullable=False)

    def __init__(self, username, password, must_change_password=True):
        self.username = username
        self.password_hash = generate_password_hash(password)
        self.must_change_password = must_change_password

    def check_password(self, password):
        return check_password_hash(self.password_hash, password)

class UserRequest(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    url = db.Column(db.String(500), nullable=False)
    reason = db.Column(db.String(500), nullable=False)
    status = db.Column(db.String(50), nullable=False, default='pending')
    user = db.Column(db.String(150), nullable=False)
    mac_address = db.Column(db.String(50), nullable=False)
    ip_address = db.Column(db.String(50), nullable=False)
    timestamp = db.Column(db.DateTime, nullable=False)

@login_manager.user_loader
def load_user(user_id):
    return User.query.get(int(user_id))

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        user = User.query.filter_by(username=username).first()
        if user and user.check_password(password):
            login_user(user)
            if user.must_change_password:
                return redirect(url_for('change_password'))
            return redirect(url_for('admin'))
        else:
            flash('Invalid username or password')
    return render_template('login.html')

@app.route('/logout')
@login_required
def logout():
    logout_user()
    return redirect(url_for('login'))

@app.route('/change_password', methods=['GET', 'POST'])
@login_required
def change_password():
    if request.method == 'POST':
        new_password = request.form['new_password']
        current_user.password_hash = generate_password_hash(new_password)
        current_user.must_change_password = False
        db.session.commit()
        flash('Password changed successfully')
        return redirect(url_for('admin'))
    return render_template('change_password.html')

@app.route('/admin')
@login_required
def admin():
    requests = UserRequest.query.all()
    return render_template('admin.html', requests=requests)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/whitelist', methods=['POST'])
def whitelist():
    url = request.form['url']
    reason = request.form['reason']
    user = current_user.username if current_user.is_authenticated else 'anonymous'
    mac_address = '00:00:00:00:00:00'  # Placeholder, replace with actual MAC address retrieval logic
    ip_address = request.remote_addr  # Gets the IP address of the client
    timestamp = datetime.utcnow()
    new_request = UserRequest(url=url, reason=reason, user=user, mac_address=mac_address, ip_address=ip_address, timestamp=timestamp)
    db.session.add(new_request)
    db.session.commit()
    return redirect(url_for('index'))

def create_admin_user():
    admin_user = User.query.filter_by(username='admin').first()
    if not admin_user:
        print("No admin user found. Please set a password for the admin user.")
        password = getpass.getpass("Enter password for admin user: ")
        admin_user = User(username='admin', password=password)
        db.session.add(admin_user)
        db.session.commit()
        print("Admin user created successfully.")

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