# app/quotes/routes.py
# This module implements the quote management features

import os
from datetime import datetime
from decimal import Decimal, ROUND_HALF_UP
from io import BytesIO
from flask import (
    Blueprint, render_template, request, redirect, url_for,
    flash, jsonify, abort, send_file, current_app
)
from sqlalchemy.exc import SQLAlchemyError
from flask_login import login_required, current_user
from sqlalchemy import func, or_, and_, case

from reportlab.lib import colors
from reportlab.lib.pagesizes import A4
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import mm
from reportlab.platypus import (
    SimpleDocTemplate, Table, TableStyle, Paragraph, Spacer, Image,
    ListFlowable, ListItem
)
from reportlab.pdfgen import canvas
from reportlab.lib.enums import TA_RIGHT
import re
import html
from xml.sax.saxutils import escape
from markupsafe import Markup
from datetime import date, datetime, timedelta
from .. import db
from ..utils import require_perm
from ..models import (
    Opportunity, Quote, QuoteItem, QuoteStatus,
    ApprovalRule, ApprovalRuleStep, QuoteApproval,
    Role, User, Client, ClientBranch, BranchContact,
    EmployeeProfile, LeadService, ProformaInvoice, Invoice, Currency,
    ProposalTermMaster, StateMaster, CountryMaster,
    PipelineStage, OpportunityStageHistory, OperationsJobcard, OperationsJobcardService,
    OperationsJobcardReopenRequest, JobcardServiceFieldMaster, OperationsJobcardFieldValue, SoftwareSaaSBilling, JobcardAdvanceBilling
)

quotes_bp = Blueprint("quotes", __name__, template_folder="../templates")
TWOPLACES = Decimal("0.01")
FOURPLACES = Decimal("0.0001")

# -------------------------
# VISIBILITY HELPERS (same as Leads)
# -------------------------

def _get_pipeline_stage_by_name(name: str):
    return PipelineStage.query.filter(func.lower(PipelineStage.name) == name.strip().lower()).first()

RECURRING_CYCLES = ("MONTHLY", "QUARTERLY", "HALF_YEARLY", "ANNUAL")


def _add_months(d, months):
    month = d.month - 1 + months
    year = d.year + month // 12
    month = month % 12 + 1

    days_in_month = [
        31,
        29 if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0) else 28,
        31, 30, 31, 30, 31, 31, 30, 31, 30, 31
    ]

    day = min(d.day, days_in_month[month - 1])
    return date(year, month, day)


def _cycle_months(cycle):
    cycle = _norm_cycle(cycle)

    if cycle == "MONTHLY":
        return 1
    if cycle == "QUARTERLY":
        return 3
    if cycle == "HALF_YEARLY":
        return 6
    if cycle == "ANNUAL":
        return 12

    return 0


def _quote_primary_recurring_cycle(q):
    if not q:
        return None

    items = q.items.order_by(QuoteItem.sort_order.asc(), QuoteItem.id.asc()).all()

    for it in items:
        cycle = _norm_cycle(getattr(it, "billing_cycle", None))
        if cycle in RECURRING_CYCLES:
            return cycle

    return None


def _quote_has_recurring_items(q):
    return _quote_primary_recurring_cycle(q) is not None


def _quote_anchor_date(q):
    if getattr(q, "proposal_confirmed_at", None):
        return q.proposal_confirmed_at.date()

    if getattr(q, "created_at", None):
        return q.created_at.date()

    return date.today()


def _renewal_root_quote(q):
    return q.renewal_source if getattr(q, "renewal_source_quote_id", None) else q


def _latest_renewal_quote(root_quote):
    return (
        Quote.query
        .filter(Quote.renewal_source_quote_id == root_quote.id)
        .order_by(Quote.renewal_period_start.desc(), Quote.id.desc())
        .first()
    )


def _next_renewal_period(root_quote):
    latest = _latest_renewal_quote(root_quote)

    base_quote = latest or root_quote
    cycle = _quote_primary_recurring_cycle(base_quote)

    if not cycle:
        return None, None, None

    months = _cycle_months(cycle)

    if latest and latest.renewal_period_start:
        start_date = _add_months(latest.renewal_period_start, months)
    else:
        start_date = _add_months(_quote_anchor_date(root_quote), months)

    end_date = _add_months(start_date, months) - timedelta(days=1)

    return cycle, start_date, end_date

def _move_opportunity_stage(opportunity, stage_name: str, changed_by_id: int, remark: str = ""):
    if not opportunity:
        return

    target_stage = _get_pipeline_stage_by_name(stage_name)
    if not target_stage:
        return

    if opportunity.stage_id == target_stage.id:
        return

    old_stage_id = opportunity.stage_id
    opportunity.stage_id = target_stage.id
    opportunity.updated_at = datetime.utcnow()
    db.session.flush()

    db.session.add(OpportunityStageHistory(
        opportunity_id=opportunity.id,
        from_stage_id=old_stage_id,
        to_stage_id=target_stage.id,
        changed_by_id=changed_by_id,
        remark=remark or f"Moved to {stage_name}"
    ))

def _proposal_pdf_page(canvas_obj, doc):
    canvas_obj.saveState()

    page_width, page_height = A4

    # top colored band
    canvas_obj.setFillColor(colors.HexColor("#0F4C81"))
    canvas_obj.rect(0, page_height - 12 * mm, page_width, 12 * mm, stroke=0, fill=1)

    # footer line
    canvas_obj.setStrokeColor(colors.HexColor("#D0D5DD"))
    canvas_obj.setLineWidth(0.5)
    canvas_obj.line(doc.leftMargin, 10 * mm, page_width - doc.rightMargin, 10 * mm)

    # footer text
    canvas_obj.setFont("Helvetica", 8)
    canvas_obj.setFillColor(colors.HexColor("#667085"))
    canvas_obj.drawString(doc.leftMargin, 6.5 * mm, "Crystal Nexus Proposal")

    # page number
    page_no = canvas_obj.getPageNumber()
    canvas_obj.drawRightString(page_width - doc.rightMargin, 6.5 * mm, f"Page {page_no}")

    canvas_obj.restoreState()

def _default_proposal_terms_text() -> str:
    rows = (
        ProposalTermMaster.query
        .filter_by(is_active=True)
        .order_by(ProposalTermMaster.sort_order.asc(), ProposalTermMaster.id.asc())
        .all()
    )

    parts = []
    for r in rows:
        txt = (r.term_text or "").strip()
        if txt:
            parts.append(txt)

    return "<br/>".join(parts)

def _sanitize_proposal_html(value: str) -> str:
    """
    Lightweight sanitizer for proposal rich text.
    Keeps basic formatting but removes dangerous HTML.
    """
    raw = value or ""

    # Remove dangerous blocks
    raw = re.sub(
        r"<\s*(script|style|iframe|object|embed)[^>]*>.*?<\s*/\s*\1\s*>",
        "",
        raw,
        flags=re.I | re.S
    )

    # Remove event handlers and javascript URLs
    raw = re.sub(r"\son\w+\s*=\s*(['\"]).*?\1", "", raw, flags=re.I | re.S)
    raw = re.sub(r"\son\w+\s*=\s*[^\s>]+", "", raw, flags=re.I)
    raw = re.sub(r"javascript\s*:", "", raw, flags=re.I)

    allowed_tags = {
        "p", "br", "b", "strong", "i", "em", "u",
        "ul", "ol", "li", "div", "span"
    }

    def clean_tag(match):
        tag = match.group(0)
        tag_name_match = re.match(r"</?\s*([a-zA-Z0-9]+)", tag)

        if not tag_name_match:
            return ""

        tag_name = tag_name_match.group(1).lower()

        if tag_name not in allowed_tags:
            return ""

        if tag.startswith("</"):
            return "</{}>".format(tag_name)

        if tag.endswith("/>") or tag_name == "br":
            return "<br/>"

        return "<{}>".format(tag_name)

    raw = re.sub(r"<[^>]+>", clean_tag, raw)
    return raw.strip()


def _proposal_html_to_plain_text(raw_html: str) -> str:
    """
    Converts proposal HTML to plain text for validation/fallback.
    """
    text = raw_html or ""

    text = re.sub(r"<\s*br\s*/?\s*>", "\n", text, flags=re.I)
    text = re.sub(r"<\s*li[^>]*>", "\n- ", text, flags=re.I)
    text = re.sub(r"</\s*(p|div|li|ul|ol)\s*>", "\n", text, flags=re.I)
    text = re.sub(r"<[^>]+>", "", text)
    text = html.unescape(text)
    text = text.replace(u"\xa0", " ")
    text = re.sub(r"\n{3,}", "\n\n", text)

    return text.strip()


def _strip_html_tags_keep_text(raw_html):
    """
    Converts editor HTML into safe text with temporary formatting tokens.
    This avoids broken ReportLab tags like '<i>' without '</i>'.
    """
    text = raw_html or ""

    text = text.replace("\r\n", "\n").replace("\r", "\n")

    # Normalize common blocks
    text = re.sub(r"<\s*br\s*/?\s*>", "\n", text, flags=re.I)
    text = re.sub(r"</\s*p\s*>", "\n", text, flags=re.I)
    text = re.sub(r"</\s*div\s*>", "\n", text, flags=re.I)
    text = re.sub(r"</\s*h[1-6]\s*>", "\n", text, flags=re.I)

    # Convert list items to bullet/number lines before stripping tags
    text = re.sub(r"<\s*li[^>]*>", "\n• ", text, flags=re.I)
    text = re.sub(r"</\s*li\s*>", "", text, flags=re.I)
    text = re.sub(r"</?\s*(ul|ol)[^>]*>", "\n", text, flags=re.I)

    # Temporary tokens for allowed inline formatting
    text = re.sub(r"<\s*(strong|b)[^>]*>", "___B_OPEN___", text, flags=re.I)
    text = re.sub(r"</\s*(strong|b)\s*>", "___B_CLOSE___", text, flags=re.I)

    text = re.sub(r"<\s*(em|i)[^>]*>", "___I_OPEN___", text, flags=re.I)
    text = re.sub(r"</\s*(em|i)\s*>", "___I_CLOSE___", text, flags=re.I)

    text = re.sub(r"<\s*u[^>]*>", "___U_OPEN___", text, flags=re.I)
    text = re.sub(r"</\s*u\s*>", "___U_CLOSE___", text, flags=re.I)

    # Remove all remaining tags
    text = re.sub(r"<[^>]+>", "", text)

    text = html.unescape(text)
    text = text.replace(u"\xa0", " ")

    return text


def _balance_reportlab_inline_tags(text):
    """
    Keeps only correctly paired ReportLab inline tags.
    If formatting is broken, it removes that formatting instead of crashing PDF.
    """
    replacements = [
        ("___B_OPEN___", "___B_CLOSE___", "<b>", "</b>"),
        ("___I_OPEN___", "___I_CLOSE___", "<i>", "</i>"),
        ("___U_OPEN___", "___U_CLOSE___", "<u>", "</u>"),
    ]

    for open_token, close_token, open_tag, close_tag in replacements:
        open_count = text.count(open_token)
        close_count = text.count(close_token)

        if open_count != close_count:
            text = text.replace(open_token, "").replace(close_token, "")
        else:
            text = text.replace(open_token, open_tag).replace(close_token, close_tag)

    return text


def _safe_reportlab_paragraph_text(text):
    """
    Escapes user text and restores only safe ReportLab inline tags.
    """
    text = text or ""

    text = text.replace("<b>", "___SAFE_B_OPEN___").replace("</b>", "___SAFE_B_CLOSE___")
    text = text.replace("<i>", "___SAFE_I_OPEN___").replace("</i>", "___SAFE_I_CLOSE___")
    text = text.replace("<u>", "___SAFE_U_OPEN___").replace("</u>", "___SAFE_U_CLOSE___")

    text = escape(text)

    text = text.replace("___SAFE_B_OPEN___", "<b>").replace("___SAFE_B_CLOSE___", "</b>")
    text = text.replace("___SAFE_I_OPEN___", "<i>").replace("___SAFE_I_CLOSE___", "</i>")
    text = text.replace("___SAFE_U_OPEN___", "<u>").replace("___SAFE_U_CLOSE___", "</u>")

    return text


def _html_blocks_to_pdf_flowables(raw_html, styles):
    """
    Converts proposal rich text into safe ReportLab flowables.
    Supports:
    - normal paragraphs
    - bullet points
    - bold
    - italics
    - underline

    This version prevents ReportLab crashes from broken tags.
    """
    flowables = []

    raw_html = _sanitize_proposal_html(raw_html or "")
    text = _strip_html_tags_keep_text(raw_html)
    text = _balance_reportlab_inline_tags(text)

    lines = []
    for line in text.split("\n"):
        line = line.strip()
        if line:
            lines.append(line)

    if not lines:
        flowables.append(Paragraph("—", styles["SmallMuted"]))
        return flowables

    normal_buffer = []
    bullet_items = []

    def flush_normal():
        if not normal_buffer:
            return

        paragraph_lines = []
        for item in normal_buffer:
            safe_item = _safe_reportlab_paragraph_text(item)
            if safe_item.strip():
                paragraph_lines.append(safe_item)

        if paragraph_lines:
            flowables.append(Paragraph("<br/>".join(paragraph_lines), styles["Body"]))
            flowables.append(Spacer(1, 4))

        del normal_buffer[:]

    def flush_bullets():
        if not bullet_items:
            return

        flowables.append(ListFlowable(
            bullet_items[:],
            bulletType="bullet",
            leftIndent=16,
            bulletIndent=6,
            bulletFontName="Helvetica",
            bulletFontSize=9,
        ))
        flowables.append(Spacer(1, 5))

        del bullet_items[:]

    for line in lines:
        is_bullet = (
            line.startswith("•")
            or line.startswith("- ")
            or line.startswith("* ")
        )

        if is_bullet:
            flush_normal()

            clean_line = line.lstrip("•").strip()
            clean_line = re.sub(r"^[-*]\s+", "", clean_line).strip()

            if clean_line:
                bullet_items.append(
                    ListItem(
                        Paragraph(
                            _safe_reportlab_paragraph_text(clean_line),
                            styles["Body"]
                        ),
                        leftIndent=8
                    )
                )
        else:
            flush_bullets()
            normal_buffer.append(line)

    flush_normal()
    flush_bullets()

    if not flowables:
        flowables.append(Paragraph("—", styles["SmallMuted"]))

    return flowables


def _norm_text(v):
    return " ".join(str(v or "").strip().lower().split())


def _state_name_from_obj(obj):
    """
    Returns the best available normalized state name from an object
    that may have:
    - state_master relationship
    - state_id
    - state text column
    """
    if not obj:
        return ""

    state_master = getattr(obj, "state_master", None)
    if state_master and getattr(state_master, "name", None):
        return _norm_text(state_master.name)

    state_id = getattr(obj, "state_id", None)
    if state_id:
        sm = db.session.get(StateMaster, state_id)
        if sm and sm.name:
            return _norm_text(sm.name)

    return _norm_text(getattr(obj, "state", None))


def _quote_billing_state_name(q):
    """
    Highest-trust customer billing state source:
    1. linked quote branch master/text
    2. opportunity branch
    3. opportunity lead branch
    4. quote.billing_state text fallback
    """
        # fallback direct branch state text
    raw_state = getattr(q.branch, "state", None)
    if raw_state:
        return _norm_text(raw_state)

    if getattr(q, "opportunity", None):
        if getattr(q.opportunity, "branch", None):
            name = _state_name_from_obj(q.opportunity.branch)
            if name:
                return name

        if getattr(q.opportunity, "lead", None) and getattr(q.opportunity.lead, "branch", None):
            name = _state_name_from_obj(q.opportunity.lead.branch)
            if name:
                return name

    return _norm_text(getattr(q, "billing_state", None))

def _gst_registration_type_from_quote(q):
    sources = []

    if getattr(q, "branch", None):
        sources.append(q.branch)

    if getattr(q, "opportunity", None):
        if getattr(q.opportunity, "branch", None):
            sources.append(q.opportunity.branch)

        if getattr(q.opportunity, "lead", None) and getattr(q.opportunity.lead, "branch", None):
            sources.append(q.opportunity.lead.branch)

    for branch in sources:
        gst_type = _norm_text(getattr(branch, "gst_registration_type", None))
        if gst_type:
            return gst_type

    return ""

def _calculate_tax_components(q: Quote):
    """
    Returns: (cgst, sgst, igst, total_tax)

    GST rules:
    - GST only when currency == INR AND is_gst_applicable == True
    - SEZ without payment of TAX => No GST
    - SEZ with payment of TAX => IGST 18%
    - Regular B2B => CGST+SGST if same state, else IGST
    """

    try:
        subtotal = _d(q.subtotal, "0")
        discount = _d(q.discount, "0")
        taxable = subtotal - discount
        if taxable < 0:
            taxable = Decimal("0")
    except Exception:
        taxable = Decimal("0")

    TWOPLACES = Decimal("0.01")

    currency = (q.currency or "INR").strip().upper()
    if currency != "INR" or not getattr(q, "is_gst_applicable", False):
        return (Decimal("0"), Decimal("0"), Decimal("0"), Decimal("0"))

    gst_registration_type = _gst_registration_type_from_quote(q)

    sez_without_tax_values = {
        "sezwop",
        "sez without payment",
        "sez without payment of tax",
        "sez without tax",
        "sez w/o payment of tax",
    }
    sez_with_tax_values = {
        "sezwp",
        "sez with payment",
        "sez with payment of tax",
        "sez with tax",
    }

    if gst_registration_type in sez_without_tax_values:
        return (Decimal("0"), Decimal("0"), Decimal("0"), Decimal("0"))

    if gst_registration_type in sez_with_tax_values:
        igst = (taxable * Decimal("0.18")).quantize(TWOPLACES)
        return (Decimal("0"), Decimal("0"), igst, igst)

    company_state = _state_name_from_obj(getattr(q, "company_branch", None))
    billing_state = _quote_billing_state_name(q)

    if not company_state or not billing_state:
        igst = (taxable * Decimal("0.18")).quantize(TWOPLACES)
        return (Decimal("0"), Decimal("0"), igst, igst)

    if company_state == billing_state:
        cgst = (taxable * Decimal("0.09")).quantize(TWOPLACES)
        sgst = (taxable * Decimal("0.09")).quantize(TWOPLACES)
        total_tax = cgst + sgst
        return (cgst, sgst, Decimal("0"), total_tax)

    igst = (taxable * Decimal("0.18")).quantize(TWOPLACES)
    return (Decimal("0"), Decimal("0"), igst, igst)


def _opportunity_has_any_invoice(opportunity_id: int) -> bool:
    if not opportunity_id:
        return False
    return (
        db.session.query(Invoice.id)
        .join(Quote, Quote.id == Invoice.quote_id)
        .filter(Quote.opportunity_id == opportunity_id)
        .filter(Invoice.status != "Cancelled")
        .limit(1)
        .scalar()
        is not None
    )

def _team_user_ids(manager_user_id: int, include_self: bool = True):
    """
    Returns a list of user_ids in the manager's reporting tree.
    include_self=True includes the manager_user_id in the returned list.
    """
    seen = set([manager_user_id]) if include_self else set()
    stack = [manager_user_id]

    while stack:
        mid = stack.pop()
        rows = (
            EmployeeProfile.query
            .filter(EmployeeProfile.reporting_manager_user_id == mid)
            .with_entities(EmployeeProfile.user_id)
            .all()
        )
        for (uid,) in rows:
            if uid is not None and uid not in seen:
                seen.add(uid)
                stack.append(uid)

    return list(seen)


def _allowed_sales_user_ids():
    """
    Who can the current user see?
    - quotes.view_all => everyone (None = no restriction)
    - else => self + reportees
    """
    if current_user.has_perm("quotes.view_all"):
        return None
    return _team_user_ids(current_user.id, include_self=True)


def _can_access_quote(q: Quote) -> bool:
    allowed = _allowed_sales_user_ids()
    if allowed is None:
        return True

    if q.created_by_id == current_user.id:
        return True

    opp_owner = q.opportunity.owner_id if q.opportunity else None
    return (opp_owner in set(allowed)) if opp_owner else False


def _require_quote_access(q: Quote):
    if not _can_access_quote(q):
        abort(403)


def _require_opp_access(opp: Opportunity):
    allowed = _allowed_sales_user_ids()
    if allowed is None:
        return
    if opp.owner_id not in set(allowed):
        abort(403)

# -------------------------
# Helpers
# -------------------------
def _safe_commit():
    try:
        db.session.commit()
        return True
    except SQLAlchemyError:
        db.session.rollback()
        raise

def _quote_code_next():
    last = Quote.query.order_by(Quote.id.desc()).first()
    nxt = (last.id + 1) if last else 1
    return f"QT-{nxt:06d}"


def _d(val, default="0", places=TWOPLACES):
    """
    Safe Decimal conversion with configurable rounding.
    Default is 2 decimals for normal amounts.
    Use FOURPLACES for rates.
    """
    if val is None:
        return Decimal(default).quantize(places, rounding=ROUND_HALF_UP)

    s = str(val).strip().replace(",", "")

    if s == "":
        return Decimal(default).quantize(places, rounding=ROUND_HALF_UP)

    try:
        return Decimal(s).quantize(places, rounding=ROUND_HALF_UP)
    except Exception:
        return Decimal(default).quantize(places, rounding=ROUND_HALF_UP)


ALLOWED_BILLING = {"ONETIME", "MONTHLY", "QUARTERLY", "HALF_YEARLY", "ANNUAL"}

BILLING_MULT = {
    "ONETIME": Decimal("1"),
    "MONTHLY": Decimal("1"),
    "QUARTERLY": Decimal("3"),
    "HALF_YEARLY": Decimal("6"),
    "ANNUAL": Decimal("12"),
}


def _norm_cycle(v: str) -> str:
    v = (v or "ONETIME").strip().upper()
    return v if v in ALLOWED_BILLING else "ONETIME"


def _recalc_quote(quote: Quote):
    TWOPLACES = Decimal("0.01")
    subtotal = Decimal("0")
    
    for it in quote.items.all():
        qty = _d(it.qty, "0", TWOPLACES)
        rate = _d(it.rate, "0", FOURPLACES)

        cycle = _norm_cycle(getattr(it, "billing_cycle", None))
        it.billing_cycle = cycle  # keep normalized in DB

        mult = BILLING_MULT.get(cycle, Decimal("1"))

        if getattr(it, "is_flat_cost", False):
            it.amount = rate.quantize(TWOPLACES)
        else:
            it.amount = (qty * rate * mult).quantize(TWOPLACES)

        subtotal += _d(it.amount, "0")

    quote.subtotal = subtotal.quantize(TWOPLACES)
    discount = _d(quote.discount, "0")

    # ✅ Calculate GST automatically
    cgst, sgst, igst, total_tax = _calculate_tax_components(quote)

    quote.tax = total_tax
    quote.cgst = cgst
    quote.sgst = sgst
    quote.igst = igst

    quote.total = (
        quote.subtotal - discount + total_tax
    ).quantize(TWOPLACES, rounding=ROUND_HALF_UP)

    quote.total_amount = _d(quote.total, "0")



def _latest_approved_reopen(q: Quote):
    if not q:
        return None
    return (
        OperationsJobcardReopenRequest.query
        .filter_by(quote_id=q.id, status="Approved")
        .order_by(OperationsJobcardReopenRequest.id.desc())
        .first()
    )


def _quote_is_in_reopened_billing_cycle(q: Quote) -> bool:
    """True while a reopened invoiced quote is waiting for its new invoice."""
    return bool(
        _latest_approved_reopen(q)
        and getattr(q, "invoice_request_status", None) != "Approved"
    )

def _quote_has_active_invoice(q: Quote) -> bool:
    return (
        Invoice.query
        .filter_by(quote_id=q.id)
        .filter(Invoice.status != "Cancelled")
        .first()
        is not None
    )


def _quote_is_edit_locked(q: Quote) -> bool:
    status_name = q.status.name if q.status else ""

    if _quote_has_active_invoice(q) and not _quote_is_in_reopened_billing_cycle(q):
        return True

    if status_name in ("Pending Approval", "Selected"):
        return True

    # Sent quotes are editable only after proposal confirmation and before invoice.
    if status_name == "Sent" and not getattr(q, "proposal_confirmed_at", None):
        return True

    return False


def _ensure_jobcard_field_values_for_service(jc_service):
    """
    Ensures OperationsJobcardFieldValue rows exist for a jobcard service line.

    This is important when quote items are added after jobcard creation.
    New OperationsJobcardService rows must also get their service-wise
    JobcardServiceFieldMaster field rows.
    """
    if not jc_service or not jc_service.service_id:
        return

    fields = (
        JobcardServiceFieldMaster.query
        .filter_by(service_id=jc_service.service_id, is_active=True)
        .order_by(
            JobcardServiceFieldMaster.sort_order.asc(),
            JobcardServiceFieldMaster.id.asc()
        )
        .all()
    )

    if not fields:
        return

    existing_field_master_ids = {
        row.field_master_id
        for row in OperationsJobcardFieldValue.query
        .filter_by(jobcard_service_id=jc_service.id)
        .all()
    }

    for field in fields:
        if field.id in existing_field_master_ids:
            continue

        db.session.add(OperationsJobcardFieldValue(
            jobcard_service_id=jc_service.id,
            field_master_id=field.id,
            field_key=field.field_key,
            field_value=None,
            file_path=None,
        ))

def _sync_open_jobcard_from_quote(q: Quote, update_assignments=True):
    # Historical invoices must normally lock/suppress quote -> jobcard sync.
    # Exception: when an invoiced jobcard has been formally reopened after a
    # Credit Note, the same quote enters a fresh billing cycle. In that cycle
    # new/edited QuoteItems must be reconciled into OperationsJobcardService
    # rows so Operations can process the additional work.
    if _quote_has_active_invoice(q) and not _quote_is_in_reopened_billing_cycle(q):
        return

    jobcard = (
        OperationsJobcard.query
        .filter_by(quote_id=q.id)
        .order_by(OperationsJobcard.id.desc())
        .first()
    )

    if not jobcard:
        return

    if jobcard.status in ("Ready For Billing", "Closure Approval Pending", "Closed"):
        return

    quote_items = q.items.order_by(
        QuoteItem.sort_order.asc(),
        QuoteItem.id.asc()
    ).all()

    active_quote_item_ids = {item.id for item in quote_items}

    # DELETE stale jobcard service lines
    for svc in jobcard.services.all():
        try:
            assignments = svc.assignments.all()
        except Exception:
            assignments = []

        has_active_assignments = any(
            ass.status not in ("Cancelled", "Closed")
            for ass in assignments
        )

        if has_active_assignments:
            continue

        should_delete = False

        if svc.quote_item_id and svc.quote_item_id not in active_quote_item_ids:
            should_delete = True

        if not svc.quote_item_id:
            should_delete = True

        if should_delete and svc.status not in ("Completed", "QC Pending", "Closed"):
            OperationsJobcardFieldValue.query.filter_by(
                jobcard_service_id=svc.id
            ).delete(synchronize_session=False)

            db.session.delete(svc)

    db.session.flush()

    existing_by_quote_item_id = {
        row.quote_item_id: row
        for row in jobcard.services.all()
        if row.quote_item_id
    }

    for item in quote_items:
        service_name = item.service.name if getattr(item, "service", None) else None
        jc_service = existing_by_quote_item_id.get(item.id)

        if jc_service:
            service_changed = jc_service.service_id != item.service_id

            jc_service.service_id = item.service_id
            jc_service.service_name = service_name

            if jc_service.status not in ("Completed", "QC Pending", "Closed"):
                jc_service.total_quantity = item.qty or 0

            if service_changed or item.service_id:
                _ensure_jobcard_field_values_for_service(jc_service)

        else:
            jc_service = OperationsJobcardService(
                jobcard_id=jobcard.id,
                quote_item_id=item.id,
                service_id=item.service_id,
                service_name=service_name,
                status="Submitted",
                total_quantity=item.qty or 0,
                completed_quantity=0,
                checklist_status="Pending",
            )
            db.session.add(jc_service)
            db.session.flush()

            _ensure_jobcard_field_values_for_service(jc_service)

        if update_assignments:
            # IMPORTANT: quote/service edits must never mutate quantities that
            # Operations has already assigned.  A partial assignment is a
            # historical operational commitment and remains exactly as entered;
            # only the service line total quantity follows the edited QuoteItem.
            try:
                assignments = jc_service.assignments.all()
            except Exception:
                assignments = []

            active_assigned_qty = sum(
                (Decimal(str(ass.assigned_qty or 0)) for ass in assignments
                 if ass.status not in ("Cancelled", "Replaced", "Rejected", "Closed")),
                Decimal("0")
            )
            service_total_qty = Decimal(str(jc_service.total_quantity or 0))

            if jc_service.status not in ("Completed", "QC Pending", "Closed"):
                if active_assigned_qty <= 0:
                    jc_service.status = "Submitted"
                elif active_assigned_qty < service_total_qty:
                    jc_service.status = "Partially Assigned"
                elif active_assigned_qty == service_total_qty:
                    jc_service.status = "Assigned"
                else:
                    jc_service.status = "Over Assigned"


    if hasattr(jobcard, "updated_at"):
        jobcard.updated_at = datetime.utcnow()

def _sync_quote_ops_status(q: Quote):
    jc = (
        OperationsJobcard.query
        .filter_by(quote_id=q.id)
        .order_by(OperationsJobcard.id.desc())
        .first()
    )

    if not jc:
        q.ops_assignment_status = "Pending Jobcard"
        return

    q.ops_assignment_status = jc.status

def _get_status(name: str):
    return QuoteStatus.query.filter_by(name=name).first()

def _get_currency_obj(code: str):
    code = (code or "INR").strip().upper()
    return Currency.query.filter(func.upper(Currency.code) == code).first()


def _currency_label_from_quote(q: Quote):
    """
    Returns a dict:
    {
        "code": "USD",
        "symbol": "$",
        "display": "$",
        "full": "USD ($)"
    }
    """
    code = (getattr(q, "currency", None) or "INR").strip().upper()
    row = _get_currency_obj(code)

    symbol = ""
    if row and getattr(row, "symbol", None):
        symbol = (row.symbol or "").strip()

    display = symbol or code
    full = f"{code} ({symbol})" if symbol and symbol != code else code

    return {
        "code": code,
        "symbol": symbol,
        "display": display,
        "full": full,
    }

def _company_display_from_quote(q: Quote) -> dict:
    cb = getattr(q, "company_branch", None)

    company_name = "Company"
    branch_name = ""
    address_parts = []
    logo_path = None
    gst_no = ""
    pan_no = ""
    state_name = ""
    country_name = ""

    if cb:
        company = getattr(cb, "company", None)

        company_name = (
            getattr(company, "name", None)
            or getattr(company, "company_name", None)
            or "Company"
        )

        branch_name = (
            getattr(cb, "branch_name", None)
            or getattr(cb, "name", None)
            or ""
        )

        # Prefer proper branch master fields
        branch_address = (
            getattr(cb, "branch_address", None)
            or getattr(cb, "address", None)
            or ""
        )
        city = getattr(cb, "city", None) or ""
        pin_code = getattr(cb, "pin_code", None) or ""

        # State from master first, then text
        if getattr(cb, "state_master", None) and getattr(cb.state_master, "name", None):
            state_name = cb.state_master.name.strip()
        else:
            state_name = (getattr(cb, "state", None) or "").strip()

        # Country from master first, then text
        if getattr(cb, "country_master", None) and getattr(cb.country_master, "name", None):
            country_name = cb.country_master.name.strip()
        else:
            country_name = (getattr(cb, "country", None) or "").strip()

        gst_no = (
            getattr(cb, "gst_no", None)
            or getattr(cb, "gst", None)
            or ""
        )

        if company:
            pan_no = (
                getattr(company, "pan", None)
                or ""
            )

        for val in [branch_address, city, state_name, country_name, pin_code]:
            if val:
                address_parts.append(str(val).strip())

        if company:
            raw_logo = (
                getattr(company, "logo", None)
                or getattr(company, "logo_path", None)
                or getattr(company, "logo_file", None)
                or getattr(company, "company_logo", None)
            )

            if raw_logo:
                raw_logo = str(raw_logo).strip()

                if os.path.isabs(raw_logo) and os.path.exists(raw_logo):
                    logo_path = raw_logo
                elif os.path.exists(os.path.join(current_app.static_folder, raw_logo)):
                    logo_path = os.path.join(current_app.static_folder, raw_logo)
                elif os.path.exists(os.path.join(current_app.static_folder, "uploads", raw_logo)):
                    logo_path = os.path.join(current_app.static_folder, "uploads", raw_logo)
                elif os.path.exists(raw_logo):
                    logo_path = raw_logo

    if not logo_path:
        fallback_logo = os.path.join(current_app.static_folder, "img", "company_logo.png")
        if os.path.exists(fallback_logo):
            logo_path = fallback_logo

    return {
        "company_name": company_name,
        "branch_name": branch_name,
        "address": ", ".join([x for x in address_parts if x]),
        "logo_path": logo_path,
        "gst_no": gst_no,
        "pan_no": pan_no,
        "state_name": state_name,
        "country_name": country_name,
    }
def _client_display_from_quote(q: Quote) -> dict:
    client = getattr(q, "client", None)
    branch = getattr(q, "branch", None)
    opp = getattr(q, "opportunity", None)

    client_name = (
        getattr(client, "company_name", None)
        or (getattr(opp, "company", None) if opp else None)
        or "—"
    )

    contact_name = (getattr(opp, "contact_name", None) if opp else None) or "—"
    contact_email = (getattr(opp, "contact_email", None) if opp else None) or "—"
    contact_phone = (getattr(opp, "contact_phone", None) if opp else None) or "—"

    branch_parts = []
    if branch:
        for val in [
            getattr(branch, "branch_location", None),
            getattr(branch, "address", None),
            getattr(branch, "city", None),
            getattr(branch, "state", None),
            getattr(branch, "country", None),
            getattr(branch, "pin_code", None),
        ]:
            if val:
                branch_parts.append(str(val).strip())

    return {
        "client_name": client_name,
        "branch_text": ", ".join([x for x in branch_parts if x]) or "—",
        "gst": getattr(branch, "gst", None) or getattr(q, "billing_gstin", None) or "—",
        "contact_name": contact_name,
        "contact_email": contact_email,
        "contact_phone": contact_phone,
    }


def _matching_rules(total_amount: Decimal):
    rules = (ApprovalRule.query
             .filter_by(is_active=True)
             .order_by(ApprovalRule.sort_order.asc(), ApprovalRule.id.asc())
             .all())

    matched = []
    for r in rules:
        if total_amount < _d(r.min_amount, "0"):
            continue
        if r.max_amount is not None and total_amount > _d(r.max_amount, "0"):
            continue
        matched.append(r)
    return matched


def _user_can_act_on(qa: QuoteApproval) -> bool:
    if qa.approver_user_id and qa.approver_user_id == current_user.id:
        return True

    role_name = current_user.role.name if getattr(current_user, "role", None) else ""
    if qa.approver_role and qa.approver_role == role_name:
        return True

    return False


def _activate_next_step_if_any(q: Quote):
    nxt = (q.approvals
           .filter_by(status="WAITING")
           .order_by(QuoteApproval.step_order.asc(), QuoteApproval.id.asc())
           .first())
    if nxt:
        nxt.status = "PENDING"
        db.session.commit()


# -------------------------
# Create quote from opportunity
# -------------------------
@quotes_bp.route("/opportunity/<int:opp_id>/new", methods=["GET", "POST"])
@login_required
@require_perm("quotes.create")
def create_quote(opp_id):
    opp = Opportunity.query.get_or_404(opp_id)
    _require_opp_access(opp)

    draft = _get_status("Draft")

    if request.method == "POST":
        est_closure_raw = request.form.get("estimated_closure_date")
        estimated_closure_date = (
            datetime.strptime(est_closure_raw, "%Y-%m-%d").date()
            if est_closure_raw else None
        )

        linked_branch = None
        if getattr(opp, "branch", None):
            linked_branch = opp.branch
        elif getattr(opp, "lead", None) and getattr(opp.lead, "branch", None):
            linked_branch = opp.lead.branch
        elif getattr(opp, "lead", None) and opp.lead.branch_id:
            linked_branch = db.session.get(ClientBranch, opp.lead.branch_id)

        q = Quote(
            quote_code=_quote_code_next(),
            version=1,
            opportunity_id=opp.id,
            status_id=draft.id if draft else None,
            created_by_id=current_user.id,
            company_branch_id=current_user.company_branch_id,
            client_id=opp.client_id or (opp.lead.client_id if getattr(opp, "lead", None) else None),
            branch_id=opp.branch_id or (opp.lead.branch_id if getattr(opp, "lead", None) else None),
            billing_state=(
                linked_branch.state_master.name
                if linked_branch and getattr(linked_branch, "state_master", None)
                else (linked_branch.state if linked_branch else None)
            ),
            billing_gstin=(linked_branch.gst if linked_branch else None),
            currency=(request.form.get("currency") or "INR").strip().upper(),
            is_gst_applicable=True if (request.form.get("currency") or "INR").strip().upper() == "INR" else False,
            customer_notes=(request.form.get("customer_notes") or "").strip(),
            notes=(request.form.get("notes") or "").strip(),
            discount=Decimal("0"),
            tax=Decimal("0"),
            subtotal=Decimal("0"),
            total=Decimal("0"),
            total_amount=Decimal("0"),
            estimated_closure_date=estimated_closure_date,
        )
        db.session.add(q)
        _safe_commit()

        # ✅ set defaults (billing_cycle/service_id)
        db.session.add(QuoteItem(
            quote_id=q.id,
            item_name="Item 1",
            description="",
            qty=Decimal("1"),
            rate=Decimal("0"),
            is_flat_cost=False,
            amount=Decimal("0"),
            sort_order=1,
            service_id=None,
            billing_cycle="ONETIME",
        ))
        _safe_commit()

        _recalc_quote(q)

        if q.opportunity:
            _move_opportunity_stage(
                q.opportunity,
                "Proposal",
                changed_by_id=current_user.id,
                remark=f"Auto: Quote {q.quote_code} created"
            )

        _safe_commit()

        flash("Quote created (Draft) ✅", "success")
        return redirect(url_for("quotes.edit_quote", quote_id=q.id))
    
    currencies = (Currency.query.filter_by(is_active=True)
              .order_by(Currency.sort_order.asc(), Currency.code.asc())
              .all())

    return render_template(
        "quotes/new.html",
        opp=opp,
        currencies=currencies,   # ✅ add
        default_estimated_closure_date=opp.expected_close_date,
        today=datetime.utcnow().date()
    )


def _current_saas_billing_jobcard(quote):
    """Return the exact recurring SaaS Jobcard currently driving billing.

    SaaS deliberately reuses the source quotation across billing cycles, therefore
    quote-wide "latest PI/invoice" lookups are unsafe.  Request-context pointers
    remain the first choice, but after Finance generates a PI those pointers may no
    longer be sufficient to identify the open cycle.  In that case the latest open
    SoftwareSaaSBilling row is the authoritative source.

    This helper only returns recurring SaaS Jobcards and therefore does not alter
    normal Translation/Operations quotation behaviour.
    """
    # 1) Exact request context, when present.
    for attr in ("invoice_requested_jobcard_id", "pi_requested_jobcard_id"):
        jobcard_id = getattr(quote, attr, None)
        if not jobcard_id:
            continue
        billing = SoftwareSaaSBilling.query.filter_by(jobcard_id=jobcard_id).first()
        if not billing:
            continue
        jobcard = OperationsJobcard.query.filter_by(id=jobcard_id, quote_id=quote.id).first()
        if jobcard:
            return jobcard

    # 2) Fallback to the latest *open* recurring SaaS billing cycle for this quote.
    #    An open cycle has a Jobcard but has not yet been linked to its final invoice.
    billing = (SoftwareSaaSBilling.query
               .join(SoftwareSaaSBilling.jobcard)
               .filter(OperationsJobcard.quote_id == quote.id)
               .filter(SoftwareSaaSBilling.jobcard_id.isnot(None))
               .filter(SoftwareSaaSBilling.invoice_id.is_(None))
               .order_by(SoftwareSaaSBilling.billing_date.desc(),
                         SoftwareSaaSBilling.id.desc())
               .first())
    if billing and billing.jobcard:
        return billing.jobcard

    return None


# -------------------------
# View quote
# -------------------------
@quotes_bp.route("/<int:quote_id>")
@login_required
@require_perm("quotes.view")
def view_quote(quote_id):
    q = Quote.query.get_or_404(quote_id)
    _require_quote_access(q)

    _recalc_quote(q)
    db.session.commit()

    items = q.items.order_by(QuoteItem.sort_order.asc()).all()

    # Completed advance billing remains in Jobcard billing history and must not
    # masquerade as the final PI/Invoice on the quotation screen.
    latest_pi = (ProformaInvoice.query
                 .filter_by(quote_id=q.id, advance_billing_id=None)
                 .filter(ProformaInvoice.status != "Cancelled")
                 .order_by(ProformaInvoice.id.desc())
                 .first())

    latest_invoice = (Invoice.query.join(ProformaInvoice, Invoice.pi_id == ProformaInvoice.id)
                      .filter(Invoice.quote_id == q.id, Invoice.status != "Cancelled",
                              ProformaInvoice.advance_billing_id.is_(None))
                      .order_by(Invoice.id.desc())
                      .first())

    active_advance = (JobcardAdvanceBilling.query
                      .filter(JobcardAdvanceBilling.quote_id == q.id,
                              JobcardAdvanceBilling.status.in_(["PI_REQUESTED", "PI_RAISED", "INVOICE_REQUESTED"]))
                      .order_by(JobcardAdvanceBilling.id.desc()).first())
    if active_advance:
        if active_advance.pi:
            latest_pi = active_advance.pi
        latest_invoice = active_advance.invoice

    # Recurring SaaS uses the same commercial quotation for every billing cycle.
    # Resolve the PI/Invoice against the exact current billing Jobcard so an older
    # invoice on the source quote does not hide Request Invoice for the new cycle.
    saas_context_jobcard = _current_saas_billing_jobcard(q)
    if saas_context_jobcard:
        latest_pi = (ProformaInvoice.query
                     .filter_by(quote_id=q.id, jobcard_id=saas_context_jobcard.id)
                     .filter(ProformaInvoice.status != "Cancelled")
                     .order_by(ProformaInvoice.id.desc())
                     .first())
        latest_invoice = (Invoice.query
                          .filter_by(quote_id=q.id, jobcard_id=saas_context_jobcard.id)
                          .filter(Invoice.status != "Cancelled")
                          .order_by(Invoice.id.desc())
                          .first())

    reopened_billing_cycle = _quote_is_in_reopened_billing_cycle(q)
    if reopened_billing_cycle:
        # Historical documents remain in the database, but the quote screen
        # should drive the fresh PI -> Invoice cycle created by the reopen.
        if getattr(q, "pi_request_status", None) in (None, "Pending"):
            latest_pi = None
        if getattr(q, "invoice_request_status", None) in (None, "Pending"):
            latest_invoice = None

    currencies = (Currency.query.filter_by(is_active=True)
                  .order_by(Currency.sort_order.asc(), Currency.code.asc())
                  .all())

    countries = (CountryMaster.query
                 .filter_by(is_active=True)
                 .order_by(CountryMaster.name.asc())
                 .all())

    states = (StateMaster.query
              .filter_by(is_active=True)
              .order_by(StateMaster.name.asc())
              .all())

    subtotal_dec = Decimal(q.subtotal or 0)
    discount_dec = Decimal(q.discount or 0)
    taxable_dec = subtotal_dec - discount_dec

    if taxable_dec < 0:
        taxable_dec = Decimal("0")
    
    jobcard_exists = (
        OperationsJobcard.query
        .filter_by(quote_id=q.id)
        .first()
        is not None
    )

    return render_template(
        "quotes/view.html",
        q=q,
        items=items,
        today=datetime.utcnow().date(),
        latest_pi=latest_pi,
        latest_invoice=latest_invoice,
        currencies=currencies,
        countries=countries,
        states=states,
        taxable_dec=taxable_dec,
        Decimal=Decimal,
        jobcard_exists=jobcard_exists,
        reopened_billing_cycle=reopened_billing_cycle
    )
# -------------------------
# Edit quote
# -------------------------
@quotes_bp.route("/<int:quote_id>/edit", methods=["GET", "POST"])
@login_required
@require_perm("quotes.edit")
def edit_quote(quote_id):
    q = Quote.query.get_or_404(quote_id)
    _require_quote_access(q)

    if _quote_is_edit_locked(q):
        flash("Quote is locked in current status or invoice is already generated.", "warning")
        return redirect(url_for("quotes.view_quote", quote_id=q.id))
        
    # Ensure quote has a company branch for GST
    if not q.company_branch_id and getattr(current_user, "company_branch_id", None):
        q.company_branch_id = current_user.company_branch_id
    if not q.branch_id and getattr(q, "opportunity", None):
        q.branch_id = q.opportunity.branch_id or (q.opportunity.lead.branch_id if getattr(q.opportunity, "lead", None) else None)

    if not q.client_id and getattr(q, "opportunity", None):
        q.client_id = q.opportunity.client_id or (q.opportunity.lead.client_id if getattr(q.opportunity, "lead", None) else None)

    if not q.billing_state and getattr(q, "branch", None):
        q.billing_state = (
            q.branch.state_master.name
            if getattr(q.branch, "state_master", None)
            else q.branch.state
        )

    if not q.billing_gstin and getattr(q, "branch", None):
        q.billing_gstin = q.branch.gst

    if request.method == "POST":
        q.currency = (request.form.get("currency") or "INR").strip().upper()

        # ✅ INR-only GST toggle
        if q.currency != "INR":
            q.is_gst_applicable = False
        else:
            q.is_gst_applicable = True if request.form.get("is_gst_applicable") == "1" else False

        q.discount = max(
            Decimal("0"),
            _d(request.form.get("discount"), "0")
        )
        q.customer_notes = (request.form.get("customer_notes") or "").strip()
        q.notes = (request.form.get("notes") or "").strip()
        q.billing_state = (request.form.get("billing_state") or "").strip() or None
        q.billing_gstin = (request.form.get("billing_gstin") or "").strip() or None
        
        if not q.company_branch_id and getattr(current_user, "company_branch_id", None):
            q.company_branch_id = current_user.company_branch_id

        est_closure_raw = request.form.get("estimated_closure_date")
        q.estimated_closure_date = (
            datetime.strptime(est_closure_raw, "%Y-%m-%d").date()
            if est_closure_raw else None
        )

        item_ids = request.form.getlist("item_id")
        for idx, item_id in enumerate(item_ids):
            if not str(item_id).isdigit():
                continue

            it = db.session.get(QuoteItem, int(item_id))
            if not it or it.quote_id != q.id:
                continue

            it.item_name = (request.form.get(f"item_name_{item_id}") or "").strip()
            it.description = (request.form.get(f"item_desc_{item_id}") or "").strip()
            it.qty = max(
                Decimal("1"),
                _d(request.form.get(f"item_qty_{item_id}"), "1")
            )
            it.rate = max(
                Decimal("0"),
                _d(request.form.get(f"item_rate_{item_id}"), "0", FOURPLACES)
            )
            it.is_flat_cost = True if request.form.get(f"item_is_flat_cost_{item_id}") == "1" else False
            raw_service = (request.form.get(f"item_service_id_{item_id}") or "").strip()
            it.service_id = int(raw_service) if raw_service.isdigit() else None

            it.billing_cycle = _norm_cycle(request.form.get(f"item_billing_cycle_{item_id}") or "ONETIME")
            it.sort_order = idx + 1

        _recalc_quote(q)
        _sync_open_jobcard_from_quote(q)
        _safe_commit()

        flash("Quote updated ✅", "success")
        return redirect(url_for("quotes.edit_quote", quote_id=q.id))

    _recalc_quote(q)
    _safe_commit()

    items = q.items.order_by(QuoteItem.sort_order.asc()).all()
    services = (LeadService.query
                .filter_by(is_active=True)
                .order_by(LeadService.sort_order.asc(), LeadService.name.asc())
                .all())
    currencies = (Currency.query.filter_by(is_active=True)
              .order_by(Currency.sort_order.asc(), Currency.code.asc())
              .all())

    return render_template("quotes/edit.html", q=q, items=items, services=services, currencies=currencies)


# -------------------------
# Add item
# -------------------------
@quotes_bp.route("/<int:quote_id>/items/add", methods=["GET"])
@login_required
@require_perm("quotes.edit")
def add_item(quote_id):
    q = Quote.query.get_or_404(quote_id)
    _require_quote_access(q)

    if _quote_is_edit_locked(q):
        flash("Quote is locked in current status or invoice is already generated.", "warning")
        return redirect(url_for("quotes.view_quote", quote_id=q.id))

    db.session.add(QuoteItem(
        quote_id=q.id,
        item_name=f"Item {q.items.count() + 1}",
        description="",
        qty=Decimal("1"),
        rate=Decimal("0"),
        is_flat_cost=False,
        amount=Decimal("0"),
        sort_order=q.items.count() + 1,
        service_id=None,
        billing_cycle="ONETIME",
    ))
    _recalc_quote(q)
    _sync_open_jobcard_from_quote(q)
    db.session.commit()

    flash("Item added ✅", "success")
    return redirect(url_for("quotes.edit_quote", quote_id=q.id))

# -------------------------
# Delete item
# -------------------------
@quotes_bp.route("/<int:quote_id>/items/<int:item_id>/delete", methods=["POST"])
@login_required
@require_perm("quotes.edit")
def delete_item(quote_id, item_id):
    q = Quote.query.get_or_404(quote_id)
    _require_quote_access(q)

    if _quote_is_edit_locked(q):
        flash("Quote is locked in current status or invoice is already generated.", "warning")
        return redirect(url_for("quotes.view_quote", quote_id=q.id))

    it = QuoteItem.query.get_or_404(item_id)
    if it.quote_id != q.id:
        abort(400)

    item_count = q.items.count()
    if item_count <= 1:
        flash("At least one quote item must remain.", "warning")
        return redirect(url_for("quotes.edit_quote", quote_id=q.id))

    linked_jobcard_services = OperationsJobcardService.query.filter_by(
        quote_item_id=it.id
    ).all()

    for svc in linked_jobcard_services:
        assignment_count = 0
        try:
            assignment_count = svc.assignments.count()
        except Exception:
            assignment_count = 0

        if assignment_count == 0:
            db.session.delete(svc)
        else:
            svc.status = "Cancelled"
            svc.service_name = (svc.service_name or "") + " - Removed from Quote"
            svc.total_quantity = 0
            svc.completed_quantity = 0

    db.session.flush()

    db.session.delete(it)
    db.session.flush()

    remaining_items = q.items.order_by(
        QuoteItem.sort_order.asc(),
        QuoteItem.id.asc()
    ).all()

    for idx, row in enumerate(remaining_items, start=1):
        row.sort_order = idx

    _recalc_quote(q)
    _sync_open_jobcard_from_quote(q)
    db.session.commit()

    flash("Quote item deleted ✅", "success")
    return redirect(url_for("quotes.edit_quote", quote_id=q.id))

# -------------------------
# Auto-save item (AJAX)
# -------------------------
@quotes_bp.route("/<int:quote_id>/items/<int:item_id>/autosave", methods=["POST"])
@login_required
@require_perm("quotes.edit")
def autosave_item(quote_id, item_id):
    q = Quote.query.get_or_404(quote_id)
    _require_quote_access(q)

    it = QuoteItem.query.get_or_404(item_id)
    if it.quote_id != q.id:
        return jsonify({"ok": False, "error": "Invalid item"}), 400

    if _quote_is_edit_locked(q):
        return jsonify({"ok": False, "error": "Quote locked or invoice already generated"}), 400

    data = request.get_json(force=True) or {}

    # item fields
    it.item_name = (data.get("item_name") or "").strip()
    it.description = (data.get("description") or "").strip()
    it.qty = max(
        Decimal("1"),
        _d(data.get("qty"), "1")
    )
    it.rate = max(
        Decimal("0"),
        _d(data.get("rate"), "0", FOURPLACES)
    )

    it.is_flat_cost = True if str(data.get("is_flat_cost", "0")) in ("1", "true", "True", "on") else False

    raw_service = data.get("service_id")
    it.service_id = int(raw_service) if str(raw_service).isdigit() else None
    it.billing_cycle = _norm_cycle(data.get("billing_cycle") or it.billing_cycle or "ONETIME")

    # quote fields (global)
    q.discount = max(
        Decimal("0"),
        _d(data.get("discount"), str(q.discount or 0))
    )

    raw = (data.get("estimated_closure_date") or "").strip()
    q.estimated_closure_date = (
        datetime.strptime(raw, "%Y-%m-%d").date()
        if raw else None
    )

    # ✅ NEW: billing fields so GST can be calculated even for new leads
    q.billing_state = (data.get("billing_state") or "").strip() or None
    q.billing_gstin = (data.get("billing_gstin") or "").strip() or None
    # optional: if you send currency in autosave payload
    if "currency" in data:
        q.currency = (data.get("currency") or q.currency or "INR").strip().upper()

    # ✅ INR-only GST toggle
    if (q.currency or "INR").strip().upper() != "INR":
        q.is_gst_applicable = False
    else:
        q.is_gst_applicable = True if str(data.get("is_gst_applicable", "1")) in ("1", "true", "True") else False

    # ✅ ensure branch exists so GST can compute
    if not q.company_branch_id and getattr(current_user, "company_branch_id", None):
        q.company_branch_id = current_user.company_branch_id
    if not q.branch_id and getattr(q, "opportunity", None):
        q.branch_id = q.opportunity.branch_id or (q.opportunity.lead.branch_id if getattr(q.opportunity, "lead", None) else None)

    if not q.client_id and getattr(q, "opportunity", None):
        q.client_id = q.opportunity.client_id or (q.opportunity.lead.client_id if getattr(q.opportunity, "lead", None) else None)

    if not q.billing_state and getattr(q, "branch", None):
        q.billing_state = (
            q.branch.state_master.name
            if getattr(q.branch, "state_master", None)
            else q.branch.state
        )

    if not q.billing_gstin and getattr(q, "branch", None):
        q.billing_gstin = q.branch.gst

    _recalc_quote(q)
    _sync_open_jobcard_from_quote(q)
    _safe_commit()

    return jsonify({
        "ok": True,
        "item_amount": str(it.amount or 0),
        "subtotal": str(q.subtotal or 0),
        "discount": str(q.discount or 0),
        "cgst": str(q.cgst or 0),
        "sgst": str(q.sgst or 0),
        "igst": str(q.igst or 0),
        "tax": str(q.tax or 0),
        "total": str(q.total or 0),
    })

# -------------------------
# Request approval
# -------------------------
@quotes_bp.route("/<int:quote_id>/request-approval", methods=["POST"])
@login_required
@require_perm("quotes.request_approval")
def request_approval(quote_id):
    q = Quote.query.get_or_404(quote_id)
    _require_quote_access(q)

    _recalc_quote(q)
    _safe_commit()

    if q.status and q.status.name in ("Pending Approval", "Approved", "Sent", "Selected"):
        flash("Quote is locked. You cannot request approval in current status.", "warning")
        return redirect(url_for("quotes.view_quote", quote_id=q.id))

    existing_pending = q.approvals.filter(
        QuoteApproval.status.in_(["WAITING", "PENDING"])
    ).count()

    if existing_pending > 0:
        flash("Approval workflow already exists for this quote.", "warning")
        return redirect(url_for("quotes.view_quote", quote_id=q.id))

    rules = _matching_rules(_d(q.total, "0"))

    # ✅ If no rule matched → No approval required → Auto Approve
    if not rules:
        approved = _get_status("Approved")
        if approved:
            q.status_id = approved.id
            _safe_commit()

        flash("No approval required for this amount. Quote auto-approved ✅", "success")
        return redirect(url_for("quotes.view_quote", quote_id=q.id))

    QuoteApproval.query.filter_by(quote_id=q.id).delete(synchronize_session=False)
    _safe_commit()

    global_step = 0
    created_any = False

    for r in rules:
        steps = (ApprovalRuleStep.query
                 .filter_by(rule_id=r.id, is_active=True)
                 .order_by(ApprovalRuleStep.step_order.asc(), ApprovalRuleStep.id.asc())
                 .all())

        if not steps:
            flash(f"Rule '{r.name}' has no steps. Add steps in Approval Rules.", "danger")
            return redirect(url_for("quotes.edit_quote", quote_id=q.id))

        for s in steps:
            global_step += 1
            db.session.add(QuoteApproval(
                quote_id=q.id,
                rule_id=r.id,
                rule_step_id=s.id,
                step_order=global_step,
                approver_role=s.approver_role,
                approver_user_id=s.approver_user_id,
                status="WAITING"
            ))
            created_any = True

    if not created_any:
        flash("No approval steps created. Please check rules/steps.", "danger")
        return redirect(url_for("quotes.edit_quote", quote_id=q.id))

    _safe_commit()

    first = (q.approvals
             .filter_by(status="WAITING")
             .order_by(QuoteApproval.step_order.asc(), QuoteApproval.id.asc())
             .first())
    if first:
        first.status = "PENDING"
        _safe_commit()

    pending = _get_status("Pending Approval")
    if pending:
        q.status_id = pending.id
        _safe_commit()

    flash("Approval requested ✅ (Sequential flow started)", "success")
    return redirect(url_for("quotes.view_quote", quote_id=q.id))


# -------------------------
# Approvals inbox
# -------------------------
@quotes_bp.route("/approvals")
@login_required
@require_perm("quotes.approve")
def approvals_inbox():
    role_name = current_user.role.name if getattr(current_user, "role", None) else ""
    show_waiting = (request.args.get("show_waiting") or "").strip() in ("1", "true", "yes", "on")

    statuses = ["PENDING"]
    if show_waiting:
        statuses.append("WAITING")

    assigned_filter = or_(
        QuoteApproval.approver_user_id == current_user.id,
        and_(QuoteApproval.approver_user_id.is_(None), QuoteApproval.approver_role == role_name),
    )

    status_order = case(
        (QuoteApproval.status == "PENDING", 0),
        (QuoteApproval.status == "WAITING", 1),
        else_=2,
    )

    items = (QuoteApproval.query
             .filter(QuoteApproval.status.in_(statuses))
             .filter(assigned_filter)
             .order_by(status_order.asc(),
                       QuoteApproval.created_at.desc(),
                       QuoteApproval.quote_id.desc(),
                       QuoteApproval.step_order.asc(),
                       QuoteApproval.id.asc())
             .all())

    return render_template("quotes/approvals.html", items=items)


# -------------------------
# Approve / reject
# -------------------------
@quotes_bp.route("/approval/<int:approval_id>/act", methods=["POST"])
@login_required
@require_perm("quotes.approve")
def act_on_approval(approval_id):
    a = QuoteApproval.query.get_or_404(approval_id)
    q = a.quote

    _require_quote_access(q)

    if a.status != "PENDING":
        flash("This approval is not pending.", "warning")
        return redirect(url_for("quotes.approvals_inbox"))

    if not _user_can_act_on(a):
        flash("You are not allowed to approve this step.", "danger")
        return redirect(url_for("quotes.approvals_inbox"))

    decision = request.form.get("decision")
    remark = (request.form.get("remark") or "").strip()

    if decision not in ("APPROVE", "REJECT"):
        flash("Invalid decision.", "danger")
        return redirect(url_for("quotes.approvals_inbox"))

    a.status = "APPROVED" if decision == "APPROVE" else "REJECTED"
    a.remark = remark
    a.acted_by_id = current_user.id
    a.acted_at = datetime.utcnow()
    _safe_commit()

    if decision == "REJECT":
        q.approvals.filter(QuoteApproval.status.in_(["WAITING", "PENDING"])) \
                  .update({"status": "CANCELLED"}, synchronize_session=False)
        _safe_commit()

        q.proposal_confirmed_at = None
        rej = _get_status("Rejected")
        if rej:
            q.status_id = rej.id
            _safe_commit()

        flash("Quote rejected ❌", "warning")
        return redirect(url_for("quotes.approvals_inbox"))

    _activate_next_step_if_any(q)

    pending_left = q.approvals.filter_by(status="PENDING").count()
    waiting_left = q.approvals.filter_by(status="WAITING").count()

    if pending_left == 0 and waiting_left == 0:
        appr = _get_status("Approved")
        if appr:
            q.status_id = appr.id
            _safe_commit()
        flash("All approvals completed ✅ Quote Approved", "success")

    return redirect(url_for("quotes.approvals_inbox"))


# =========================================================
# ✅ PROPOSAL WORKFLOW (only after Selected)
# =========================================================
@quotes_bp.route("/<int:quote_id>/proposal", methods=["GET", "POST"])
@login_required
@require_perm("quotes.edit")
def proposal_builder(quote_id):
    q = Quote.query.get_or_404(quote_id)
    _require_quote_access(q)

    if not q.status or q.status.name not in ("Approved", "Selected", "Sent"):
        flash("Proposal can be viewed only after Quote is Approved, Selected, or Sent.", "danger")
        return redirect(url_for("quotes.view_quote", quote_id=q.id))

    if q.status.name == "Sent":
        items = q.items.order_by(QuoteItem.sort_order.asc()).all()
        return render_template(
            "quotes/proposal_builder.html",
            q=q,
            items=items,
            readonly=True,
            currency_meta=_currency_label_from_quote(q)
        )

    if request.method == "POST":
        terms = _sanitize_proposal_html(request.form.get("proposal_terms") or "")
        if not _proposal_html_to_plain_text(terms):
            flash("Please add Terms & Conditions.", "danger")
            return redirect(url_for("quotes.proposal_builder", quote_id=q.id))

        # IMPORTANT:
        # store the company branch mapped to the user creating the proposal
        if getattr(current_user, "company_branch_id", None):
            q.company_branch_id = current_user.company_branch_id

        q.proposal_terms = terms
        q.proposal_created_at = datetime.utcnow()
        q.proposal_created_by_id = current_user.id
        db.session.commit()

        flash("Proposal saved ✅ You can download and then mark as Sent.", "success")
        return redirect(url_for("quotes.proposal_builder", quote_id=q.id))

    # If proposal is being opened and branch is blank, default it from current user
    if not q.company_branch_id and getattr(current_user, "company_branch_id", None):
        q.company_branch_id = current_user.company_branch_id
        db.session.commit()

    if not (q.proposal_terms or "").strip():
        q.proposal_terms = _default_proposal_terms_text()
        db.session.commit()

    items = q.items.order_by(QuoteItem.sort_order.asc()).all()
    return render_template(
        "quotes/proposal_builder.html",
        q=q,
        items=items,
        readonly=False,
        currency_meta=_currency_label_from_quote(q)
    )

@quotes_bp.route("/proposal-terms-master", methods=["GET", "POST"])
@login_required
@require_perm("approval_rules.manage")
def proposal_terms_master():
    action = request.form.get("action") if request.method == "POST" else None

    if request.method == "POST":
        if action == "create":
            term_text = _sanitize_proposal_html(request.form.get("term_text") or "")
            sort_order = int(request.form.get("sort_order") or 1)
            is_active = True if request.form.get("is_active") == "1" else False

            if not _proposal_html_to_plain_text(term_text):
                flash("Term text is required.", "danger")
                return redirect(url_for("quotes.proposal_terms_master"))

            db.session.add(ProposalTermMaster(
                term_text=term_text,
                sort_order=sort_order,
                is_active=is_active
            ))
            db.session.commit()
            flash("Default proposal term added ✅", "success")
            return redirect(url_for("quotes.proposal_terms_master"))

        if action == "update":
            term_id = int(request.form.get("term_id"))
            row = ProposalTermMaster.query.get_or_404(term_id)

            term_text = _sanitize_proposal_html(request.form.get("term_text") or "")
            sort_order = int(request.form.get("sort_order") or 1)
            is_active = True if request.form.get("is_active") == "1" else False

            if not _proposal_html_to_plain_text(term_text):
                flash("Term text is required.", "danger")
                return redirect(url_for("quotes.proposal_terms_master"))

            row.term_text = term_text
            row.sort_order = sort_order
            row.is_active = is_active
            db.session.commit()
            flash("Default proposal term updated ✅", "success")
            return redirect(url_for("quotes.proposal_terms_master"))

        if action == "delete":
            term_id = int(request.form.get("term_id"))
            row = ProposalTermMaster.query.get_or_404(term_id)
            db.session.delete(row)
            db.session.commit()
            flash("Default proposal term deleted ✅", "success")
            return redirect(url_for("quotes.proposal_terms_master"))

    rows = ProposalTermMaster.query.order_by(
        ProposalTermMaster.sort_order.asc(),
        ProposalTermMaster.id.asc()
    ).all()

    return render_template("quotes/proposal_terms_master.html", rows=rows)

@quotes_bp.route("/<int:quote_id>/proposal/download", methods=["GET"])
@login_required
@require_perm("quotes.view")
def download_proposal(quote_id):
    q = Quote.query.get_or_404(quote_id)
    _require_quote_access(q)

    if not q.status or q.status.name not in ("Approved", "Selected", "Sent"):
        flash("Proposal download is allowed only for Approved/Selected/Sent quotes.", "danger")
        return redirect(url_for("quotes.view_quote", quote_id=q.id))

    if not getattr(q, "proposal_created_at", None):
        flash("Proposal not created yet.", "danger")
        return redirect(url_for("quotes.proposal_builder", quote_id=q.id))

    _recalc_quote(q)
    db.session.commit()

    items = q.items.order_by(QuoteItem.sort_order.asc()).all()
    currency_meta = _currency_label_from_quote(q)
    currency_prefix = currency_meta["display"]

    def _money(val):
        try:
            v = Decimal(str(val or 0))
        except Exception:
            v = Decimal("0")
        from app.utils import indian_amount
        return indian_amount(v)
    
    def _rate(val):
        try:
            v = Decimal(str(val or 0))
        except Exception:
            v = Decimal("0")
        from app.utils import indian_amount
        return indian_amount(v, 4)

    def _rate_with_currency(val):
        return f"{currency_prefix} {_rate(val)}"

    def _money_with_currency(val):
        return f"{currency_prefix} {_money(val)}"

    creator = db.session.get(User, q.proposal_created_by_id) if getattr(q, "proposal_created_by_id", None) else None
    creator_name = (getattr(creator, "name", None) or "—") if creator else "—"
    creator_email = (getattr(creator, "email", None) or "—") if creator else "—"

    if not q.company_branch_id and creator and getattr(creator, "company_branch_id", None):
        q.company_branch_id = creator.company_branch_id
        db.session.commit()

    company_info = _company_display_from_quote(q)
    client_info = _client_display_from_quote(q)

    buff = BytesIO()
    doc = SimpleDocTemplate(
        buff,
        pagesize=A4,
        leftMargin=18 * mm,
        rightMargin=18 * mm,
        topMargin=22 * mm,
        bottomMargin=18 * mm,
        title=f"Proposal {q.quote_code}",
    )

    styles = getSampleStyleSheet()
    styles.add(ParagraphStyle(name="SmallMuted", fontSize=8.5, leading=11, textColor=colors.HexColor("#667085")))
    styles.add(ParagraphStyle(name="Body", fontSize=9.5, leading=12, textColor=colors.HexColor("#101828")))
    styles.add(ParagraphStyle(name="Label", fontSize=8.5, leading=10, textColor=colors.HexColor("#667085")))
    styles.add(ParagraphStyle(name="SectionTitle", fontSize=11.5, leading=14, textColor=colors.HexColor("#101828"), spaceAfter=4))
    styles.add(ParagraphStyle(name="DocTitle", fontSize=16, leading=18, alignment=TA_RIGHT, textColor=colors.HexColor("#101828")))
    styles.add(ParagraphStyle(name="Right", fontSize=9.5, leading=12, alignment=TA_RIGHT, textColor=colors.HexColor("#101828")))

    story = []

    logo_flowable = None
    if company_info.get("logo_path") and os.path.exists(company_info["logo_path"]):
        try:
            logo_flowable = Image(company_info["logo_path"], width=28 * mm, height=14 * mm)
        except Exception:
            logo_flowable = None

    company_text_lines = [f"<b>{company_info['company_name']}</b>"]

    if company_info.get("branch_name"):
        company_text_lines.append(company_info["branch_name"])

    if company_info.get("address"):
        company_text_lines.append(company_info["address"])

    if company_info.get("gst_no"):
        company_text_lines.append(f"GSTIN: {company_info['gst_no']}")

    if company_info.get("pan_no"):
        company_text_lines.append(f"PAN: {company_info['pan_no']}")

    left_data = []
    if logo_flowable:
        left_data.append([logo_flowable])
    left_data.append([Paragraph("<br/>".join(company_text_lines), styles["Body"])])

    header_left = Table(left_data, colWidths=[88 * mm])
    header_left.setStyle(TableStyle([
        ("VALIGN", (0, 0), (-1, -1), "TOP"),
        ("LEFTPADDING", (0, 0), (-1, -1), 0),
        ("RIGHTPADDING", (0, 0), (-1, -1), 0),
        ("TOPPADDING", (0, 0), (-1, -1), 0),
        ("BOTTOMPADDING", (0, 0), (-1, -1), 2),
    ]))

    header_right = Table([
        [Paragraph("<b>PROPOSAL</b>", styles["DocTitle"])],
        [Paragraph(
            f"Quote: {q.quote_code}<br/>"
            f"Version: {q.version}<br/>"
            f"Currency: {currency_meta['full']}<br/>"
            f"Generated: {q.proposal_created_at.strftime('%d-%b-%Y %H:%M')}",
            styles["Right"]
        )]
    ], colWidths=[88 * mm])
    header_right.setStyle(TableStyle([
        ("VALIGN", (0, 0), (-1, -1), "TOP"),
        ("ALIGN", (0, 0), (-1, -1), "RIGHT"),
        ("LEFTPADDING", (0, 0), (-1, -1), 0),
        ("RIGHTPADDING", (0, 0), (-1, -1), 0),
        ("TOPPADDING", (0, 0), (-1, -1), 0),
        ("BOTTOMPADDING", (0, 0), (-1, -1), 2),
    ]))

    header_tbl = Table([[header_left, header_right]], colWidths=[88 * mm, 88 * mm])
    header_tbl.setStyle(TableStyle([
        ("VALIGN", (0, 0), (-1, -1), "TOP"),
        ("LINEBELOW", (0, 0), (-1, -1), 0.8, colors.HexColor("#D0D5DD")),
        ("BOTTOMPADDING", (0, 0), (-1, -1), 8),
    ]))
    story.append(header_tbl)
    story.append(Spacer(1, 10))

    opp = q.opportunity

    client_box = Table([
        [Paragraph("<b>Client / Opportunity</b>", styles["SectionTitle"])],
        [Paragraph(
            f"<b>Opportunity:</b> {(opp.opp_code + ' - ' + opp.title) if opp else '—'}<br/>"
            f"<b>Client Company:</b> {client_info['client_name']}<br/>"
            f"<b>Client Branch:</b> {client_info['branch_text']}<br/>"
            f"<b>Client GST:</b> {client_info['gst']}<br/>"
            f"<b>Contact:</b> {client_info['contact_name']}<br/>"
            f"<b>Email:</b> {client_info['contact_email']}<br/>"
            f"<b>Phone:</b> {client_info['contact_phone']}",
            styles["Body"]
        )]
    ], colWidths=[176 * mm])
    client_box.setStyle(TableStyle([
        ("BACKGROUND", (0, 0), (-1, -1), colors.white),
        ("BOX", (0, 0), (-1, -1), 0.6, colors.HexColor("#E4E7EC")),
        ("ROUNDRECT", (0, 0), (-1, -1), 6, colors.HexColor("#E4E7EC")),
        ("LEFTPADDING", (0, 0), (-1, -1), 8),
        ("RIGHTPADDING", (0, 0), (-1, -1), 8),
        ("TOPPADDING", (0, 0), (-1, -1), 7),
        ("BOTTOMPADDING", (0, 0), (-1, -1), 7),
    ]))
    story.append(client_box)
    story.append(Spacer(1, 10))

    data = [[
        Paragraph("<b>#</b>", styles["Body"]),
        Paragraph("<b>Service</b>", styles["Body"]),
        Paragraph("<b>Item</b>", styles["Body"]),
        Paragraph("<b>Description</b>", styles["Body"]),
        Paragraph("<b>Qty</b>", styles["Body"]),
        Paragraph("<b>Rate</b>", styles["Body"]),
        Paragraph("<b>Amount</b>", styles["Body"]),
    ]]

    for idx, it in enumerate(items, start=1):
        service_name = "—"
        if getattr(it, "service", None) and getattr(it.service, "name", None):
            service_name = it.service.name

        data.append([
            Paragraph(str(idx), styles["Body"]),
            Paragraph(service_name, styles["Body"]),
            Paragraph(it.item_name or "", styles["Body"]),
            Paragraph(it.description or "", styles["Body"]),
            Paragraph(str(it.qty or 0), styles["Body"]),
            Paragraph(_rate_with_currency(it.rate), styles["Body"]),
            Paragraph(_money_with_currency(it.amount), styles["Body"]),
        ])

    items_tbl = Table(
        data,
        colWidths=[10 * mm, 28 * mm, 30 * mm, 52 * mm, 14 * mm, 26 * mm, 26 * mm],
        repeatRows=1
    )
    items_tbl.setStyle(TableStyle([
        ("BACKGROUND", (0, 0), (-1, 0), colors.HexColor("#F2F4F7")),
        ("TEXTCOLOR", (0, 0), (-1, 0), colors.HexColor("#101828")),
        ("FONTNAME", (0, 0), (-1, 0), "Helvetica-Bold"),
        ("FONTSIZE", (0, 0), (-1, -1), 9),
        ("GRID", (0, 0), (-1, -1), 0.45, colors.HexColor("#D0D5DD")),
        ("VALIGN", (0, 0), (-1, -1), "TOP"),
        ("ALIGN", (0, 0), (0, -1), "CENTER"),
        ("ALIGN", (4, 1), (6, -1), "RIGHT"),
        ("ROWBACKGROUNDS", (0, 1), (-1, -1), [colors.white, colors.HexColor("#FCFCFD")]),
        ("TOPPADDING", (0, 0), (-1, -1), 7),
        ("BOTTOMPADDING", (0, 0), (-1, -1), 7),
    ]))
    story.append(items_tbl)
    story.append(Spacer(1, 12))

    subtotal = _d(q.subtotal, "0")
    discount = _d(q.discount, "0")
    taxable_value = (subtotal - discount).quantize(TWOPLACES, rounding=ROUND_HALF_UP)

    if taxable_value < 0:
        taxable_value = Decimal("0.00")

    total = _d(q.total_amount, "0")

    totals_data = [
        ["Amount (Subtotal)", _money_with_currency(subtotal)],
        ["Discount", _money_with_currency(discount)],
        ["Taxable Value", _money_with_currency(taxable_value)],
    ]

    if (q.currency or "INR").strip().upper() == "INR" and getattr(q, "is_gst_applicable", False):
        if _d(q.igst, "0") > 0:
            totals_data += [
                ["IGST (18%)", _money_with_currency(q.igst)],
                ["Total GST", _money_with_currency(q.tax)],
            ]
        else:
            totals_data += [
                ["CGST (9%)", _money_with_currency(q.cgst)],
                ["SGST (9%)", _money_with_currency(q.sgst)],
                ["Total GST", _money_with_currency(q.tax)],
            ]

    totals_data += [
        ["Total Amount", _money_with_currency(total)],
    ]

    totals_tbl = Table(totals_data, colWidths=[72 * mm, 42 * mm], hAlign="RIGHT")
    totals_tbl.setStyle(TableStyle([
        ("BACKGROUND", (0, 0), (-1, -1), colors.white),
        ("BOX", (0, 0), (-1, -1), 0.6, colors.HexColor("#D0D5DD")),
        ("ALIGN", (0, 0), (-1, -1), "RIGHT"),

        # Normal rows
        ("FONTNAME", (0, 0), (-1, -1), "Helvetica"),

        # Taxable Value row, now row index 2
        ("FONTNAME", (0, 2), (-1, 2), "Helvetica-Bold"),

        # Final Total Amount row
        ("FONTNAME", (0, -1), (-1, -1), "Helvetica-Bold"),
        
        ("TEXTCOLOR", (0, 0), (-1, -1), colors.HexColor("#101828")),
        ("FONTSIZE", (0, 0), (-1, -1), 10),
        ("LINEABOVE", (0, -1), (-1, -1), 0.8, colors.HexColor("#344054")),
        ("TOPPADDING", (0, 0), (-1, -1), 7),
        ("BOTTOMPADDING", (0, 0), (-1, -1), 7),
        ("LEFTPADDING", (0, 0), (-1, -1), 8),
        ("RIGHTPADDING", (0, 0), (-1, -1), 8),
    ]))
    story.append(totals_tbl)
    story.append(Spacer(1, 14))

    meta_tbl = Table([
        [
            Paragraph("<b>Proposal created by</b><br/>"
                      f"{creator_name}<br/>{creator_email}", styles["Body"]),
            Paragraph(f"<b>Document Status</b><br/>Proposal Ready<br/><b>Currency:</b> {currency_meta['full']}", styles["Body"])
        ]
    ], colWidths=[88 * mm, 88 * mm])

    meta_tbl.setStyle(TableStyle([
        ("BOX", (0, 0), (-1, -1), 0.6, colors.HexColor("#E4E7EC")),
        ("BACKGROUND", (0, 0), (-1, -1), colors.white),
        ("VALIGN", (0, 0), (-1, -1), "TOP"),
        ("LEFTPADDING", (0, 0), (-1, -1), 8),
        ("RIGHTPADDING", (0, 0), (-1, -1), 8),
        ("TOPPADDING", (0, 0), (-1, -1), 8),
        ("BOTTOMPADDING", (0, 0), (-1, -1), 8),
    ]))
    story.append(meta_tbl)
    story.append(Spacer(1, 12))

    story.append(Paragraph("<b>Terms & Conditions</b>", styles["SectionTitle"]))
    story.append(Spacer(1, 3))

    try:
        for flowable in _html_blocks_to_pdf_flowables(q.proposal_terms or "", styles):
            story.append(flowable)
    except Exception:
        clean_terms = _proposal_html_to_plain_text(q.proposal_terms or "")

        if clean_terms:
            for line in clean_terms.splitlines():
                line = line.strip()
                if line:
                    story.append(Paragraph(escape(line), styles["Body"]))
                    story.append(Spacer(1, 3))
        else:
            story.append(Paragraph("—", styles["SmallMuted"]))

    doc.build(
        story,
        onFirstPage=_proposal_pdf_page,
        onLaterPages=_proposal_pdf_page
    )
    buff.seek(0)

    client_filename = re.sub(
        r"[^A-Za-z0-9._-]+",
        "_",
        (client_info.get("client_name") or "Client").strip(),
    ).strip("._-") or "Client"
    quote_filename = re.sub(r"[^A-Za-z0-9._-]+", "_", (q.quote_code or "Quote").strip())
    filename = f"{client_filename}_{quote_filename}.pdf"
    return send_file(buff, as_attachment=True, download_name=filename, mimetype="application/pdf")

# -------------------------
# Mark sent (only if Selected + proposal created)
# -------------------------
@quotes_bp.route("/<int:quote_id>/mark-sent", methods=["POST"])
@login_required
@require_perm("quotes.send")
def mark_sent(quote_id):
    q = Quote.query.get_or_404(quote_id)
    _require_quote_access(q)

    if q.status and q.status.name == "Sent":
        flash("Quote is already marked as Sent.", "info")
        return redirect(url_for("quotes.view_quote", quote_id=q.id))

    if not q.status or q.status.name != "Selected":
        flash("Only Selected quotes can be marked as Sent.", "danger")
        return redirect(url_for("quotes.view_quote", quote_id=q.id))

    if not getattr(q, "proposal_created_at", None):
        flash("Create Proposal first (add T&Cs) before marking as Sent.", "danger")
        return redirect(url_for("quotes.view_quote", quote_id=q.id))

    sent = _get_status("Sent")
    q.status_id = sent.id if sent else q.status_id

    if q.opportunity:
        _move_opportunity_stage(
            q.opportunity,
            "Negotiation",
            changed_by_id=current_user.id,
            remark=f"Auto: Proposal sent for quote {q.quote_code}"
        )

    db.session.commit()

    flash("Quote marked as Sent ✅", "success")
    return redirect(url_for("quotes.view_quote", quote_id=q.id))


# -------------------------
# List quotes (latest version only + visibility)
# -------------------------
@quotes_bp.route("/", methods=["GET"])
@login_required
@require_perm("quotes.view")
def list_quotes():
    qtext = (request.args.get("q") or "").strip()
    status_id = (request.args.get("status_id") or "").strip()
    owner = (request.args.get("owner") or "").strip()

    sub = (db.session.query(
        Quote.opportunity_id.label("opp_id"),
        func.max(Quote.version).label("max_ver")
    )
        .group_by(Quote.opportunity_id)
        .subquery())

    qs = (Quote.query
          .join(sub, (Quote.opportunity_id == sub.c.opp_id) & (Quote.version == sub.c.max_ver))
          .outerjoin(QuoteStatus)
          .outerjoin(Opportunity)
          .order_by(Quote.updated_at.desc(), Quote.id.desc()))

    if not current_user.has_perm("quotes.view_all"):
        allowed_ids = _allowed_sales_user_ids()  # <-- will be list here, not None
        qs = qs.filter(or_(
            Quote.created_by_id == current_user.id,
            Opportunity.owner_id.in_(allowed_ids)
        ))
    allowed_ids = _allowed_sales_user_ids()
    # Owner filter (only meaningful when not view_all)
    if owner == "me":
        qs = qs.filter(Opportunity.owner_id == current_user.id)
    elif owner.isdigit():
        oid = int(owner)
        if allowed_ids is None or oid in allowed_ids:
            qs = qs.filter(Opportunity.owner_id == oid)
        else:
            qs = qs.filter(Opportunity.owner_id == current_user.id)

    if qtext:
        like = f"%{qtext}%"
        qs = qs.filter(
            (Quote.quote_code.like(like)) |
            (func.coalesce(Opportunity.company, "").like(like)) |
            (Opportunity.title.like(like)) |
            (Opportunity.opp_code.like(like))
        )

    if status_id.isdigit():
        qs = qs.filter(Quote.status_id == int(status_id))

    statuses = QuoteStatus.query.order_by(QuoteStatus.name.asc()).all()

    page = request.args.get("page", 1, type=int)
    pagination = qs.paginate(page=page, per_page=15, error_out=False)
    owner_options = (
        User.query.filter(User.id.in_(allowed_ids)).order_by(User.name.asc()).all()
        if allowed_ids is not None
        else User.query.filter_by(is_active=True).order_by(User.name.asc()).all()
    )


    return render_template(
        "quotes/list.html",
        pagination=pagination,
        statuses=statuses,
        qtext=qtext,
        status_id=status_id,
        owner=owner, 
        owner_options=owner_options
    )


# -------------------------
# Create new version of quote
# -------------------------
@quotes_bp.route("/<int:quote_id>/new-version", methods=["POST"])
@login_required
@require_perm("quotes.edit")
def create_new_version(quote_id):
    base = Quote.query.get_or_404(quote_id)
    _require_quote_access(base)

    if _opportunity_has_any_invoice(base.opportunity_id):
        flash("Invoice already generated for this Opportunity. New quote versions are blocked.", "warning")
        return redirect(url_for("quotes.view_quote", quote_id=base.id))
    
    existing_jobcard = (
        OperationsJobcard.query
        .filter_by(quote_id=base.id)
        .first()
    )

    if existing_jobcard:
        flash("Jobcard already created for this quote. New version is blocked. Please edit the existing quote.", "warning")
        return redirect(url_for("quotes.view_quote", quote_id=base.id))

    draft = _get_status("Draft")

    latest = (Quote.query
              .filter(Quote.opportunity_id == base.opportunity_id)
              .order_by(Quote.version.desc())
              .first())

    next_version = (latest.version + 1) if latest else (base.version + 1)
    new_code = _quote_code_next()

    nq = Quote(
        quote_code=new_code,
        version=next_version,
        opportunity_id=base.opportunity_id,
        status_id=draft.id if draft else base.status_id,
        created_by_id=current_user.id,
        company_branch_id=base.company_branch_id,
        client_id=base.client_id,
        branch_id=base.branch_id,
        billing_state=base.billing_state,
        billing_gstin=base.billing_gstin,
        currency=base.currency,
        is_gst_applicable=base.is_gst_applicable,
        discount=base.discount,
        tax=Decimal("0.00"),
        cgst=Decimal("0.00"),
        sgst=Decimal("0.00"),
        igst=Decimal("0.00"),
        customer_notes=base.customer_notes,
        notes=base.notes,
        subtotal=Decimal("0"),
        total=Decimal("0"),
        total_amount=Decimal("0"),
        estimated_closure_date=base.estimated_closure_date,
    )
    db.session.add(nq)
    db.session.flush()

    old_items = base.items.order_by(QuoteItem.sort_order.asc()).all()
    for it in old_items:
        db.session.add(QuoteItem(
            quote_id=nq.id,
            item_name=it.item_name,
            description=it.description,
            qty=_d(it.qty, "0"),
            rate=_d(it.rate, "0", FOURPLACES),
            amount=Decimal("0"),
            sort_order=it.sort_order,
            # ✅ copy these too
            service_id=getattr(it, "service_id", None),
            billing_cycle=_norm_cycle(getattr(it, "billing_cycle", None)),
            is_flat_cost=True if getattr(it, "is_flat_cost", False) else False,
        ))

    db.session.commit()

    _recalc_quote(nq)
    db.session.commit()

    flash(f"New version created ✅ {nq.quote_code} (V{next_version})", "success")
    return redirect(url_for("quotes.edit_quote", quote_id=nq.id))


# -------------------------
# View all versions for an opportunity
# -------------------------
@quotes_bp.route("/opportunity/<int:opp_id>/versions")
@login_required
@require_perm("quotes.view")
def versions_for_opportunity(opp_id):
    opp = Opportunity.query.get_or_404(opp_id)
    _require_opp_access(opp)

    quotes = (Quote.query
              .filter_by(opportunity_id=opp.id)
              .outerjoin(QuoteStatus)
              .order_by(Quote.version.desc(), Quote.updated_at.desc())
              .all())

    return render_template("quotes/versions.html", opp=opp, quotes=quotes)


# -------------------------
# Approval Rules Management
# -------------------------
@quotes_bp.route("/approval-rules", methods=["GET", "POST"])
@login_required
@require_perm("approval_rules.manage")
def approval_rules_master():
    action = request.form.get("action") if request.method == "POST" else None

    if request.method == "POST":
        if action in ("rule_create", "rule_update"):
            rid = request.form.get("rule_id")
            name = (request.form.get("name") or "").strip()
            min_amt = _d(request.form.get("min_amount"), "0")
            max_raw = (request.form.get("max_amount") or "").strip()
            max_amt = None if max_raw == "" else _d(max_raw, "0")
            sort_order = int(request.form.get("sort_order") or 1)
            is_active = True if request.form.get("is_active") == "1" else False

            if not name:
                flash("Rule name is required.", "danger")
                return redirect(url_for("quotes.approval_rules_master"))

            if max_amt is not None and min_amt > max_amt:
                flash("Min Amount cannot be greater than Max Amount.", "danger")
                return redirect(url_for("quotes.approval_rules_master"))

            if action == "rule_create":
                r = ApprovalRule(
                    name=name,
                    min_amount=min_amt,
                    max_amount=max_amt,
                    sort_order=sort_order,
                    is_active=is_active
                )
                db.session.add(r)
                db.session.commit()
                flash("Approval rule created ✅", "success")
                return redirect(url_for("quotes.approval_rules_master"))

            r = ApprovalRule.query.get_or_404(int(rid))
            r.name = name
            r.min_amount = min_amt
            r.max_amount = max_amt
            r.sort_order = sort_order
            r.is_active = is_active
            db.session.commit()
            flash("Approval rule updated ✅", "success")
            return redirect(url_for("quotes.approval_rules_master"))

        if action == "step_add":
            rule_id = int(request.form.get("rule_id"))
            step_order = int(request.form.get("step_order") or 1)
            approver_role = (request.form.get("approver_role") or "").strip() or None
            au = (request.form.get("approver_user_id") or "").strip()
            approver_user_id = int(au) if au.isdigit() else None

            if not approver_role and not approver_user_id:
                flash("Select either Approver Role or Approver User.", "danger")
                return redirect(url_for("quotes.approval_rules_master"))

            db.session.add(ApprovalRuleStep(
                rule_id=rule_id,
                step_order=step_order,
                approver_role=approver_role,
                approver_user_id=approver_user_id,
                is_active=True
            ))
            db.session.commit()
            flash("Step added ✅", "success")
            return redirect(url_for("quotes.approval_rules_master"))

        if action == "step_update":
            step_id = int(request.form.get("step_id"))
            s = ApprovalRuleStep.query.get_or_404(step_id)

            s.step_order = int(request.form.get("step_order") or 1)
            s.approver_role = (request.form.get("approver_role") or "").strip() or None
            au = (request.form.get("approver_user_id") or "").strip()
            s.approver_user_id = int(au) if au.isdigit() else None
            s.is_active = True if request.form.get("is_active") == "1" else False

            if not s.approver_role and not s.approver_user_id:
                flash("Each step must have an approver role or approver user.", "danger")
                return redirect(url_for("quotes.approval_rules_master"))

            db.session.commit()
            flash("Step updated ✅", "success")
            return redirect(url_for("quotes.approval_rules_master"))

        if action == "step_delete":
            step_id = int(request.form.get("step_id"))
            s = ApprovalRuleStep.query.get_or_404(step_id)

            used = QuoteApproval.query.filter_by(rule_step_id=s.id).count()
            if used > 0:
                flash("This step is already used in approvals. Disable it instead of deleting.", "warning")
                return redirect(url_for("quotes.approval_rules_master"))

            db.session.delete(s)
            db.session.commit()
            flash("Step deleted ✅", "success")
            return redirect(url_for("quotes.approval_rules_master"))

    rules = ApprovalRule.query.order_by(ApprovalRule.sort_order.asc(), ApprovalRule.id.asc()).all()
    roles = Role.query.order_by(Role.name.asc()).all()
    users = User.query.order_by(User.name.asc()).all()

    return render_template("quotes/approval_rules.html", rules=rules, roles=roles, users=users)


@quotes_bp.route("/approval-rules/<int:rule_id>/edit", methods=["POST"])
@login_required
@require_perm("approval_rules.manage")
def edit_approval_rule(rule_id):
    flash("This endpoint is deprecated. Edit rules from Approval Rules page.", "info")
    return redirect(url_for("quotes.approval_rules_master"))


@quotes_bp.route("/approval-rules/<int:rule_id>/delete", methods=["POST"])
@login_required
@require_perm("approval_rules.manage")
def delete_approval_rule(rule_id):
    r = ApprovalRule.query.get_or_404(rule_id)

    used = QuoteApproval.query.filter_by(rule_id=r.id).count()
    if used > 0:
        flash("This rule is already used in approvals. Disable it instead of deleting.", "warning")
        return redirect(url_for("quotes.approval_rules_master"))

    db.session.delete(r)
    db.session.commit()
    flash("Approval rule deleted ✅", "success")
    return redirect(url_for("quotes.approval_rules_master"))


# -------------------------
# Convert Approved/Sent Quote -> Client + mark Selected
# -------------------------
@quotes_bp.route("/<int:quote_id>/convert-to-client", methods=["POST"])
@login_required
@require_perm("quotes.edit")
def convert_quote_to_client(quote_id):
    q = Quote.query.get_or_404(quote_id)
    _require_quote_access(q)

    if not q.status or q.status.name not in ("Approved", "Sent"):
        flash("Only Approved/Sent quotes can be converted.", "danger")
        return redirect(url_for("quotes.view_quote", quote_id=q.id))

    if q.client_id:
        selected = QuoteStatus.query.filter_by(name="Selected").first()
        if not selected:
            selected = QuoteStatus(name="Selected", sort_order=999, is_active=True)
            db.session.add(selected)
            db.session.flush()

        if not q.branch_id and q.opportunity and q.opportunity.branch_id:
            q.branch_id = q.opportunity.branch_id
        
        if getattr(q, "branch", None):
            q.billing_state = (
                q.branch.state_master.name
                if getattr(q.branch, "state_master", None)
                else q.branch.state
            )
            q.billing_gstin = q.branch.gst

        final_payment_raw = request.form.get("final_payment_date")
        if final_payment_raw:
            q.final_payment_date = datetime.strptime(final_payment_raw, "%Y-%m-%d").date()

        q.status_id = selected.id

        if hasattr(q, "status_updated_at"):
            q.status_updated_at = datetime.utcnow()
        if hasattr(q, "status_updated_by_id"):
            q.status_updated_by_id = current_user.id
        if hasattr(q, "status_remark"):
            q.status_remark = "Marked selected using existing linked client."

        db.session.commit()
        flash("Quote marked as Selected using the existing client ✅", "success")
        return redirect(url_for("quotes.view_quote", quote_id=q.id))

    company_name = (request.form.get("company_name") or "").strip()
    branch_location = (request.form.get("branch_location") or "").strip()
    contact_name = (request.form.get("contact_name") or "").strip()

    if not company_name or not branch_location or not contact_name:
        flash("Company name, branch location, and at least one contact are required.", "danger")
        return redirect(url_for("quotes.view_quote", quote_id=q.id))

    final_payment_raw = request.form.get("final_payment_date")
    if not final_payment_raw:
        flash("Final Payment Date is required when selecting quote.", "danger")
        return redirect(url_for("quotes.view_quote", quote_id=q.id))

    q.final_payment_date = datetime.strptime(final_payment_raw, "%Y-%m-%d").date()

    client = Client(
        company_name=company_name,
        company_industry=(request.form.get("company_industry") or "").strip() or None,
        service=(request.form.get("service") or "").strip() or None,
        client_type=(request.form.get("client_type") or "").strip() or None,
        website=(request.form.get("website") or "").strip() or None,
        reference=(request.form.get("reference") or "").strip() or None,
        pan=(request.form.get("pan") or "").strip() or None,
        client_category=(request.form.get("client_category") or "").strip() or None,
        remarks=(request.form.get("remarks") or "").strip() or None,
        source="LOCAL",
        is_active=True
    )
    db.session.add(client)
    db.session.flush()

    branch = ClientBranch(
        client_id=client.id,
        branch_location=branch_location,
        address=(request.form.get("address") or "").strip() or None,
        city=(request.form.get("city") or "").strip() or None,
        country=(request.form.get("country") or "").strip() or None,
        pin_code=(request.form.get("pin_code") or "").strip() or None,
        state=(request.form.get("state") or "").strip() or (q.billing_state or None),
        gst=(request.form.get("gst") or "").strip() or (q.billing_gstin or None),
        is_active=True
    )
    db.session.add(branch)
    db.session.flush()

    db.session.add(BranchContact(
        branch_id=branch.id,
        name=contact_name,
        phone=(request.form.get("contact_phone") or "").strip() or None,
        email=(request.form.get("contact_email") or "").strip() or None,
        designation=(request.form.get("contact_designation") or "").strip() or None,
        is_primary=True
    ))

    q.client_id = client.id
    q.branch_id = branch.id
    q.billing_state = (
        branch.state_master.name
        if getattr(branch, "state_master", None)
        else branch.state
    )
    q.billing_gstin = branch.gst

    if q.opportunity:
        q.opportunity.client_id = client.id
        q.opportunity.branch_id = branch.id
        if q.opportunity.lead:
            q.opportunity.lead.client_id = client.id
            q.opportunity.lead.branch_id = branch.id

    selected = QuoteStatus.query.filter_by(name="Selected").first()
    if not selected:
        selected = QuoteStatus(name="Selected", sort_order=999, is_active=True)
        db.session.add(selected)
        db.session.flush()

    q.status_id = selected.id

    db.session.commit()
    flash("Converted to Client and marked as Selected ✅", "success")
    return redirect(url_for("quotes.view_quote", quote_id=q.id))


@quotes_bp.route("/proposals/sent", methods=["GET"])
@login_required
@require_perm("quotes.proposals_sent.view")
def sent_proposals():
    sent = QuoteStatus.query.filter_by(name="Sent").first()

    qtext = (request.args.get("q") or "").strip()
    month = (request.args.get("month") or "").strip()
    jobcard_no = (request.args.get("jobcard_no") or "").strip()
    ops_status = (request.args.get("ops_status") or "").strip()
    proposal_status = (request.args.get("proposal_status") or "").strip()
    pi_status = (request.args.get("pi_status") or "").strip()
    invoice_status = (request.args.get("invoice_status") or "").strip()

    qs = (
        Quote.query
        .join(Opportunity, Quote.opportunity_id == Opportunity.id)
        .outerjoin(OperationsJobcard, OperationsJobcard.quote_id == Quote.id)
        .filter(Quote.status_id == (sent.id if sent else -1))
        .filter(Quote.proposal_created_at.isnot(None))
    )

    if not current_user.has_perm("quotes.view_all"):
        allowed_ids = _allowed_sales_user_ids()
        qs = qs.filter(or_(
            Quote.created_by_id == current_user.id,
            Opportunity.owner_id.in_(allowed_ids)
        ))

    if qtext:
        like = f"%{qtext}%"
        qs = qs.filter(or_(
            Quote.quote_code.ilike(like),
            Quote.currency.ilike(like),
            func.coalesce(Quote.billing_state, "").ilike(like),
            func.coalesce(Quote.billing_gstin, "").ilike(like),
            Opportunity.title.ilike(like),
            Opportunity.company.ilike(like),
        ))

    if month:
        try:
            start_date = datetime.strptime(month, "%Y-%m")
            if start_date.month == 12:
                end_date = datetime(start_date.year + 1, 1, 1)
            else:
                end_date = datetime(start_date.year, start_date.month + 1, 1)

            qs = qs.filter(
                Quote.proposal_created_at >= start_date,
                Quote.proposal_created_at < end_date
            )
        except ValueError:
            flash("Invalid month filter.", "warning")

    if jobcard_no:
        like = f"%{jobcard_no}%"
        qs = qs.filter(OperationsJobcard.jobcard_code.ilike(like))

    if ops_status:
        if ops_status == "Not Assigned":
            qs = qs.filter(Quote.ops_assignment_status.is_(None))
        elif ops_status == "Pending Jobcard":
            qs = qs.filter(Quote.ops_assignment_status == "Pending Jobcard")
        elif ops_status == "Jobcard Created":
            qs = qs.filter(OperationsJobcard.id.isnot(None))
        else:
            qs = qs.filter(Quote.ops_assignment_status == ops_status)

    qs = qs.order_by(Quote.updated_at.desc(), Quote.id.desc())

    items = qs.all()

    quote_ids = [x.id for x in items]

    latest_pi_by_quote = {}
    if quote_ids:
        rows = (
            ProformaInvoice.query
            .filter(ProformaInvoice.quote_id.in_(quote_ids))
            .filter(ProformaInvoice.status != "Cancelled", ProformaInvoice.advance_billing_id.is_(None))
            .order_by(ProformaInvoice.quote_id.asc(), ProformaInvoice.id.desc())
            .all()
        )
        for pi in rows:
            if pi.quote_id not in latest_pi_by_quote:
                latest_pi_by_quote[pi.quote_id] = pi

    latest_invoice_by_quote = {}
    if quote_ids:
        rows = (
            Invoice.query.join(ProformaInvoice, Invoice.pi_id == ProformaInvoice.id)
            .filter(Invoice.quote_id.in_(quote_ids), Invoice.status != "Cancelled",
                    ProformaInvoice.advance_billing_id.is_(None))
            .order_by(Invoice.quote_id.asc(), Invoice.id.desc())
            .all()
        )
        for inv in rows:
            if inv.quote_id not in latest_invoice_by_quote:
                latest_invoice_by_quote[inv.quote_id] = inv

    # While an advance PI/Invoice request is actively moving through Finance,
    # show that cycle on Proposals Sent. Once invoiced, it drops back to the
    # final-billing view and remains visible from the Jobcard advance history.
    if quote_ids:
        active_advances = (JobcardAdvanceBilling.query
                           .filter(JobcardAdvanceBilling.quote_id.in_(quote_ids),
                                   JobcardAdvanceBilling.status.in_(["PI_REQUESTED", "PI_RAISED", "INVOICE_REQUESTED"]))
                           .order_by(JobcardAdvanceBilling.id.desc()).all())
        seen_advance_quotes = set()
        for advance in active_advances:
            if advance.quote_id in seen_advance_quotes:
                continue
            seen_advance_quotes.add(advance.quote_id)
            if advance.pi:
                latest_pi_by_quote[advance.quote_id] = advance.pi
            else:
                latest_pi_by_quote.pop(advance.quote_id, None)
            if advance.invoice:
                latest_invoice_by_quote[advance.quote_id] = advance.invoice
            else:
                latest_invoice_by_quote.pop(advance.quote_id, None)

    # For a recurring SaaS cycle, the quotation intentionally has historical
    # PI/Invoice rows from earlier cycles.  Override the quote-wide maps with the
    # exact current billing Jobcard so the row shows JC/PI/Invoice for this cycle.
    saas_context_jobcard_by_quote = {}
    for quote in items:
        context_jobcard = _current_saas_billing_jobcard(quote)
        if not context_jobcard:
            continue
        saas_context_jobcard_by_quote[quote.id] = context_jobcard

        current_pi = (ProformaInvoice.query
                      .filter_by(quote_id=quote.id, jobcard_id=context_jobcard.id)
                      .filter(ProformaInvoice.status != "Cancelled")
                      .order_by(ProformaInvoice.id.desc())
                      .first())
        current_inv = (Invoice.query
                       .filter_by(quote_id=quote.id, jobcard_id=context_jobcard.id)
                       .filter(Invoice.status != "Cancelled")
                       .order_by(Invoice.id.desc())
                       .first())

        if current_pi:
            latest_pi_by_quote[quote.id] = current_pi
        else:
            latest_pi_by_quote.pop(quote.id, None)

        if current_inv:
            latest_invoice_by_quote[quote.id] = current_inv
        else:
            latest_invoice_by_quote.pop(quote.id, None)

    # A Credit Note reopen starts a fresh billing cycle on the same quote.
    # Historical PI / Invoice rows remain in the database for audit, but they
    # must not make the Sales workflow look already billed while the reopened
    # jobcard is waiting for its fresh PI -> Invoice cycle.
    reopened_billing_cycle_by_quote = {}
    for quote in items:
        reopened_cycle = _quote_is_in_reopened_billing_cycle(quote)
        reopened_billing_cycle_by_quote[quote.id] = reopened_cycle

        if not reopened_cycle:
            continue

        # Until Finance generates/approves the fresh PI, hide the historical PI
        # from the current-cycle status/actions.
        if getattr(quote, "pi_request_status", None) in (None, "Pending"):
            latest_pi_by_quote.pop(quote.id, None)

        # Until Finance generates the fresh invoice, hide the historical invoice
        # from the current-cycle status/actions.
        if getattr(quote, "invoice_request_status", None) in (None, "Pending"):
            latest_invoice_by_quote.pop(quote.id, None)

    # Additional workflow filters are applied after current-cycle PI / Invoice
    # resolution. This is important for Credit Note reopen cases because old
    # documents remain in history but must not count as the current billing cycle.
    if proposal_status == "Confirmed":
        items = [q for q in items if q.proposal_confirmed_at]
    elif proposal_status == "Awaiting Confirmation":
        items = [q for q in items if not q.proposal_confirmed_at]

    if pi_status == "PI Generated":
        items = [q for q in items if latest_pi_by_quote.get(q.id) is not None]
    elif pi_status == "PI Requested":
        items = [
            q for q in items
            if latest_pi_by_quote.get(q.id) is None
            and getattr(q, "pi_request_status", None) == "Pending"
        ]
    elif pi_status == "Not Requested":
        items = [
            q for q in items
            if latest_pi_by_quote.get(q.id) is None
            and getattr(q, "pi_request_status", None) != "Pending"
        ]

    if invoice_status == "Invoice Generated":
        items = [q for q in items if latest_invoice_by_quote.get(q.id) is not None]
    elif invoice_status == "Invoice Requested":
        items = [
            q for q in items
            if latest_invoice_by_quote.get(q.id) is None
            and getattr(q, "invoice_request_status", None) == "Pending"
        ]
    elif invoice_status == "Not Requested":
        items = [
            q for q in items
            if latest_invoice_by_quote.get(q.id) is None
            and getattr(q, "invoice_request_status", None) != "Pending"
        ]

    # Keep summary counts and action maps aligned with the filtered result set.
    filtered_quote_ids = {q.id for q in items}
    latest_pi_by_quote = {
        qid: row for qid, row in latest_pi_by_quote.items() if qid in filtered_quote_ids
    }
    latest_invoice_by_quote = {
        qid: row for qid, row in latest_invoice_by_quote.items() if qid in filtered_quote_ids
    }
    reopened_billing_cycle_by_quote = {
        qid: flag for qid, flag in reopened_billing_cycle_by_quote.items() if qid in filtered_quote_ids
    }

    jobcard_by_quote = {}
    if filtered_quote_ids:
        jobcards = (
            OperationsJobcard.query
            .filter(OperationsJobcard.quote_id.in_(filtered_quote_ids))
            .order_by(OperationsJobcard.quote_id.asc(), OperationsJobcard.id.desc())
            .all()
        )
        for jc in jobcards:
            if jc.quote_id not in jobcard_by_quote:
                jobcard_by_quote[jc.quote_id] = jc

    # Keep the Operations column/actions aligned with the same recurring SaaS
    # cycle used above for PI and Invoice resolution.
    for quote_id, context_jobcard in saas_context_jobcard_by_quote.items():
        if quote_id in filtered_quote_ids:
            jobcard_by_quote[quote_id] = context_jobcard

    ops_statuses = [
        "Not Assigned",
        "Pending Jobcard",
        "Jobcard Created",
    ]
    proposal_statuses = ["Awaiting Confirmation", "Confirmed"]
    pi_statuses = ["Not Requested", "PI Requested", "PI Generated"]
    invoice_statuses = ["Not Requested", "Invoice Requested", "Invoice Generated"]

    currency_rows = Currency.query.filter_by(is_active=True).all()

    currency_map = {}
    for c in currency_rows:
        currency_map[(c.code or "").upper()] = c.symbol or c.code

    return render_template(
        "quotes/sent_proposals.html",
        items=items,
        currency_map=currency_map,
        latest_pi_by_quote=latest_pi_by_quote,
        latest_invoice_by_quote=latest_invoice_by_quote,
        reopened_billing_cycle_by_quote=reopened_billing_cycle_by_quote,
        jobcard_by_quote=jobcard_by_quote,
        qtext=qtext,
        month=month,
        jobcard_no=jobcard_no,
        ops_status=ops_status,
        ops_statuses=ops_statuses,
        proposal_status=proposal_status,
        proposal_statuses=proposal_statuses,
        pi_status=pi_status,
        pi_statuses=pi_statuses,
        invoice_status=invoice_status,
        invoice_statuses=invoice_statuses,
    )

@quotes_bp.route("/<int:quote_id>/proposal/confirm", methods=["POST"])
@login_required
@require_perm("quotes.send")
def confirm_proposal(quote_id):
    q = Quote.query.get_or_404(quote_id)
    _require_quote_access(q)

    if not q.status or q.status.name != "Sent":
        flash("Only Sent proposals can be confirmed.", "danger")
        return redirect(url_for("quotes.view_quote", quote_id=q.id))

    if not q.proposal_created_at:
        flash("Proposal not created yet.", "danger")
        return redirect(url_for("quotes.proposal_builder", quote_id=q.id))

    q.proposal_confirmed_at = datetime.utcnow()
    q.proposal_confirmed_by_id = current_user.id
    db.session.commit()

    flash("Proposal confirmed ✅ Payments can now be updated.", "success")
    return redirect(url_for("quotes.sent_proposals"))

@quotes_bp.route("/<int:quote_id>/request-pi", methods=["POST"])
@login_required
@require_perm("proforma.request")
def request_pi(quote_id):
    q = Quote.query.get_or_404(quote_id)
    _require_quote_access(q)

    if not getattr(q, "proposal_confirmed_at", None):
        flash("You can request PI only after Proposal is Confirmed.", "danger")
        return redirect(url_for("quotes.view_quote", quote_id=q.id))

    if not q.status or q.status.name != "Sent":
        flash("You can request PI only after Proposal is Sent.", "danger")
        return redirect(url_for("quotes.view_quote", quote_id=q.id))

    jobcard = (
        OperationsJobcard.query
        .filter_by(quote_id=q.id)
        .order_by(OperationsJobcard.id.desc())
        .first()
    )

    if not jobcard:
        flash("You can request PI only after Operations Jobcard is created and closed.", "danger")
        return redirect(url_for("quotes.view_quote", quote_id=q.id))

    if getattr(jobcard, "is_sample_job", False) or jobcard.status == "Sample Completed":
        flash("PI cannot be requested for a Sample / Non-Billable Job.", "danger")
        return redirect(url_for("quotes.view_quote", quote_id=q.id))

    if jobcard.status != "Ready For Billing":
        flash("You can request PI only after Operations closes the Jobcard and marks it Ready For Billing.", "danger")
        return redirect(url_for("quotes.view_quote", quote_id=q.id))

    if q.pi_request_status in ("Pending", "Approved"):
        flash("PI request is already Pending with Finance.", "info")
        return redirect(url_for("quotes.view_quote", quote_id=q.id))

    existing_pi = (
        ProformaInvoice.query
        .filter_by(quote_id=q.id)
        .filter(ProformaInvoice.status != "Cancelled")
        .order_by(ProformaInvoice.id.desc())
        .first()
    )

    if existing_pi:
        reopen_cycle = _latest_approved_reopen(q)
        old_cycle_pi = bool(reopen_cycle and existing_pi.status == "Converted")
        saas_cycle = SoftwareSaaSBilling.query.filter_by(jobcard_id=jobcard.id).first() if jobcard else None
        same_jobcard_pi = (ProformaInvoice.query.filter_by(jobcard_id=jobcard.id, advance_billing_id=None)
                           .filter(ProformaInvoice.status != "Cancelled").first()) if jobcard else None
        if same_jobcard_pi:
            flash("Final PI already exists for this Jobcard.", "info")
            return redirect(url_for("proforma.view_pi", pi_id=same_jobcard_pi.id))
        if not old_cycle_pi and not saas_cycle:
            existing_final = (ProformaInvoice.query.filter_by(quote_id=q.id, advance_billing_id=None)
                              .filter(ProformaInvoice.status != "Cancelled")
                              .order_by(ProformaInvoice.id.desc()).first())
            if existing_final:
                flash("PI already exists for this quote.", "info")
                return redirect(url_for("proforma.view_pi", pi_id=existing_final.id))

    note = (request.form.get("pi_request_note") or "").strip() or None

    q.pi_requested_at = datetime.utcnow()
    q.pi_requested_by_id = current_user.id
    q.pi_request_note = note
    q.pi_request_status = "Pending"
    q.pi_requested_jobcard_id = jobcard.id if jobcard else None

    db.session.commit()

    flash("PI request sent to Finance ✅", "success")
    return redirect(url_for("quotes.view_quote", quote_id=q.id))

@quotes_bp.route("/<int:quote_id>/request-invoice", methods=["POST"])
@login_required
@require_perm("invoices.request")
def request_invoice(quote_id):
    q = Quote.query.get_or_404(quote_id)
    _require_quote_access(q)

    # Must be Sent + Proposal Confirmed
    if not q.status or q.status.name != "Sent":
        flash("You can request Invoice only after Proposal is Sent.", "danger")
        return redirect(url_for("quotes.view_quote", quote_id=q.id))

    if not getattr(q, "proposal_confirmed_at", None):
        flash("You can request Invoice only after Proposal is Confirmed.", "danger")
        return redirect(url_for("quotes.view_quote", quote_id=q.id))

    # For recurring SaaS, use the Jobcard that produced the current-cycle PI.
    # Normal quotations continue to use the latest Operations Jobcard.
    jobcard = _current_saas_billing_jobcard(q)
    if not jobcard:
        jobcard = (
            OperationsJobcard.query
            .filter_by(quote_id=q.id)
            .order_by(OperationsJobcard.id.desc())
            .first()
        )
    if jobcard and (getattr(jobcard, "is_sample_job", False) or jobcard.status == "Sample Completed"):
        flash("Invoice cannot be requested for a Sample / Non-Billable Job.", "danger")
        return redirect(url_for("quotes.view_quote", quote_id=q.id))

    # Must have PI first. For recurring SaaS use the PI for this exact Jobcard,
    # not merely the latest PI on the shared source quotation.
    saas_cycle = SoftwareSaaSBilling.query.filter_by(jobcard_id=jobcard.id).first() if jobcard else None
    if saas_cycle:
        pi = (ProformaInvoice.query
              .filter_by(quote_id=q.id, jobcard_id=jobcard.id)
              .filter(ProformaInvoice.status != "Cancelled")
              .order_by(ProformaInvoice.id.desc())
              .first())
    else:
        pi = (ProformaInvoice.query
              .filter_by(quote_id=q.id)
              .filter(ProformaInvoice.status != "Cancelled")
              .order_by(ProformaInvoice.id.desc())
              .first())
    if not pi:
        flash("Invoice can be requested only after PI is generated.", "danger")
        return redirect(url_for("quotes.view_quote", quote_id=q.id))

    # If invoice already exists for this exact PI -> redirect. Advance invoices
    # on the same Jobcard must not block a later final invoice.
    existing_for_pi = (Invoice.query.filter_by(pi_id=pi.id)
                       .filter(Invoice.status != "Cancelled")
                       .order_by(Invoice.id.desc()).first())
    if existing_for_pi:
        flash("Invoice already exists for this PI.", "info")
        return redirect(url_for("invoices.view_invoice", invoice_id=existing_for_pi.id))
    current_is_advance = bool(getattr(pi, "advance_billing_id", None))
    if not current_is_advance and not _quote_is_in_reopened_billing_cycle(q) and not saas_cycle:
        existing_final_invoice = (Invoice.query.join(ProformaInvoice, Invoice.pi_id == ProformaInvoice.id)
                                  .filter(Invoice.quote_id == q.id, Invoice.status != "Cancelled",
                                          ProformaInvoice.advance_billing_id.is_(None))
                                  .order_by(Invoice.id.desc()).first())
        if existing_final_invoice:
            flash("Final invoice already exists for this quote.", "info")
            return redirect(url_for("invoices.view_invoice", invoice_id=existing_final_invoice.id))

    # If already pending -> stop
    if getattr(q, "invoice_request_status", None) in ("Pending", "Approved"):
        flash("Invoice request is already pending with Finance.", "info")
        return redirect(url_for("quotes.view_quote", quote_id=q.id))

    note = (request.form.get("invoice_request_note") or "").strip() or None

    q.invoice_requested_at = datetime.utcnow()
    q.invoice_requested_by_id = current_user.id
    q.invoice_request_note = note
    q.invoice_request_status = "Pending"
    q.invoice_requested_jobcard_id = jobcard.id if jobcard else None
    if getattr(pi, "advance_billing_id", None):
        advance_row = JobcardAdvanceBilling.query.get(pi.advance_billing_id)
        if advance_row:
            advance_row.status = "INVOICE_REQUESTED"
    db.session.commit()

    flash("Invoice request sent to Finance ✅", "success")
    return redirect(url_for("quotes.view_quote", quote_id=q.id))

@quotes_bp.route("/<int:quote_id>/mark-selected-existing-client", methods=["POST"])
@login_required
@require_perm("quotes.edit")
def mark_selected_existing_client(quote_id):
    q = Quote.query.get_or_404(quote_id)
    _require_quote_access(q)

    if not q.status or q.status.name not in ("Approved", "Sent"):
        flash("Only Approved/Sent quotes can be marked as Selected.", "danger")
        return redirect(url_for("quotes.view_quote", quote_id=q.id))

    if not q.client_id:
        flash("This quote is not linked to an existing client.", "danger")
        return redirect(url_for("quotes.view_quote", quote_id=q.id))

    if not q.branch_id and q.opportunity and q.opportunity.branch_id:
        q.branch_id = q.opportunity.branch_id
    
    if getattr(q, "branch", None):
        q.billing_state = (
            q.branch.state_master.name
            if getattr(q.branch, "state_master", None)
            else q.branch.state
        )
        q.billing_gstin = q.branch.gst

    final_payment_date_raw = (request.form.get("final_payment_date") or "").strip()
    if final_payment_date_raw:
        q.final_payment_date = datetime.strptime(final_payment_date_raw, "%Y-%m-%d").date()

    selected_status = QuoteStatus.query.filter_by(name="Selected").first()
    if not selected_status:
        selected_status = QuoteStatus(name="Selected", sort_order=999, is_active=True)
        db.session.add(selected_status)
        db.session.flush()

    q.status_id = selected_status.id

    if hasattr(q, "status_updated_at"):
        q.status_updated_at = datetime.utcnow()
    if hasattr(q, "status_updated_by_id"):
        q.status_updated_by_id = current_user.id
    if hasattr(q, "status_remark"):
        q.status_remark = "Marked selected using existing linked client."
    
    _recalc_quote(q)
    db.session.commit()

    flash("Quote marked as Selected using the existing client ✅", "success")
    return redirect(url_for("quotes.view_quote", quote_id=q.id))


@quotes_bp.route("/sync-old-jobcards", methods=["POST"])
@login_required
@require_perm("quotes.edit")
def sync_old_jobcards():
    jobcards = (
        OperationsJobcard.query
        .filter(~OperationsJobcard.status.in_(["Ready For Billing", "Closure Approval Pending", "Closed"]))
        .all()
    )

    count = 0

    for jc in jobcards:
        if jc.quote:
            _recalc_quote(jc.quote)
            _sync_open_jobcard_from_quote(
                jc.quote,
                update_assignments=False
            )
            count += 1

    db.session.commit()

    flash(f"{count} old jobcards synced successfully.", "success")
    return redirect(url_for("quotes.list_quotes"))

@quotes_bp.route("/renewals", methods=["GET"])
@login_required
@require_perm("quotes.view")
def quotation_renewals():
    today = date.today()

    lookahead_days = int(request.args.get("lookahead_days") or 60)
    until_date = today + timedelta(days=lookahead_days)

    q = (
        Quote.query
        .join(QuoteItem, QuoteItem.quote_id == Quote.id)
        .filter(QuoteItem.billing_cycle.in_(RECURRING_CYCLES))
        .filter(Quote.proposal_confirmed_at.isnot(None))
        .filter(Quote.renewal_source_quote_id.is_(None))
    )

    if not current_user.has_perm("quotes.view_all"):
        q = q.filter(Quote.created_by_id == current_user.id)

    source_quotes = (
        q.order_by(Quote.proposal_confirmed_at.desc(), Quote.id.desc())
        .distinct()
        .all()
    )

    rows = []

    for source in source_quotes:
        cycle, next_start, next_end = _next_renewal_period(source)

        if not cycle or not next_start:
            continue

        if next_start > until_date:
            continue

        latest_renewal = _latest_renewal_quote(source)
        copy_from = latest_renewal or source

        rows.append({
            "source": source,
            "copy_from": copy_from,
            "cycle": cycle,
            "next_start": next_start,
            "next_end": next_end,
            "latest_renewal": latest_renewal,
            "is_due": next_start <= today,
        })

    return render_template(
        "quotes/quotation_renewals.html",
        rows=rows,
        today=today,
        lookahead_days=lookahead_days
    )

@quotes_bp.route("/<int:quote_id>/create-renewal", methods=["POST"])
@login_required
@require_perm("quotes.create")
def create_renewal_quote(quote_id):
    root = Quote.query.get_or_404(quote_id)
    _require_quote_access(root)

    if getattr(root, "renewal_source_quote_id", None):
        root = root.renewal_source

    if not _quote_has_recurring_items(root):
        flash("This quote does not have recurring billing items.", "danger")
        return redirect(url_for("quotes.quotation_renewals"))

    cycle, period_start, period_end = _next_renewal_period(root)

    if not cycle or not period_start:
        flash("Could not calculate next renewal period.", "danger")
        return redirect(url_for("quotes.quotation_renewals"))

    existing = (
        Quote.query
        .filter(Quote.renewal_source_quote_id == root.id)
        .filter(Quote.renewal_period_start == period_start)
        .first()
    )

    if existing:
        flash(f"Renewal quote already exists: {existing.quote_code}", "warning")
        return redirect(url_for("quotes.edit_quote", quote_id=existing.id))

    copy_from = _latest_renewal_quote(root) or root
    draft = _get_status("Draft")

    latest_version = (
        Quote.query
        .filter(Quote.opportunity_id == root.opportunity_id)
        .order_by(Quote.version.desc())
        .first()
    )

    next_version = (latest_version.version + 1) if latest_version else 1

    nq = Quote(
        quote_code=_quote_code_next(),
        version=next_version,
        opportunity_id=root.opportunity_id,
        status_id=draft.id if draft else root.status_id,
        created_by_id=current_user.id,
        company_branch_id=copy_from.company_branch_id,
        client_id=copy_from.client_id,
        branch_id=copy_from.branch_id,
        billing_state=copy_from.billing_state,
        billing_gstin=copy_from.billing_gstin,
        currency=copy_from.currency,
        is_gst_applicable=copy_from.is_gst_applicable,
        discount=copy_from.discount,
        tax=Decimal("0.00"),
        cgst=Decimal("0.00"),
        sgst=Decimal("0.00"),
        igst=Decimal("0.00"),
        customer_notes=copy_from.customer_notes,
        notes=copy_from.notes,
        subtotal=Decimal("0"),
        total=Decimal("0"),
        total_amount=Decimal("0"),
        estimated_closure_date=period_start,
        renewal_source_quote_id=root.id,
        renewal_period_start=period_start,
        renewal_period_end=period_end,
    )

    db.session.add(nq)
    db.session.flush()

    old_items = copy_from.items.order_by(QuoteItem.sort_order.asc()).all()

    for it in old_items:
        db.session.add(QuoteItem(
            quote_id=nq.id,
            item_name=it.item_name,
            description=it.description,
            qty=_d(it.qty, "0"),
            rate=_d(it.rate, "0", FOURPLACES),
            amount=Decimal("0"),
            sort_order=it.sort_order,
            service_id=getattr(it, "service_id", None),
            billing_cycle=_norm_cycle(getattr(it, "billing_cycle", None)),
            is_flat_cost=True if getattr(it, "is_flat_cost", False) else False,
        ))

    db.session.commit()

    _recalc_quote(nq)
    db.session.commit()

    flash(f"Renewal quote created ✅ {nq.quote_code}", "success")
    return redirect(url_for("quotes.edit_quote", quote_id=nq.id))