import os
import re
import sqlite3

from flask import Blueprint, abort, flash, g, redirect, render_template, request, url_for
from werkzeug.security import generate_password_hash

from .. import GRANTABLE, ROLES, admin_required, can, context_branch_ids, has, is_prime, license_info, login_required, \
    perm_required, prime_required, super_required
from ..db import commit, get_db, q, x
from ..migrations import ensure_branch_defaults, ensure_cheque_accounts
from ..money import to_int
from ..i18n import nm, t
from ..coa import auto_group, check_account, has_groups, tree, ungrouped
from ..ledger import ACCOUNT_KINDS, AccountingError, accounts_by_id, audit, trial_balance
from ..stock import inventory_account_map, reclass_inventory

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

# main colour presets for the Company page (any other colour can be picked too)
ACCENTS = [("#4f46e5", "Indigo"), ("#2563eb", "Blue"), ("#0891b2", "Ocean"), ("#0d9488", "Teal"),
           ("#00733e", "Green"), ("#7c3aed", "Violet"), ("#db2777", "Rose"), ("#ea580c", "Orange"),
           ("#b45309", "Bronze"), ("#334155", "Graphite")]


def opt_currencies():
    return [(r["code"], f"{r['code']} — {nm(r)}") for r in q("SELECT * FROM currencies WHERE active = 1 ORDER BY code")]


def opt_accounts():
    return [(r["id"], f"{r['code']} {nm(r)}")
            for r in q("SELECT * FROM accounts WHERE active = 1 AND is_group = 0 ORDER BY code")]


def opt_groups():
    return [(r["id"], f"{r['code']} {nm(r)}") for r in q("SELECT * FROM accounts WHERE is_group = 1 ORDER BY code")]


def opt_accounts_of(*kinds):
    return lambda: [(r["id"], f"{r['code']} {nm(r)}") for r in q(
        f"SELECT * FROM accounts WHERE active = 1 AND is_group = 0 AND kind IN ({','.join('?' * len(kinds))}) ORDER BY code", kinds)]


def company_default(col):
    return lambda: q(f"SELECT {col} FROM company", one=True)[0]


def opt_branches():
    return [(r["id"], f"{r['code']} — {nm(r)}") for r in q("SELECT * FROM branches ORDER BY code")]


def opt_kinds():
    return [(k, t(label)) for k, label, _ in ACCOUNT_KINDS]


def opt_journal_types():
    return [(k, t(v)) for k, v in (("sale", "Sales"), ("purchase", "Purchases"), ("bank", "Bank"),
                                   ("cash", "Cash"), ("cheque", "Cheques"), ("general", "Miscellaneous"))]


def opt_taxes_sale():
    return [(r["id"], nm(r)) for r in q("SELECT * FROM taxes WHERE active = 1 AND scope = 'sale' ORDER BY rate DESC")]


def opt_taxes_purchase():
    return [(r["id"], nm(r)) for r in q("SELECT * FROM taxes WHERE active = 1 AND scope = 'purchase' ORDER BY rate DESC")]


def opt_categories():
    return [(r["id"], nm(r)) for r in q("SELECT * FROM product_categories WHERE active = 1 ORDER BY name_en")]


def opt_product_types():
    return [("stock", t("Stockable product")), ("consumable", t("Consumable")), ("service", t("Service"))]


def opt_tracking():
    return [("none", t("No batch tracking")), ("lot", t("Batch number and expiry date"))]


def opt_methods():
    return [("linear", t("Straight line")), ("declining", t("Declining balance"))]


def opt_scope():
    return [("sale", t("Sales")), ("purchase", t("Purchases"))]


def F(name, label, type="text", options=None, required=False, list=True, help=None, default=None):
    """default: callable giving the value a new record (or an empty field) starts with."""
    return {"name": name, "label": label, "type": type, "options": options, "required": required,
            "list": list, "help": help, "default": default}


MODELS = {
    "branches": {
        "title": "Branches", "order": "code", "admin": True,
        "fields": [F("code", "Code", required=True), F("name_en", "Name (English)", required=True),
                   F("name_ar", "Name (Arabic)", "text_ar"),
                   F("currency", "Currency", "select", opt_currencies, True),
                   F("vat_no", "VAT Number"),
                   F("sale_tax_id", "Default sales VAT", "select", opt_taxes_sale, list=False,
                     help="Replaces the product's VAT in this branch, e.g. 5% for a UAE branch."),
                   F("purchase_tax_id", "Default purchase VAT", "select", opt_taxes_purchase, list=False),
                   F("phone", "Phone", list=False),
                   F("address_en", "Address (English)", "textarea", list=False),
                   F("address_ar", "Address (Arabic)", "textarea_ar", list=False),
                   F("active", "Active", "checkbox")],
    },
    "accounts": {
        "title": "Chart of Accounts", "order": "code", "admin": True,
        "fields": [F("code", "Code", required=True), F("name_en", "Name (English)", required=True),
                   F("name_ar", "Name (Arabic)", "text_ar"),
                   F("is_group", "Group account", "checkbox",
                     help="A heading that holds other accounts and shows their total. Nothing can be posted to it."),
                   F("parent_id", "Parent group", "select", opt_groups,
                     help="The group this account sits under, e.g. 1010 Cash on Hand under 111 Cash and Bank."),
                   F("kind", "Type", "select", opt_kinds, True,
                     help="Decides the statement section. For a group, the type of the accounts under it."),
                   F("intercompany", "Inter-branch account", "checkbox",
                     help="Balances on this account are eliminated in consolidated reports."),
                   F("active", "Active", "checkbox")],
    },
    "journals": {
        "title": "Journals", "order": "branch_id, code", "admin": True,
        "fields": [F("branch_id", "Branch", "select", opt_branches, True),
                   F("code", "Code", required=True), F("name_en", "Name (English)", required=True),
                   F("name_ar", "Name (Arabic)", "text_ar"),
                   F("type", "Type", "select", opt_journal_types, True),
                   F("default_account_id", "Default Account", "select", opt_accounts,
                     help="Income account for sales, expense account for purchases, bank/cash account for payments."),
                   F("active", "Active", "checkbox")],
    },
    "taxes": {
        "title": "Taxes", "order": "scope, rate DESC", "admin": True,
        "fields": [F("name_en", "Name (English)", required=True), F("name_ar", "Name (Arabic)", "text_ar"),
                   F("rate", "Rate %", "number", required=True),
                   F("scope", "Used in", "select", opt_scope, True),
                   F("account_id", "Tax Account", "select", opt_accounts, True),
                   F("active", "Active", "checkbox")],
    },
    "currencies": {
        "title": "Currencies", "order": "code", "admin": True, "key": "code",
        "fields": [F("code", "Code", required=True), F("name_en", "Name (English)", required=True),
                   F("name_ar", "Name (Arabic)", "text_ar"), F("symbol", "Symbol"),
                   F("decimals", "Decimals", "number", required=True), F("active", "Active", "checkbox")],
    },
    "rates": {
        "table": "exchange_rates", "title": "Exchange Rates", "order": "date DESC, currency", "admin": True,
        "fields": [F("currency", "Currency", "select", opt_currencies, True),
                   F("date", "Date", "date", required=True),
                   F("rate", "Rate", "number", required=True,
                     help="Value of 1 unit of this currency in the group currency.")],
    },
    "products": {
        "title": "Products", "order": "code, name_en", "admin": False,
        "fields": [F("code", "Internal Reference"), F("name_en", "Name (English)", required=True),
                   F("name_ar", "Name (Arabic)", "text_ar"),
                   F("type", "Product Type", "select", opt_product_types, True,
                     help="Stockable products are tracked in warehouses and valued at average cost."),
                   F("category_id", "Category", "select", opt_categories,
                     help="Choosing a category fills in its revenue and COGS accounts; stock is carried on the "
                          "category's inventory account."),
                   F("uom", "Unit of Measure", list=False), F("barcode", "Barcode", list=False),
                   F("sale_price", "Sales Price", "money"), F("purchase_price", "Cost", "money"),
                   F("sale_tax_id", "Sales Tax", "select", opt_taxes_sale, list=False),
                   F("purchase_tax_id", "Purchase Tax", "select", opt_taxes_purchase, list=False),
                   F("income_account_id", "Revenue Account", "select", opt_accounts, True, list=False,
                     default=company_default("income_account_id"),
                     help="Credited when this product is sold. Starts with the company default."),
                   F("expense_account_id", "COGS / Expense Account", "select", opt_accounts, True, list=False,
                     default=company_default("cogs_account_id"),
                     help="Cost of goods sold for stockable products, expense account for services and consumables. "
                          "Starts with the company default."),
                   F("min_qty", "Reorder Level", "number", list=False,
                     help="Reorder when forecast stock falls to this quantity."),
                   F("max_qty", "Reorder Up To", "number", list=False,
                     help="Reorder suggestions bring stock back up to this quantity. Empty = 30 days of sales."),
                   F("lead_days", "Lead Time (days)", "number", list=False,
                     help="Days from ordering to receiving. Empty = the vendor's average, else 7."),
                   F("tracking", "Batch / Expiry Tracking", "select", opt_tracking, True, list=False,
                     default=lambda: "none",
                     help="Batch: every receipt records a batch number and expiry date; deliveries take the "
                          "earliest-expiring batch first."),
                   F("shelf_life_days", "Shelf Life (days)", "number", list=False,
                     help="Fills in the expiry date on receipts (receipt date + shelf life)."),
                   F("active", "Active", "checkbox")],
    },
    "product_categories": {
        "title": "Product Categories", "order": "name_en", "admin": False,
        "fields": [F("name_en", "Name (English)", required=True), F("name_ar", "Name (Arabic)", "text_ar"),
                   F("inventory_account_id", "Inventory Account", "select",
                     opt_accounts_of("asset_current", "asset_non_current"),
                     help="Stock of this category is carried on this account, so it shows on its own line of the "
                          "balance sheet. Empty = the company inventory account."),
                   F("income_account_id", "Revenue Account", "select", opt_accounts_of("income", "income_other"),
                     help="Given to new products of this category. Empty = the company default."),
                   F("cogs_account_id", "COGS Account", "select", opt_accounts_of("expense_direct_cost", "expense"),
                     help="Given to new products of this category. Empty = the company default."),
                   F("active", "Active", "checkbox")],
    },
    "warehouses": {
        "title": "Warehouses", "order": "branch_id, code", "admin": True,
        "fields": [F("branch_id", "Branch", "select", opt_branches, True), F("code", "Code", required=True),
                   F("name_en", "Name (English)", required=True), F("name_ar", "Name (Arabic)", "text_ar"),
                   F("active", "Active", "checkbox")],
    },
    "asset_categories": {
        "title": "Asset Categories", "order": "name_en", "admin": True,
        "fields": [F("name_en", "Name (English)", required=True), F("name_ar", "Name (Arabic)", "text_ar"),
                   F("asset_account_id", "Asset Account", "select", opt_accounts, True),
                   F("depreciation_account_id", "Accumulated Depreciation Account", "select", opt_accounts, True),
                   F("expense_account_id", "Depreciation Expense Account", "select", opt_accounts, True),
                   F("method", "Method", "select", opt_methods, True),
                   F("life_months", "Useful life (months)", "number", required=True),
                   F("rate", "Declining rate % per year", "number", list=False), F("active", "Active", "checkbox")],
    },
    "cost_centres": {
        "title": "Cost Centres", "order": "code", "admin": False,
        "fields": [F("code", "Code", required=True,
                     help="Short code shown on lines and as the report column, e.g. SALES, PRJ-01, VAN-3."),
                   F("name_en", "Name (English)", required=True), F("name_ar", "Name (Arabic)", "text_ar"),
                   F("active", "Active", "checkbox",
                     help="Inactive cost centres can no longer be chosen; their history stays in the reports.")],
    },
    "partners": {
        "title": "Partners", "order": "name_en", "admin": False,
        "fields": [F("name_en", "Name (English)", required=True), F("name_ar", "Name (Arabic)", "text_ar"),
                   F("is_customer", "Customer", "checkbox"), F("is_vendor", "Vendor", "checkbox"),
                   F("vat_no", "VAT Number"), F("cr_no", "CR Number", list=False),
                   F("phone", "Phone"), F("email", "Email"),
                   F("receivable_account_id", "Receivable Account", "select", opt_accounts_of("asset_receivable"),
                     list=False, default=company_default("receivable_account_id"),
                     help="Used on this customer's invoices and payments. Starts with the company default."),
                   F("payable_account_id", "Payable Account", "select", opt_accounts_of("liability_payable"),
                     list=False, default=company_default("payable_account_id"),
                     help="Used on this vendor's bills and payments. Starts with the company default."),
                   F("currency", "Document currency", "select", opt_currencies, list=False,
                     help="New invoices and bills for this partner start in this currency. Empty = the branch currency."),
                   F("credit_limit", "Credit limit", "money", list=False,
                     help="Customers: the most they may owe, in the company currency, including confirmed orders not "
                          "yet invoiced. 0 = no limit."),
                   F("credit_hold", "On credit hold", "checkbox", list=False,
                     help="No new invoices or sales orders for this customer until the hold is released."),
                   F("address", "Address", "textarea", list=False), F("active", "Active", "checkbox")],
    },
}


def model_or_404(name):
    m = MODELS.get(name)
    if not m:
        abort(404)
    m.setdefault("table", name)
    m.setdefault("key", "id")
    return m


def can_edit(m):
    role = g.user["role"]
    return role == "admin" or (role == "accountant" and not m["admin"])


@bp.route("/<model>")
@login_required
def list_view(model):
    m = model_or_404(model)
    if model == "accounts":
        return chart_of_accounts(m)
    sql = f"SELECT * FROM {m['table']}"
    args = []
    where = []
    ptype = request.args.get("type")
    if model == "partners" and ptype in ("customer", "vendor"):
        where.append(f"is_{ptype} = 1")
    archivable = has_active(m)
    archived = request.args.get("archived", "")
    if archivable and archived != "all":
        where.append("active = 0" if archived == "1" else "active = 1")
    search = request.args.get("q", "").strip()
    if search:
        cols = [f["name"] for f in m["fields"] if f["type"] in ("text", "text_ar")]
        where.append("(" + " OR ".join(f"{c} LIKE ?" for c in cols) + ")")
        args += [f"%{search}%"] * len(cols)
    if where:
        sql += " WHERE " + " AND ".join(where)
    rows = q(sql + f" ORDER BY {m['order']}", args)
    options = {f["name"]: dict(f["options"]()) for f in m["fields"] if f["options"]}
    counts = {}
    if archivable:
        base = ("WHERE is_" + ptype + " = 1") if model == "partners" and ptype in ("customer", "vendor") else ""
        for r in q(f"SELECT active, COUNT(*) AS n FROM {m['table']} {base} GROUP BY active"):
            counts[r["active"]] = r["n"]
    return render_template("setup/list.html", m=m, model=model, rows=rows, options=options,
                           editable=can_edit(m), search=search, ptype=ptype, archivable=archivable,
                           archived=archived, counts=counts)


def has_active(m):
    return any(f["name"] == "active" for f in m["fields"])


def archive_blocker(model, key):
    """Why a record can't be archived, or None. Stock still on hand would vanish from every picker."""
    if model == "products":
        r = q("SELECT COALESCE(SUM(qty), 0) FROM stock_quants WHERE product_id = ?", (key,), one=True)[0]
        if abs(r) > 1e-9:
            return t("This product still has stock. Move or write off the stock before archiving it.")
    if model == "warehouses":
        r = q("SELECT COALESCE(SUM(ABS(qty)), 0) FROM stock_quants WHERE warehouse_id = ?", (key,), one=True)[0]
        if r > 1e-9:
            return t("This warehouse still holds stock. Transfer it out before archiving.")
    return None


def set_active(model, m, key, active):
    if not active:
        err = archive_blocker(model, key)
        if err:
            return err
    x(f"UPDATE {m['table']} SET active = ? WHERE {m['key']} = ?", (1 if active else 0, key))
    audit(g.user["id"], "archive" if not active else "restore", model.rstrip("s"), key)
    return None


@bp.route("/<model>/archive", methods=["POST"])
@login_required
def archive(model):
    """Archive or restore one record (key) or the rows ticked in the list (ids)."""
    m = model_or_404(model)
    if not has_active(m) or not can_edit(m):
        abort(403)
    active = request.form.get("action") in ("restore", "unarchive")
    keys = request.form.getlist("ids") or [request.form.get("key")]
    keys = [k for k in keys if k][:500]
    done, problems = 0, []
    for k in keys:
        row = q(f"SELECT * FROM {m['table']} WHERE {m['key']} = ?", (k,), one=True)
        if not row:
            continue
        err = set_active(model, m, k, active)
        if err:
            problems.append(f"{row['name_en'] if 'name_en' in row.keys() else k}: {err}")
        else:
            done += 1
    commit()
    if done:
        flash(f"{t('Restored') if active else t('Archived')}: {done}", "success")
    for p in problems[:5]:
        flash(p, "error")
    back = request.referrer if (request.referrer or "").startswith(request.host_url) else \
        url_for("setup.list_view", model=model)
    return redirect(back)


@bp.route("/<model>/new", methods=["GET", "POST"])
@bp.route("/<model>/<key>", methods=["GET", "POST"])
@login_required
def form_view(model, key=None):
    m = model_or_404(model)
    row = None
    if key is not None:
        row = q(f"SELECT * FROM {m['table']} WHERE {m['key']} = ?", (key,), one=True)
        if not row:
            abort(404)
    if request.method == "POST":
        if not can_edit(m):
            flash(t("You do not have permission for this action."), "error")
            return redirect(url_for("setup.list_view", model=model))
        values = {}
        for f in m["fields"]:
            v = request.form.get(f["name"])
            if f["type"] == "checkbox":
                v = 1 if v else 0
            elif f["type"] == "money":
                try:
                    v = to_int(v)
                except ValueError:
                    flash(f"{t(f['label'])}: {t('invalid number')}", "error")
                    return render_template("setup/form.html", m=m, model=model, row=request.form, key=key)
            elif f["type"] == "number":
                v = v.strip() if v else ""
                if v == "":
                    v = None
                else:
                    try:
                        v = float(v) if "." in v else int(v)
                    except ValueError:
                        flash(f"{t(f['label'])}: {t('invalid number')}", "error")
                        return render_template("setup/form.html", m=m, model=model, row=request.form, key=key)
            else:
                v = (v or "").strip() or None
            if v is None and f["name"] not in request.form and f.get("default"):
                v = f["default"]()  # a field the form did not send (older forms, scripts) keeps its default
            if f["required"] and v in (None, ""):
                flash(f"{t(f['label'])}: {t('is required')}", "error")
                return render_template("setup/form.html", m=m, model=model, row=request.form, key=key)
            values[f["name"]] = v
        if key is not None and "active" in values and not values["active"] and row["active"]:
            err = archive_blocker(model, key)
            if err:
                flash(err, "error")
                return render_template("setup/form.html", m=m, model=model, row=request.form, key=key)
        before = inventory_account_map() if model in ("products", "product_categories") else None
        try:
            if model == "accounts":
                check_account(values, key, accounts_by_id())
            if key is None and model == "branches":
                if not can("branches"):
                    flash(t("Only the software provider can add branches. Ask them to give you access."), "error")
                    return redirect(url_for("setup.list_view", model=model))
                max_b = license_info().limit("max_branches")
                if max_b and q("SELECT COUNT(*) FROM branches", one=True)[0] >= max_b:
                    flash(t("Your license allows") + f" {max_b} " + t("branches."), "error")
                    return redirect(url_for("setup.list_view", model=model))
            if key is None:
                cols = ",".join(values)
                new_key = x(f"INSERT INTO {m['table']} ({cols}) VALUES ({','.join('?' * len(values))})",
                            list(values.values()))
                if m["key"] != "id":
                    new_key = values[m["key"]]
                if model == "branches":
                    ensure_branch_defaults(get_db(), new_key)
                    ensure_cheque_accounts(get_db())
                if model == "partners" and values.get("is_vendor") and has("vendors") and \
                        q("SELECT require_approved_vendors FROM company", one=True)[0]:
                    x("UPDATE partners SET vendor_status = 'prospect' WHERE id = ?", (new_key,))
                audit(g.user["id"], "create", model, new_key if m["key"] == "id" else None, str(new_key))
            else:
                sets = ",".join(f"{c} = ?" for c in values)
                x(f"UPDATE {m['table']} SET {sets} WHERE {m['key']} = ?", list(values.values()) + [key])
                audit(g.user["id"], "update", model, int(key) if m["key"] == "id" else None, str(key))
            if model == "partners":
                from .. import partneraccts
                pid = new_key if key is None else int(key)
                partneraccts.rename(pid)
                if partneraccts.enabled():
                    for customer in (True, False):
                        if values.get("is_customer" if customer else "is_vendor"):
                            partneraccts.ensure_account(pid, customer, g.user["id"])
            if model == "products":
                # keep the category name on the product (POS screen, imports)
                x("UPDATE products SET category = (SELECT name_en FROM product_categories WHERE id = products.category_id) "
                  "WHERE id = ?", (new_key if key is None else key,))
            if before is not None:
                reclass_inventory(before, g.user["id"])
            commit()
        except sqlite3.IntegrityError:
            get_db().rollback()
            flash(t("This record conflicts with an existing one (duplicate code?)."), "error")
            return render_template("setup/form.html", m=m, model=model, row=request.form, key=key, **form_extra(model))
        except AccountingError as e:
            get_db().rollback()
            flash(str(e), "error")
            return render_template("setup/form.html", m=m, model=model, row=request.form, key=key, **form_extra(model))
        flash(t("Saved."), "success")
        if model == "partners" and values.get("is_vendor") and has("vendors") and request.args.get("type") == "vendor":
            return redirect(url_for("vendors.view", pid=new_key if key is None else int(key)))
        args = {"type": request.args["type"]} if request.args.get("type") else {}
        return redirect(url_for("setup.list_view", model=model, **args))
    if row:
        row = dict(row)
    else:
        row = {"active": 1}
        if model == "partners" and request.args.get("type") in ("customer", "vendor"):
            row[f"is_{request.args['type']}"] = 1
        if model == "accounts":  # "+ add under" from the chart: start with the group's type
            par = q("SELECT id, kind FROM accounts WHERE id = ? AND is_group = 1",
                    (request.args.get("parent", type=int),), one=True)
            if par:
                row.update(parent_id=par["id"], kind=par["kind"])
            row["is_group"] = 1 if request.args.get("group") else 0
    for f in m["fields"]:
        if f["default"] and row.get(f["name"]) is None:
            row[f["name"]] = f["default"]()
    return render_template("setup/form.html", m=m, model=model, row=row, key=key, editable=can_edit(m),
                           **form_extra(model))


def chart_of_accounts(m):
    """The chart as a tree: groups with the rolled-up balance of every account under them."""
    from datetime import date
    accs = accounts_by_id()
    ids = context_branch_ids()
    bal, currency = {}, None
    if ids:
        tb = trial_balance(ids, "0000-01-01", date.today().isoformat())
        bal = {r["account"]["id"]: r["closing"] for r in tb["rows"]}
        currency = tb["currency"]
    rows = tree(accs)
    total = {}
    for a, _ in reversed(rows):  # children come after their group, so walk back up
        total[a["id"]] = total.get(a["id"], 0) + bal.get(a["id"], 0)
        if a["parent_id"]:
            total[a["parent_id"]] = total.get(a["parent_id"], 0) + total[a["id"]]
    kids = {a["parent_id"] for a in accs.values() if a["parent_id"]}
    return render_template("setup/accounts.html", m=m, rows=rows, total=total, kids=kids, currency=currency,
                           editable=can_edit(m), kinds=dict(opt_kinds()), ungrouped=ungrouped(),
                           grouped=has_groups())


@bp.route("/accounts/auto-group", methods=["POST"])
@admin_required
def accounts_auto_group():
    try:
        n = auto_group()
        audit(g.user["id"], "update", "accounts", None, f"auto-grouped {n} accounts")
        commit()
        flash(f"{n} " + t("accounts were placed in the standard groups."), "success")
    except AccountingError as e:
        get_db().rollback()
        flash(str(e), "error")
    return redirect(url_for("setup.list_view", model="accounts"))


def form_extra(model):
    if model != "products":
        return {}
    return {"category_accounts": {r["id"]: {"income": r["income_account_id"], "cogs": r["cogs_account_id"]}
                                  for r in q("SELECT * FROM product_categories")}}


@bp.route("/company", methods=["GET", "POST"])
@admin_required
def company_view():
    c = q("SELECT * FROM company WHERE id = 1", one=True)
    if request.method == "POST":
        f = request.form
        before = inventory_account_map()
        x("UPDATE company SET name_en=?, name_ar=?, vat_no=?, cr_no=?, currency=?, address_en=?, address_ar=?, "
          "phone=?, email=?, lock_date=?, fy_start_month=?, receivable_account_id=?, payable_account_id=?, "
          "inventory_account_id=?, grni_account_id=?, stock_adjust_account_id=?, po_approval_limit=?, "
          "require_approved_vendors=?, income_account_id=?, cogs_account_id=?, landed_cost_account_id=?, "
          "credit_policy=?, credit_overdue_days=?, retained_earnings_account_id=?, cost_centre_required=? WHERE id = 1",
          (f["name_en"], f.get("name_ar"), f.get("vat_no"), f.get("cr_no"), f["currency"], f.get("address_en"),
           f.get("address_ar"), f.get("phone"), f.get("email"), f.get("lock_date") or None,
           int(f.get("fy_start_month") or 1), f.get("receivable_account_id") or None,
           f.get("payable_account_id") or None, f.get("inventory_account_id") or None,
           f.get("grni_account_id") or None, f.get("stock_adjust_account_id") or None,
           to_int(f.get("po_approval_limit") or 0), 1 if f.get("require_approved_vendors") else 0,
           f.get("income_account_id") or None, f.get("cogs_account_id") or None,
           f.get("landed_cost_account_id") or None,
           "block" if f.get("credit_policy") == "block" else "warn",
           int(f["credit_overdue_days"]) if (f.get("credit_overdue_days") or "").isdigit() else 0,
           f.get("retained_earnings_account_id") or None, 1 if f.get("cost_centre_required") else 0))
        if "scrap_account_id" in f:
            x("UPDATE company SET scrap_account_id = ? WHERE id = 1", (f.get("scrap_account_id") or None,))
        x("UPDATE company SET fx_gain_account_id = ?, fx_loss_account_id = ?, fx_unrealized_gain_id = ?, "
          "fx_unrealized_loss_id = ? WHERE id = 1", tuple(f.get(k) or None for k in (
              "fx_gain_account_id", "fx_loss_account_id", "fx_unrealized_gain_id", "fx_unrealized_loss_id")))
        if f.get("cost_centre_scope") in ("pl", "expense"):
            x("UPDATE company SET cost_centre_scope = ? WHERE id = 1", (f["cost_centre_scope"],))
        x("UPDATE company SET require_vendor_ref = ? WHERE id = 1", (1 if f.get("require_vendor_ref") else 0,))
        opened = None
        if f.get("partner_accounts") in ("shared", "each"):
            was = c["partner_accounts"]
            x("UPDATE company SET partner_accounts = ? WHERE id = 1", (f["partner_accounts"],))
            if f["partner_accounts"] == "each" and was != "each":
                from .. import partneraccts
                try:
                    opened = partneraccts.open_all(g.user["id"])
                except AccountingError as e:
                    get_db().rollback()
                    flash(str(e), "error")
                    return redirect(url_for("setup.company_view"))
        if "advance_account_id" in f:
            x("UPDATE company SET advance_account_id = ? WHERE id = 1", (f.get("advance_account_id") or None,))
        if has("procurement") and "match_policy" in f:
            def pct(v):
                try:
                    return max(float(v or 0), 0)
                except ValueError:
                    return 0
            x("UPDATE company SET match_policy = ?, match_qty_tolerance = ?, match_price_tolerance = ? WHERE id = 1",
              (f["match_policy"] if f["match_policy"] in ("none", "warn", "block") else "warn",
               pct(f.get("match_qty_tolerance")), pct(f.get("match_price_tolerance"))))
        if has("projects") and "retention_account_id" in f:
            x("UPDATE company SET retention_account_id = ? WHERE id = 1", (f.get("retention_account_id") or None,))
        save_mail_settings(f)
        accent = (f.get("accent") or "").strip().lower()
        x("UPDATE company SET accent = ? WHERE id = 1", (accent if re.fullmatch(r"#[0-9a-f]{6}", accent) else None,))
        audit(g.user["id"], "update", "company", 1, f"lock_date={f.get('lock_date')}")
        try:
            reclass_inventory(before, g.user["id"])
        except AccountingError as e:
            get_db().rollback()
            flash(str(e), "error")
            return redirect(url_for("setup.company_view"))
        commit()
        flash(t("Saved."), "success")
        if opened:
            flash(f"{opened[0]} " + t("partner accounts opened") + f", {opened[1]} " +
                  t("transfer entries posted for balances already on the shared accounts."), "success")
        return redirect(url_for("setup.company_view"))
    return render_template("setup/company.html", c=c, currencies=opt_currencies(), accounts=opt_accounts(),
                           accents=ACCENTS)


@bp.route("/company/logo", methods=["POST"])
@admin_required
def company_logo():
    from ..branding import remove_logo, save_logo
    old = q("SELECT logo FROM company WHERE id = 1", one=True)["logo"]
    try:
        if request.form.get("action") == "remove":
            x("UPDATE company SET logo = NULL WHERE id = 1")
            remove_logo(old)
        else:
            f = request.files.get("logo")
            if not f or not f.filename:
                raise AccountingError(t("Choose an image file."))
            x("UPDATE company SET logo = ? WHERE id = 1", (save_logo(f),))
            remove_logo(old)
        audit(g.user["id"], "update", "company", 1, "logo")
        commit()
        flash(t("Saved."), "success")
    except AccountingError as e:
        flash(str(e), "error")
    return redirect(url_for("setup.company_view"))


@bp.route("/company/logo.png")
@login_required
def company_logo_file():
    from flask import abort, send_file
    from ..branding import logo_path
    path = logo_path(q("SELECT * FROM company WHERE id = 1", one=True))
    if not path:
        abort(404)
    return send_file(path, mimetype="image/png", max_age=300)


@bp.route("/users")
@super_required
def users():
    # the provider's prime login is invisible to the customer
    rows = q("SELECT * FROM users " + ("" if is_prime() else "WHERE COALESCE(level, '') != 'prime' ") + "ORDER BY username")
    ub = {}
    for r in q("SELECT ub.user_id, b.code FROM user_branches ub JOIN branches b ON b.id = ub.branch_id"):
        ub.setdefault(r["user_id"], []).append(r["code"])
    return render_template("setup/users.html", rows=rows, ub=ub)


@bp.route("/users/new", methods=["GET", "POST"])
@bp.route("/users/<int:uid>", methods=["GET", "POST"])
@super_required
def user_form(uid=None):
    u = q("SELECT * FROM users WHERE id = ?", (uid,), one=True) if uid else None
    me = g.user["id"]
    if u and (u["level"] or "") == "prime" and not is_prime():
        abort(404)
    if u and (u["level"] or "") == "super" and not is_prime() and u["id"] != me:
        flash(t("Only the software provider can change another system administrator."), "error")
        return redirect(url_for("setup.users"))
    if request.method == "POST":
        f = request.form
        role = f.get("role") if f.get("role") in ROLES else "viewer"
        # levels: only the provider makes or removes system administrators; nobody makes a prime login here
        level = (u["level"] if u else None) or None
        if is_prime() and (not u or (u["level"] or "") != "prime"):
            level = "super" if f.get("level") == "super" else None
        if level in ("super", "prime"):
            role = "admin"  # a system administrator always has full company rights
        if u and u["id"] == me and not f.get("active"):
            flash(t("You cannot deactivate your own login."), "error")
            return redirect(request.url)
        branch_ids = [int(b) for b in f.getlist("branches")]
        try:
            if uid:
                x("UPDATE users SET username=?, full_name=?, role=?, lang=?, all_branches=?, active=?, can_approve=? "
                  "WHERE id=?", (f["username"].strip(), f.get("full_name"), role, f.get("lang", "en"),
                                 1 if f.get("all_branches") else 0, 1 if f.get("active") else 0,
                                 1 if f.get("can_approve") else 0, uid))
                if f.get("password"):
                    from .auth import password_problem
                    if password_problem(f["password"]):
                        raise AccountingError(password_problem(f["password"]))
                    x("UPDATE users SET password_hash = ? WHERE id = ?", (generate_password_hash(f["password"], method="pbkdf2:sha256"), uid))
            else:
                max_users = license_info().limit("max_users")
                if max_users and q("SELECT COUNT(*) FROM users WHERE active = 1 AND COALESCE(level, '') != 'prime'",
                                   one=True)[0] >= max_users:
                    flash(t("Your license allows") + f" {max_users} " + t("active users."), "error")
                    return redirect(request.url)
                from .auth import password_problem
                if password_problem(f.get("password", "")):
                    flash(password_problem(f.get("password", "")), "error")
                    return redirect(request.url)
                uid = x("INSERT INTO users (username, password_hash, full_name, role, lang, all_branches, active, "
                        "can_approve) VALUES (?,?,?,?,?,?,?,?)",
                        (f["username"].strip(), generate_password_hash(f["password"], method="pbkdf2:sha256"), f.get("full_name"), role,
                         f.get("lang", "en"), 1 if f.get("all_branches") else 0, 1 if f.get("active") else 0,
                         1 if f.get("can_approve") else 0))
            x("UPDATE users SET email = ?, level = ? WHERE id = ?", ((f.get("email") or "").strip() or None, level, uid))
            x("DELETE FROM user_branches WHERE user_id = ?", (uid,))
            for b in branch_ids:
                x("INSERT INTO user_branches (user_id, branch_id) VALUES (?, ?)", (uid, b))
            audit(g.user["id"], "update", "user", uid, f["username"])
            commit()
        except sqlite3.IntegrityError:
            get_db().rollback()
            flash(t("This record conflicts with an existing one (duplicate code?)."), "error")
            return redirect(request.url)
        except AccountingError as e:
            get_db().rollback()
            flash(str(e), "error")
            return redirect(request.url)
        flash(t("Saved."), "success")
        return redirect(url_for("setup.users"))
    mine = {r["branch_id"] for r in q("SELECT branch_id FROM user_branches WHERE user_id = ?", (uid,))} if uid else set()
    return render_template("setup/user_form.html", u=u, roles=ROLES, branches=q("SELECT * FROM branches ORDER BY code"),
                           mine=mine)


def save_mail_settings(f):
    port = (f.get("smtp_port") or "").strip()
    x("UPDATE company SET smtp_host = ?, smtp_port = ?, smtp_security = ?, smtp_user = ?, mail_from = ?, "
      "mail_from_name = ?, mail_bcc = ? WHERE id = 1",
      ((f.get("smtp_host") or "").strip() or None, int(port) if port.isdigit() else None,
       f.get("smtp_security") if f.get("smtp_security") in ("starttls", "ssl", "none") else "starttls",
       (f.get("smtp_user") or "").strip() or None, (f.get("mail_from") or "").strip() or None,
       (f.get("mail_from_name") or "").strip() or None, (f.get("mail_bcc") or "").strip() or None))
    if f.get("smtp_password"):
        x("UPDATE company SET smtp_password = ? WHERE id = 1", (f["smtp_password"],))
    url = (f.get("public_url") or "").strip().rstrip("/")
    x("UPDATE company SET public_url = ? WHERE id = 1", (url or None,))


@bp.route("/company/test-email", methods=["POST"])
@admin_required
def test_email():
    from ..mailer import send
    save_mail_settings(request.form)
    commit()
    to = (request.form.get("mail_from") or "").strip()   # the company's own mailbox
    try:
        send(to or "", t("Test email from Vertex ERP"),
             t("Your outgoing mail server is set up correctly. Statements, invoices and reminders can now be emailed."),
             kind="test", user_id=g.user["id"])
        flash(f"{t('Test email sent to')} {to}.", "success")
    except AccountingError as e:
        flash(str(e), "error")
    commit()
    return redirect(url_for("setup.company_view") + "#email")


@bp.route("/email-log")
@admin_required
def email_log():
    rows = q("SELECT e.*, u.username, p.name_en AS pname_en, p.name_ar AS pname_ar FROM email_log e "
             "LEFT JOIN users u ON u.id = e.sent_by LEFT JOIN partners p ON p.id = e.partner_id ORDER BY e.id DESC LIMIT 500")
    return render_template("setup/email_log.html", rows=rows)


@bp.route("/audit")
@admin_required
def audit_log():
    rows = q("SELECT a.*, u.username FROM audit_log a LEFT JOIN users u ON u.id = a.user_id "
             "ORDER BY a.id DESC LIMIT 500")
    return render_template("setup/audit.html", rows=rows)


@bp.route("/license")
@admin_required
def license_view():
    from ..modules import MODULES
    lic = license_info()
    usage = {"users": q("SELECT COUNT(*) FROM users WHERE active = 1 AND COALESCE(level, '') != 'prime'", one=True)[0],
             "branches": q("SELECT COUNT(*) FROM branches", one=True)[0]}
    from ..modules import BUSINESS_TYPES
    return render_template("setup/license.html", lic=lic, modules=MODULES, usage=usage, business_types=BUSINESS_TYPES,
                           presets={k: v["modules"] for k, v in BUSINESS_TYPES.items()})


@bp.route("/license/modules", methods=["POST"])
@perm_required("modules")
def license_modules():
    """Switch this company's modules on or off (within the license) by type of business."""
    from ..modules import BUSINESS_TYPES, MODULES
    lic = license_info()
    btype = request.form.get("business_type") if request.form.get("business_type") in BUSINESS_TYPES else "custom"
    chosen = set(BUSINESS_TYPES[btype]["modules"] or []) if btype != "custom" else set(request.form.getlist("mod"))
    chosen = {m for m in chosen if m in MODULES and m in lic.modules} | {"accounting"}
    # a module needs the ones it builds on (e.g. the supplier portal needs vendor management)
    for m in list(chosen):
        for req in MODULES[m].get("requires", []):
            if req in lic.modules:
                chosen.add(req)
    x("UPDATE company SET business_type = ?, enabled_modules = ? WHERE id = 1", (btype, ",".join(sorted(chosen))))
    from ..modules import sync_module_accounts
    sync_module_accounts(chosen)
    audit(g.user["id"], "update", "company", 1, f"business type {btype}: {','.join(sorted(chosen))}")
    commit()
    flash(t("Saved. Menus and forms now show only the modules in use."), "success")
    return redirect(url_for("setup.license_view"))


@bp.route("/backups", methods=["GET", "POST"])
@perm_required("backup")
def backups():
    from .. import backup
    if request.method == "POST":
        try:
            path = backup.make_backup("manual")
            audit(g.user["id"], "backup", "company", 1, os.path.basename(path))
            commit()
            flash(t("Backup created."), "success")
        except Exception as e:  # disk full, permissions...
            flash(f"{t('The backup failed')}: {e}", "error")
        return redirect(url_for("setup.backups"))
    return render_template("setup/backups.html", rows=backup.listing(), folder=backup.folder(), keep=backup.KEEP)


@bp.route("/backups/<name>")
@perm_required("backup")
def backup_download(name):
    from flask import abort, send_file
    from .. import backup
    p = backup.path_of(name)
    if not p:
        abort(404)
    audit(g.user["id"], "backup_download", "company", 1, name)
    commit()
    return send_file(p, as_attachment=True, download_name=os.path.basename(p))


@bp.route("/access", methods=["GET", "POST"])
@prime_required
def access():
    """The provider decides what the customer's system administrator (IT) may do besides managing users."""
    if request.method == "POST":
        chosen = [k for k in GRANTABLE if request.form.get(k)]
        x("UPDATE company SET prime_grants = ? WHERE id = 1", (",".join(chosen),))
        audit(g.user["id"], "update", "company", 1, "provider grants: " + (",".join(chosen) or "none"))
        commit()
        flash(t("Saved."), "success")
        return redirect(url_for("setup.access"))
    grants = set((q("SELECT prime_grants FROM company WHERE id = 1", one=True)[0] or "").split(","))
    admins = q("SELECT * FROM users WHERE level IN ('super', 'prime') ORDER BY level DESC, username")
    return render_template("setup/access.html", grantable=GRANTABLE, grants=grants, admins=admins)
