from flask import Blueprint, render_template, request, jsonify, send_file
from flask_login import login_required, current_user
from services.ReportService import ReportService
from model.Report import ReportHelper

report_bp = Blueprint("report", __name__)

# ---------------- Report Page ----------------
@report_bp.route("/report")
@login_required
def report_page():
    return render_template("/report.html")


# ---------------- Search Contractor ----------------
@report_bp.route("/search_contractor", methods=["POST"])
@login_required
def search_contractor():

    data = ReportHelper.search_contractor(request)

    # Pagination (basic)
    page = int(request.form.get("page", 1))
    per_page = 20

    start = (page - 1) * per_page
    end = start + per_page

    paginated_data = data[start:end]

    return jsonify({
        "data": paginated_data,
        "total": len(data)
    })

# ---------------- Contractor Report by contractor id ----------------
@report_bp.route('/contractor_report/<int:contractor_id>')
@login_required
def contractor_report(contractor_id):

    service = ReportService(contractor_id=contractor_id).load_data()

    return render_template(
        'subcontractor_report.html',
        contractor_id=contractor_id,
        **service.get_web_data()
    )

# ---------------- Contractor Report by pmc no ----------------
@report_bp.route("/pmc_report/<pmc_no>")
@login_required
def pmc_report(pmc_no):

    service = ReportService(pmc_no=pmc_no).load_data()

    return render_template(
        "pmc_report.html",
        **service.get_web_data()
    )

# ---------------- Contractor Download Report by contractor id ----------------
@report_bp.route('/download_report/<int:contractor_id>')
@login_required
def download_report(contractor_id):

    service = ReportService(contractor_id=contractor_id).load_data()

    file, error = service.download_excel()

    if error:
        return error, 404

    return send_file(file, as_attachment=True)

# ---------------- Contractor Download Report by pmc no ----------------
@report_bp.route("/download_pmc_report/<pmc_no>")
@login_required
def download_pmc_report(pmc_no):

    service = ReportService(pmc_no=pmc_no).load_data()

    file, error = service.download_excel()
    if error:
        return error, 404

    return send_file(file, as_attachment=True)