from datetime import date, timedelta

from flask import Blueprint, abort, flash, g, redirect, render_template, request, url_for

from .. import can_approve, check_branch, currency_decimals, has, login_required, write_required
from ..db import commit, get_db, placeholders, q, x
from ..i18n import t
from ..ledger import AccountingError, audit, compute_invoice_line, now
from ..money import to_int
from ..stock import ORDER_PREFIX, confirm_order, create_order_invoice, create_order_picking, next_number, \
    order_progress, order_status
from ..attachments import remove_all as remove_attachments
from ..costcentres import options as cost_centre_options, parse as parse_cost_centre
from ..projects import cost_centre as project_cost_centre, options as project_options, parse as parse_project
from .common import apply_search, partner_search, product_search, branch_map, default_branch, list_filters, partners_list, taxes_list, user_id

bp = Blueprint("orders", __name__, url_prefix="/orders")

KINDS = {
    "sale": {"title": "Sales Orders", "label": "Sales Order", "draft": "Quotation", "partner_type": "customer"},
    "purchase": {"title": "Purchase Orders", "label": "Purchase Order", "draft": "Draft PO",
                 "partner_type": "vendor"},
}
MODULE_OF = {"sale": "sales", "purchase": "procurement"}


@bp.before_request
def guard():
    from flask import request as rq
    kind = (rq.view_args or {}).get("kind")
    if not kind and (rq.view_args or {}).get("order_id"):
        o = q("SELECT kind FROM orders WHERE id = ?", (rq.view_args["order_id"],), one=True)
        kind = o["kind"] if o else None
    if kind in MODULE_OF and not has(MODULE_OF[kind]):
        flash(t("This module is not included in your license."), "error")
        return redirect(url_for("home.index"))


def kind_or_404(kind):
    if kind not in KINDS:
        abort(404)
    return KINDS[kind]


def get_order(order_id):
    o = q("SELECT o.*, p.name_en AS pname_en, p.name_ar AS pname_ar, p.vat_no AS pvat, p.address AS paddress, "
          "w.code AS wcode, w.name_en AS wname_en, w.name_ar AS wname_ar, cc.code AS cc_code, cc.name_en AS cc_name_en, "
          "cc.name_ar AS cc_name_ar, pj.code AS pj_code, pj.name_en AS pj_en, pj.name_ar AS pj_ar "
          "FROM orders o JOIN partners p ON p.id = o.partner_id "
          "LEFT JOIN warehouses w ON w.id = o.warehouse_id LEFT JOIN cost_centres cc ON cc.id = o.cost_centre_id "
          "LEFT JOIN projects pj ON pj.id = o.project_id WHERE o.id = ?",
          (order_id,), one=True)
    if not o:
        abort(404)
    check_branch(o["branch_id"])
    return o


def products_list():
    return q("SELECT * FROM products WHERE active = 1 ORDER BY code, name_en")


def warehouses_for(branch_ids):
    if not branch_ids:
        return []
    return q(f"SELECT * FROM warehouses WHERE active = 1 AND branch_id IN ({placeholders(branch_ids)}) ORDER BY code",
             list(branch_ids))


@bp.route("/<kind>")
@login_required
def index(kind):
    info = kind_or_404(kind)
    f = list_filters()
    rows = []
    if f["branch_ids"]:
        sql = (f"SELECT o.*, p.name_en AS pname_en, p.name_ar AS pname_ar FROM orders o "
               f"JOIN partners p ON p.id = o.partner_id WHERE o.kind = ? AND o.branch_id IN ({placeholders(f['branch_ids'])})")
        args = [kind] + list(f["branch_ids"])
        if f["date_from"]:
            sql += " AND o.date >= ?"
            args.append(f["date_from"])
        if f["date_to"]:
            sql += " AND o.date <= ?"
            args.append(f["date_to"])
        if f["state"] in ("draft", "to_approve", "confirmed", "cancelled"):
            sql += " AND o.state = ?"
            args.append(f["state"])
        sql, args = apply_search(f, sql, args, [
            ("number", "Number", "o.number LIKE ?", "text"),
            ("partner", "Vendor" if kind == "purchase" else "Customer", partner_search("p"), "text"),
            ("ref", "Reference", "o.ref LIKE ?", "text"),
            ("product", "Product", product_search("order_lines", "order_id", "o.id"), "text"),
            ("notes", "Notes", "o.notes LIKE ?", "text"),
            ("amount", "Amount", "o.amount_total = ?", "amount")])
        rows = [dict(r) for r in q(sql + " ORDER BY o.date DESC, o.id DESC LIMIT 1000", args)]
        for r in rows:
            r["deliv"], r["inv"] = order_status(r)
        todo = request.args.get("todo")
        if todo == "deliver":
            rows = [r for r in rows if r["deliv"] in ("no", "partial")]
        elif todo == "invoice":
            rows = [r for r in rows if r["inv"] in ("no", "partial")]
    return render_template("orders/list.html", rows=rows, kind=kind, info=info, f=f, branches=branch_map(),
                           todo=request.args.get("todo", ""))


def parse_lines(form, decimals):
    taxes = {r["id"]: r for r in q("SELECT * FROM taxes")}
    lines = []
    rows = zip(form.getlist("product_id"), form.getlist("description"), form.getlist("quantity"),
               form.getlist("price_unit"), form.getlist("tax_id"))
    for seq, (prod, desc, qty, price, tax) in enumerate(rows):
        if not prod and not desc and not price:
            continue
        try:
            qty_f = float(qty or 1)
            price_i = to_int(price)
        except ValueError:
            raise AccountingError(t("invalid number"))
        if qty_f <= 0:
            raise AccountingError(t("Quantities must be greater than zero."))
        tax_id = int(tax) if tax else None
        sub, tx = compute_invoice_line(qty_f, price_i, taxes[tax_id]["rate"] if tax_id else 0, decimals)
        lines.append({"sequence": seq, "product_id": int(prod) if prod else None, "description": desc,
                      "quantity": qty_f, "price_unit": price_i, "tax_id": tax_id, "subtotal": sub, "tax_amount": tx})
    return lines


@bp.route("/<kind>/new", methods=["GET", "POST"])
@bp.route("/<kind>/<int:order_id>/edit", methods=["GET", "POST"])
@write_required
def form(kind, order_id=None):
    info = kind_or_404(kind)
    o = get_order(order_id) if order_id else None
    if o and o["state"] != "draft":
        flash(t("Only draft documents can be edited."), "error")
        return redirect(url_for("orders.view", order_id=order_id))
    lines = [dict(r) for r in q("SELECT * FROM order_lines WHERE order_id = ? ORDER BY sequence, id",
                                (order_id,))] if o else []
    orig_id = order_id
    if request.method == "POST":
        fm = request.form
        try:
            branch_id = check_branch(fm["branch_id"])
            if not fm.get("partner_id"):
                raise AccountingError(t("Choose a partner."))
            wh = q("SELECT * FROM warehouses WHERE id = ?", (fm.get("warehouse_id") or 0,), one=True)
            if has("inventory") and (not wh or wh["branch_id"] != branch_id):
                raise AccountingError(t("The warehouse does not belong to the selected branch."))
            wh_id = wh["id"] if wh and wh["branch_id"] == branch_id else None
            branch = q("SELECT * FROM branches WHERE id = ?", (branch_id,), one=True)
            lines = parse_lines(fm, currency_decimals(branch["currency"]))
            if not lines:
                raise AccountingError(t("Add at least one line."))
            untaxed = sum(ln["subtotal"] for ln in lines)
            tax = sum(ln["tax_amount"] for ln in lines)
            project_id = parse_project(fm.get("project_id"), branch_id, dict(o).get("project_id") if o else None)
            cc_id = project_cost_centre(project_id) if project_id else parse_cost_centre(fm.get("cost_centre_id"))
            vals = (branch_id, wh_id, int(fm["partner_id"]), fm["date"], fm.get("expected_date") or None,
                    fm.get("ref"), fm.get("notes"), untaxed, tax, untaxed + tax, cc_id,
                    fm.get("terms"), project_id)
            if o and (o["branch_id"] != branch_id or str(o["date"])[:4] != fm["date"][:4]):
                # a draft quotation / order moved to another branch or year takes that branch's next number
                x("UPDATE orders SET number = ? WHERE id = ?",
                  (next_number("orders", "number", ORDER_PREFIX[kind], branch_id, fm["date"]), order_id))
            if o:
                x("UPDATE orders SET branch_id=?, warehouse_id=?, partner_id=?, date=?, expected_date=?, ref=?, notes=?, "
                  "amount_untaxed=?, amount_tax=?, amount_total=?, cost_centre_id=?, terms=?, project_id=? WHERE id = ?",
                  vals + (order_id,))
                x("DELETE FROM order_lines WHERE order_id = ?", (order_id,))
            else:
                number = next_number("orders", "number", ORDER_PREFIX[kind], branch_id, fm["date"])
                order_id = x("INSERT INTO orders (branch_id, warehouse_id, partner_id, date, expected_date, ref, notes, "
                             "amount_untaxed, amount_tax, amount_total, cost_centre_id, terms, project_id, kind, number, state, "
                             "created_by, created_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,'draft',?,?)",
                             vals + (kind, number, user_id(), now()))
            for ln in lines:
                x("INSERT INTO order_lines (order_id, sequence, product_id, description, quantity, price_unit, tax_id, "
                  "subtotal, tax_amount) VALUES (?,?,?,?,?,?,?,?,?)",
                  (order_id, ln["sequence"], ln["product_id"], ln["description"], ln["quantity"], ln["price_unit"],
                   ln["tax_id"], ln["subtotal"], ln["tax_amount"]))
            audit(user_id(), "save", "order", order_id)
            msg = t("Saved.")
            if fm.get("action") == "confirm":
                if confirm_order(order_id, user_id(), False) == "to_approve":
                    msg = t("The order is above the approval limit and is waiting for approval.")
            commit()
            flash(msg, "success")
            return redirect(url_for("orders.view", order_id=order_id))
        except AccountingError as e:
            get_db().rollback()
            flash(str(e), "error")
            o = dict(fm.items())
            o["id"] = orig_id
            lines = [{"product_id": int(p) if p else None, "description": d, "quantity": qq,
                      "price_unit": to_int(pr or 0) if pr.replace(".", "", 1).isdigit() else 0,
                      "tax_id": int(tx) if tx else None}
                     for p, d, qq, pr, tx in zip(fm.getlist("product_id"), fm.getlist("description"),
                                                 fm.getlist("quantity"), fm.getlist("price_unit"), fm.getlist("tax_id"))]
    branches = branch_map()
    today = date.today()
    return render_template("orders/form.html", o=o, lines=lines, kind=kind, info=info, branches=branches,
                           warehouses=warehouses_for(list(branches)), partners=partners_list(info["partner_type"]),
                           products=products_list(), taxes=taxes_list("sale" if kind == "sale" else "purchase"),
                           default_branch=default_branch(), today=today.isoformat(),
                           cost_centres=cost_centre_options(dict(o).get("cost_centre_id") if o else None),
                           projects=project_options(dict(o).get("project_id") if o else request.args.get("project", type=int)),
                           project_pre=request.args.get("project", type=int),
                           expected=(today + timedelta(days=7)).isoformat())


def order_context(order_id):
    o = get_order(order_id)
    lines = q("SELECT ol.*, p.code AS pcode, p.name_en AS pname_en, p.name_ar AS pname_ar, p.type AS ptype, p.uom, "
              "tx.name_en AS tname_en, tx.name_ar AS tname_ar, tx.rate AS trate FROM order_lines ol "
              "LEFT JOIN products p ON p.id = ol.product_id LEFT JOIN taxes tx ON tx.id = ol.tax_id "
              "WHERE ol.order_id = ? ORDER BY ol.sequence, ol.id", (order_id,))
    pickings = q("SELECT * FROM pickings WHERE order_id = ? ORDER BY id", (order_id,))
    invoices = q("SELECT * FROM invoices WHERE order_id = ? ORDER BY id", (order_id,))
    deliv, inv = order_status(o)
    branch = q("SELECT * FROM branches WHERE id = ?", (o["branch_id"],), one=True)
    rfq = q("SELECT id, number FROM rfqs WHERE id = ?", (o["rfq_id"],), one=True) if o["rfq_id"] else None
    pr = q("SELECT id, number FROM purchase_requisitions WHERE id = ?", (o["pr_id"],), one=True) if o["pr_id"] else None
    prog = order_progress(order_id)
    ctx = {"o": o, "lines": lines, "rfq": rfq, "pr": pr, "prog": prog, "pickings": pickings, "invoices": invoices,
           "deliv": deliv, "inv_status": inv, "branch": branch, "kind": o["kind"], "info": KINDS[o["kind"]],
           "open_picking": any(p["state"] == "ready" for p in pickings),
           "stock_open": any(ln["ptype"] == "stock" and ln["quantity"] - prog[ln["id"]]["done"] - prog[ln["id"]]["pending"] > 1e-9
                             for ln in lines) and has("inventory")}
    if o["kind"] == "purchase" and has("procurement"):
        from ..procurement import can_receive, grn_lines_open, po_type
        ctx["po_type"] = po_type(o)
        ctx["grn_lines"] = grn_lines_open(order_id)
        ctx["grn_open"] = any(ln["open"] > 1e-9 for ln in ctx["grn_lines"])
        ctx["can_grn"] = can_receive(o, g.user)
        ctx["grns"] = q("SELECT g.*, u.full_name FROM grns g LEFT JOIN users u ON u.id = g.received_by "
                        "WHERE g.order_id = ? ORDER BY g.id", (order_id,))
        ctx["mr"] = q("SELECT id, number FROM material_requests WHERE id = ?", (o["mr_id"],), one=True) if o["mr_id"] else None
    return ctx


@bp.route("/view/<int:order_id>")
@login_required
def view(order_id):
    o = get_order(order_id)
    if request.args.get("export") and o["kind"] == "purchase" and o["state"] == "confirmed":
        from ..exports import respond
        from ..procurement import po_report
        out = respond(po_report(order_id), o["number"].replace("/", "-"))
        if out:
            return out
    return render_template("orders/view.html", **order_context(order_id), today=date.today().isoformat())


@bp.route("/view/<int:order_id>/grn", methods=["GET", "POST"])
@write_required
def grn(order_id):
    from ..procurement import can_receive, create_grn, grn_lines_open
    o = get_order(order_id)
    if not has("procurement") or o["kind"] != "purchase":
        abort(404)
    if not can_receive(o, g.user):
        flash(t("Only the requester, the project team or an administrator can receive these items."), "error")
        return redirect(url_for("orders.view", order_id=order_id))
    lines = grn_lines_open(order_id)
    if request.method == "POST":
        fm = request.form
        try:
            gid = create_grn(order_id, fm.get("date") or date.today().isoformat(),
                             {ln["id"]: fm.get(f"qty_{ln['id']}") or 0 for ln in lines}, fm.get("delivery_note"),
                             fm.get("notes"), user_id())
            commit()
            flash(t("Goods received note saved."), "success")
            return redirect(url_for("orders.grn_view", grn_id=gid))
        except (AccountingError, ValueError) as e:
            get_db().rollback()
            flash(str(e), "error")
    return render_template("orders/grn_form.html", o=o, lines=lines, today=date.today().isoformat())


@bp.route("/grn/<int:grn_id>", methods=["GET", "POST"])
@login_required
def grn_view(grn_id):
    from ..procurement import cancel_grn, grn_report
    gr = q("SELECT g.*, u.full_name, o.number AS po FROM grns g LEFT JOIN users u ON u.id = g.received_by "
           "JOIN orders o ON o.id = g.order_id WHERE g.id = ?", (grn_id,), one=True)
    if not gr:
        abort(404)
    o = get_order(gr["order_id"])
    if request.method == "POST":
        if g.user["role"] not in ("admin", "accountant"):
            abort(403)
        try:
            cancel_grn(grn_id, user_id())
            commit()
            flash(t("Cancelled."), "success")
        except AccountingError as e:
            get_db().rollback()
            flash(str(e), "error")
        return redirect(url_for("orders.grn_view", grn_id=grn_id))
    if request.args.get("export"):
        from ..exports import respond
        out = respond(grn_report(grn_id), gr["number"].replace("/", "-"))
        if out:
            return out
    lines = q("SELECT gl.*, ol.description, ol.quantity AS ordered FROM grn_lines gl JOIN order_lines ol "
              "ON ol.id = gl.order_line_id WHERE gl.grn_id = ? ORDER BY gl.id", (grn_id,))
    return render_template("orders/grn_view.html", gr=gr, o=o, lines=lines)


@bp.route("/print/<int:order_id>")
@login_required
def print_view(order_id):
    return render_template("orders/print.html", **order_context(order_id))


@bp.route("/view/<int:order_id>/<action>", methods=["POST"])
@write_required
def action(order_id, action):
    o = get_order(order_id)
    try:
        if action in ("approve", "reject"):
            from ..workflow import act_on_doc
            act_on_doc("po", order_id, user_id(), action, request.form.get("reason") or request.form.get("comment"),
                       bool(request.form.get("override")))
        elif action == "confirm":
            if confirm_order(order_id, user_id(), False) == "to_approve":
                commit()
                flash(t("The order is waiting for approval."), "success")
                return redirect(url_for("orders.view", order_id=order_id))
        elif action in ("send", "mark_sent"):
            from ..procurement import send_po
            send_po(order_id, user_id(), email=action == "send", cc=g.user["email"])
            commit()
            flash(t("Purchase order emailed to the vendor.") if action == "send" else t("Marked as sent."), "success")
            return redirect(url_for("orders.view", order_id=order_id))
        elif action == "ack":
            from ..procurement import acknowledge_po
            fm = request.form
            acknowledge_po(order_id, fm.get("ack_state"), fm.get("ack_ref"), fm.get("ack_date") or None,
                           fm.get("ack_note"), user_id())
        elif action == "picking" and o["state"] == "confirmed":
            pid = create_order_picking(order_id, user_id())
            commit()
            return redirect(url_for("inventory.picking", picking_id=pid))
        elif action == "invoice":
            inv_id = create_order_invoice(order_id, date.today().isoformat(), user_id())
            commit()
            flash(t("Draft invoice created. Review and post it."), "success")
            return redirect(url_for("invoices.view", inv_id=inv_id))
        elif action == "cancel" and o["state"] in ("draft", "to_approve", "confirmed"):
            from ..workflow import cancel as cancel_approval
            cancel_approval("po", order_id, user_id(), t("Cancelled"))
            if q("SELECT 1 FROM pickings WHERE order_id = ? AND state = 'done'", (order_id,)) or \
                    q("SELECT 1 FROM invoices WHERE order_id = ? AND state != 'cancelled'", (order_id,)):
                raise AccountingError(t("This order already has done transfers or invoices."))
            x("UPDATE pickings SET state = 'cancelled' WHERE order_id = ? AND state = 'ready'", (order_id,))
            x("UPDATE orders SET state = 'cancelled' WHERE id = ?", (order_id,))
            audit(user_id(), "cancel", "order", order_id, o["number"])
        elif action == "draft" and o["state"] == "cancelled":
            x("UPDATE orders SET state = 'draft' WHERE id = ?", (order_id,))
        elif action == "delete" and o["state"] == "draft":
            x("DELETE FROM orders WHERE id = ?", (order_id,))
            remove_attachments("order", order_id)
            audit(user_id(), "delete", "order", order_id, o["number"])
            commit()
            flash(t("Deleted."), "success")
            return redirect(url_for("orders.index", kind=o["kind"]))
        else:
            raise AccountingError(t("This action is not allowed in the current state."))
        commit()
        flash(t("Done."), "success")
    except AccountingError as e:
        get_db().rollback()
        flash(str(e), "error")
    return redirect(url_for("orders.view", order_id=order_id))
