from flask import Flask, render_template, redirect, request, session, url_for
from flask_sqlalchemy import SQLAlchemy
from flask_admin import Admin
from flask_admin.contrib.sqla import ModelView
from werkzeug.security import generate_password_hash, check_password_hash

app = Flask(__name__)
app.secret_key = 'bebra'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///Picture_Puzzle_web.db'
db = SQLAlchemy(app)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(100), unique=True, nullable=False)
    password = db.Column(db.String(100), nullable=False)
    email = db.Column(db.String(100), unique=True, nullable=False)
    
class Post(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    date_created = db.Column(db.String(100), unique=False, nullable=False)
    alias = db.Column(db.String(100), unique=True, nullable=False)
    title = db.Column(db.String(100), nullable=False)
    image = db.Column(db.String(100), nullable=False)

def create_tables():
    with app.app_context():
        db.create_all()

def register_admin_views():
    admin = Admin(app, name='Admin Panel', template_mode='bootstrap3')
    admin.add_view(ModelView(User, db.session))
    admin.add_view(ModelView(Post, db.session))

@app.route("/")
def index():
    latest_posts = Post.query.all()
    return render_template("index.html", latest_posts=latest_posts)

@app.route("/posts")
def all_posts():
    all_posts = Post.query.all()
    return render_template("posts.html", posts=all_posts)

@app.route("/about")
def about():
    return render_template("about.html")

@app.route("/posts/<alias>")
def post(alias):
    post_info = Post.query.filter_by(alias=alias).first()
    if post_info:
        return render_template(f"{alias}.html", post_info=post_info)
    else:
        return "Post not found", 404

@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, password=password).first()
        if user:
            session["username"] = username
            return redirect(url_for("index"))
    return render_template("auth/login.html")

@app.route("/logout")
def logout():
    session.pop("username", None)
    return redirect(url_for("index"))

@app.route("/register", methods=["GET", "POST"])
def register():
    if request.method == "POST":
        username = request.form["username"]
        email = request.form["email"]
        password = request.form["password"]
        new_user = User(username=username, email=email, password=password)
        db.session.add(new_user)
        db.session.commit()
        return redirect(url_for("login"))
    return render_template("auth/register.html")

if __name__ == '__main__':
    register_admin_views()
    app.run(debug=True)