from flask import Flask, render_template, request, redirect, url_for, flash, jsonify
from datetime import datetime

app = Flask(__name__)
app.secret_key = 'quickfunding-2025-secret-key-xK9mP2'

LOAN_RATES = {
    'unsecured': 14.9,
    'personal':  10.9,
    'car':        6.9,
    'business':  12.9,
}

@app.context_processor
def inject_globals():
    return {'now': datetime.now()}

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

@app.route('/business-loan')
def business_loan():
    return render_template('business_loan.html')

@app.route('/personal-loan')
def personal_loan():
    return render_template('personal_loan.html')

@app.route('/car-loan')
def car_loan():
    return render_template('car_loan.html')
    
@app.route('/about')
def about():
    return render_template('about.html')

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

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


@app.route('/apply', methods=['GET', 'POST'])
def apply():
    prefill = {
        'amount':    request.args.get('amount', ''),
        'term':      request.args.get('term', ''),
        'loan_type': request.args.get('type', 'business'),
    }
    if request.method == 'POST':
        first_name = request.form.get('first_name', 'there')
        flash(
            f"Thank you, {first_name}! Your application has been received. "
            "Our team will contact you within 2 business hours.",
            'success'
        )
        return redirect(url_for('apply'))
    return render_template('apply.html', prefill=prefill)

@app.route('/calculator/compute', methods=['POST'])
def calculator_compute():
    data = request.get_json(silent=True)
    if not data:
        return jsonify({'error': 'Invalid request'}), 400
    try:
        principal    = float(data.get('principal', 0))
        annual_rate  = float(data.get('annual_rate', 12.9))
        term_months  = int(data.get('term_months', 36))
        monthly_rate = annual_rate / 100 / 12
        if monthly_rate == 0:
            payment = principal / term_months
        else:
            payment = principal * (monthly_rate * (1 + monthly_rate)**term_months) / ((1 + monthly_rate)**term_months - 1)
        total    = payment * term_months
        interest = total - principal
        return jsonify({
            'monthly':  round(payment, 2),
            'total':    round(total, 2),
            'interest': round(interest, 2),
        })
    except Exception as e:
        return jsonify({'error': str(e)}), 400

@app.errorhandler(404)
def not_found(e):
    return render_template('home.html'), 404

if __name__ == '__main__':
    import os
    port = int(os.environ.get('PORT', 5001))
    host = os.environ.get('HOST', '0.0.0.0')   # bind to all interfaces for network access
    debug = os.environ.get('DEBUG', 'true').lower() == 'true'
    print(f"\n🚀  Quick Funding running on http://{host}:{port}")
    print(f"    Local:    http://localhost:{port}")
    app.run(debug=debug, host=host, port=port)
