"""
Companies Routes - GMAO Collège
Gestion des entreprises
"""
from flask import Blueprint, render_template, request, flash, redirect, url_for
from flask_login import login_required
from app_new.extensions import db
from ..core.models.company import Company

companies_bp = Blueprint('companies', __name__)

@companies_bp.route('/')
@login_required
def index():
    """Liste des entreprises."""
    page = request.args.get('page', 1, type=int)
    companies = Company.query.order_by(Company.name).paginate(page=page, per_page=20)
    return render_template('companies/index.html', companies=companies)

@companies_bp.route('/<int:id>')
@login_required
def detail(id):
    """Détail d'une entreprise."""
    company = Company.query.get_or_404(id)
    from ..core.models.maintenance import Intervention
    from ..core.models.maintenance import LotTask
    from ..contracts.models import ContractVisit
    interventions = Intervention.query.filter_by(company_id=id, is_deleted=False).all()
    preventive_tasks = LotTask.query.filter_by(company_id=id).order_by(LotTask.tache).all()
    visits = ContractVisit.query.join(ContractVisit.contract).filter(ContractVisit.contract.has(company_id=id)).order_by(ContractVisit.scheduled_date).all()
    return render_template('companies/detail.html', company=company, interventions=interventions, preventive_tasks=preventive_tasks, visits=visits)

@companies_bp.route('/new', methods=['GET', 'POST'])
@login_required
def create():
    """Créer une entreprise."""
    if request.method == 'POST':
        name = (request.form.get('name') or '').strip()
        if not name:
            flash('Le nom de l’entreprise est obligatoire.', 'danger')
            return render_template('companies/new.html', form_data=request.form), 400
        company = Company(
            name=name,
            address=request.form.get('address'),
            contact_phone=request.form.get('contact_phone') or request.form.get('phone'),
            contact_email=request.form.get('contact_email') or request.form.get('email'),
            contact_name=request.form.get('contact_name'),
            specialty=request.form.get('specialty'),
        )
        db.session.add(company)
        try:
            db.session.commit()
        except Exception:
            db.session.rollback()
            flash('Impossible d’enregistrer cette entreprise. Vérifiez les données saisies.', 'danger')
            return render_template('companies/new.html', form_data=request.form), 400
        flash('Entreprise créée avec succès.', 'success')
        return redirect(url_for('companies.index'))
    
    return render_template('companies/new.html')
