from flask import Flask, render_template, redirect, url_for
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from .models import db, Vehicle, Repostaje
from .forms import VehicleForm, RepostajeForm

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///vehicles.db'
app.config['SECRET_KEY'] = 'mysecret'

db.init_app(app)
migrate = Migrate(app, db)

@app.route('/')
def index():
    vehicles = Vehicle.query.all()
    repostajes = Repostaje.query.all()
    return render_template('index.html', vehicles=vehicles, repostajes=repostajes)

@app.route('/add_vehicle', methods=['GET', 'POST'])
def add_vehicle():
    form = VehicleForm()
    if form.validate_on_submit():
        vehicle = Vehicle(license_plate=form.license_plate.data, model=form.model.data)
        db.session.add(vehicle)
        db.session.commit()
        return redirect(url_for('index'))
    return render_template('add_vehicle.html', form=form)

@app.route('/add_repostaje', methods=['GET', 'POST'])
def add_repostaje():
    form = RepostajeForm()
    form.vehicle_id.choices = [(v.id, v.license_plate) for v in Vehicle.query.all()]
    if form.validate_on_submit():
        repostaje = Repostaje(
            vehicle_id=form.vehicle_id.data, 
            amount=form.amount.data, 
            date=form.date.data,
            kilometers=form.kilometers.data,
            liters=form.liters.data,
            total_amount=form.total_amount.data
        )
        db.session.add(repostaje)
        db.session.commit()
        return redirect(url_for('index'))
    return render_template('add_repostaje.html', form=form)

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