from flask import Blueprint, render_template, request, jsonify
from flask_login import login_required
from app import db
from app.models import Project, ProjectCost, RevenueRecognition, PurchaseOrder, ProjectBudget, Vendor
from sqlalchemy import func, and_, extract
from decimal import Decimal
from datetime import datetime, date
import calendar

accounting_bp = Blueprint('accounting', __name__)

@accounting_bp.route('/laporan')
@login_required
def laporan():
    return render_template('accounting/laporan.html')

@accounting_bp.route('/laporan/project-cost')
@login_required
def laporan_project_cost():
    project_id = request.args.get('project_id')
    year = request.args.get('year', datetime.now().year)
    projects = Project.query.all()
    selected_project = None
    costs_by_category = []

    if project_id:
        selected_project = Project.query.get(project_id)
        costs_by_category = db.session.query(
            ProjectCost.cost_category,
            func.sum(ProjectCost.amount).label('total')
        ).filter_by(project_id=project_id).group_by(ProjectCost.cost_category).all()

    return render_template('accounting/project_cost.html',
                           projects=projects,
                           selected_project=selected_project,
                           costs_by_category=costs_by_category,
                           selected_year=year)

@accounting_bp.route('/laporan/revenue')
@login_required
def laporan_revenue():
    """Laporan Pengakuan Pendapatan PSAK 72"""
    projects = Project.query.all()
    revenue_data = []
    for p in projects:
        revenue_data.append({
            'project': p,
            'contract_value': p.contract_value,
            'recognized': p.recognized_revenue,
            'remaining': p.contract_value - p.recognized_revenue,
            'completion': p.completion_percentage
        })
    return render_template('accounting/revenue.html', revenue_data=revenue_data)

@accounting_bp.route('/laporan/budget-vs-actual')
@login_required
def laporan_budget_vs_actual():
    project_id = request.args.get('project_id')
    projects = Project.query.all()
    selected_project = None
    bva_data = []

    if project_id:
        from app.models import ProjectBudget
        selected_project = Project.query.get(project_id)
        budgets = db.session.query(
            ProjectBudget.cost_category,
            func.sum(ProjectBudget.amount).label('budget')
        ).filter_by(project_id=project_id).group_by(ProjectBudget.cost_category).all()

        for b in budgets:
            actual = db.session.query(func.sum(ProjectCost.amount)).filter_by(
                project_id=project_id, cost_category=b.cost_category
            ).scalar() or Decimal('0')
            variance = b.budget - actual
            bva_data.append({
                'category': b.cost_category,
                'budget': b.budget,
                'actual': actual,
                'variance': variance,
                'pct': round(float(actual / b.budget * 100), 1) if b.budget else 0
            })

    return render_template('accounting/budget_vs_actual.html',
                           projects=projects,
                           selected_project=selected_project,
                           bva_data=bva_data)
