from flask import render_template, request, flash, redirect, url_for, jsonify
from app import app, db
from models import Contact
import logging

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

@app.route('/contact', methods=['POST'])
def contact():
    """Handle contact form submissions"""
    try:
        name = request.form.get('name', '').strip()
        email = request.form.get('email', '').strip()
        phone = request.form.get('phone', '').strip()
        service = request.form.get('service', '').strip()
        message = request.form.get('message', '').strip()
        
        # Basic validation
        if not name or not email or not message:
            flash('Please fill in all required fields.', 'error')
            return redirect(url_for('index') + '#contact')
        
        # Create new contact record
        contact_record = Contact(
            name=name,
            email=email,
            phone=phone,
            service=service,
            message=message
        )
        
        db.session.add(contact_record)
        db.session.commit()
        
        flash('Thank you for your message! We will get back to you soon.', 'success')
        logging.info(f"New contact form submission from {name} ({email})")
        
    except Exception as e:
        db.session.rollback()
        flash('There was an error submitting your message. Please try again.', 'error')
        logging.error(f"Error processing contact form: {str(e)}")
    
    return redirect(url_for('index') + '#contact')

@app.route('/about')
def about():
    """About page route"""
    return render_template('index.html', section='about')

@app.route('/services')
def services():
    """Services page route"""
    return render_template('index.html', section='services')

@app.route('/portfolio')
def portfolio():
    """Portfolio page route"""
    return render_template('index.html', section='portfolio')

@app.errorhandler(404)
def not_found_error(error):
    """Handle 404 errors"""
    return render_template('index.html'), 404

@app.errorhandler(500)
def internal_error(error):
    """Handle internal server errors"""
    db.session.rollback()
    return render_template('index.html'), 500
