from flask import Blueprint, render_template
from flask_login import login_required
from app.models import Project, PurchaseRequest, PurchaseOrder, Document, RevenueRecognition
from app import db
from decimal import Decimal

dashboard_bp = Blueprint('dashboard', __name__)

@dashboard_bp.route('/')
@login_required
def index():
    total_projects = Project.query.filter_by(status='active').count()
    total_pr = PurchaseRequest.query.filter_by(status='submitted').count()
    total_po = PurchaseOrder.query.filter_by(status='sent').count()
    total_docs = Document.query.count()

    projects = Project.query.filter_by(status='active').order_by(Project.created_at.desc()).limit(5).all()
    recent_pr = PurchaseRequest.query.order_by(PurchaseRequest.created_at.desc()).limit(5).all()
    recent_po = PurchaseOrder.query.order_by(PurchaseOrder.created_at.desc()).limit(5).all()

    # Total contract value across active projects
    total_contract = db.session.query(db.func.sum(Project.contract_value)).filter_by(status='active').scalar() or Decimal('0')
    total_recognized = db.session.query(
        db.func.sum(RevenueRecognition.recognized_amount)
    ).scalar() or Decimal('0')

    stats = {
        'total_projects': total_projects,
        'total_pr': total_pr,
        'total_po': total_po,
        'total_docs': total_docs,
        'total_contract': total_contract,
    }

    return render_template('dashboard/index.html',
                           stats=stats,
                           projects=projects,
                           recent_pr=recent_pr,
                           recent_po=recent_po)
