from flask import Blueprint, render_template, redirect, url_for, flash, request, current_app
from flask_login import login_required, current_user
from app import db
from models import Product, Service, Category, Contact, FAQ, SiteSetting
from forms import ContactForm
from utils import initialize_site_settings

# Create blueprint
main_bp = Blueprint('main', __name__)

@main_bp.before_app_request
def setup_app():
    """Initialize app settings before first request"""
    # Only run initialization once
    if not getattr(setup_app, 'initialized', False):
        initialize_site_settings()
        setup_app.initialized = True

@main_bp.context_processor
def inject_settings():
    """Add site settings and common variables to all templates"""
    # Add site settings
    settings = {}
    site_settings = SiteSetting.query.all()
    for setting in site_settings:
        settings[setting.key] = setting.value
    
    # Add categories for navigation menu
    parent_categories = Category.query.filter_by(parent_id=None).all()
    
    # Add current date/time for copyright year
    from datetime import datetime
    now = datetime.utcnow()
    
    return dict(settings=settings, parent_categories=parent_categories, now=now)

@main_bp.route('/')
def index():
    """Home page"""
    # Get featured products
    featured_products = Product.query.filter_by(is_available=True).order_by(Product.created_at.desc()).limit(6).all()
    
    # Get services
    services = Service.query.filter_by(is_active=True).all()
    
    return render_template('index.html', 
                          featured_products=featured_products, 
                          services=services,
                          title="Accueil")

@main_bp.route('/about')
def about():
    """About page"""
    return render_template('about.html', title="À propos")

@main_bp.route('/products')
def products():
    """Products list page"""
    category_id = request.args.get('category', type=int)
    
    # Get all parent categories for filter sidebar
    parent_categories = Category.query.filter_by(parent_id=None).all()
    current_app.logger.info(f"Parent catégories trouvées: {parent_categories}")
    
    # Filter products by category if provided
    if category_id:
        category = Category.query.get_or_404(category_id)
        # Include subcategories
        if category.subcategories:
            subcategory_ids = [subcategory.id for subcategory in category.subcategories]
            subcategory_ids.append(category.id)
            products = Product.query.filter(Product.category_id.in_(subcategory_ids), 
                                          Product.is_available==True).all()
        else:
            products = Product.query.filter_by(category_id=category_id, is_available=True).all()
        
        title = f"Produits - {category.name}"
    else:
        products = Product.query.filter_by(is_available=True).all()
        current_app.logger.info(f"Nombre de produits trouvés: {len(products)}")
        for product in products:
            current_app.logger.info(f"Produit: {product.id} - {product.name} - {product.image_url}")
        title = "Tous nos produits"
    
    return render_template('products.html', 
                          products=products, 
                          parent_categories=parent_categories,
                          current_category_id=category_id,
                          title=title)

@main_bp.route('/product/<int:product_id>')
def product_detail(product_id):
    """Product detail page"""
    product = Product.query.get_or_404(product_id)
    
    # Get related products from same category
    related_products = Product.query.filter(
        Product.category_id == product.category_id,
        Product.id != product.id,
        Product.is_available == True
    ).limit(4).all()
    
    return render_template('product_detail.html', 
                          product=product, 
                          related_products=related_products,
                          title=product.name)

@main_bp.route('/services')
def services():
    """Services page"""
    all_services = Service.query.filter_by(is_active=True).all()
    return render_template('services.html', services=all_services, title="Nos services")

@main_bp.route('/contact', methods=['GET', 'POST'])
def contact():
    """Contact page with form"""
    form = ContactForm()
    
    if form.validate_on_submit():
        contact = Contact(
            name=form.name.data,
            email=form.email.data,
            phone=form.phone.data,
            message=form.message.data
        )
        db.session.add(contact)
        db.session.commit()
        
        flash('Votre message a bien été envoyé. Nous vous contacterons bientôt.', 'success')
        return redirect(url_for('main.contact'))
    
    return render_template('contact.html', form=form, title="Contact")
