"""Care HCM extras: recruitment, onboarding, performance, training, expenses, loans, helpdesk, assets,
documents, policies, productivity, org chart, calendar, analytics, audit log, 2FA."""
import os, json, secrets, calendar as cal
from datetime import datetime, date, timedelta
from flask import render_template, request, redirect, url_for, flash, abort, send_file, session
from werkzeug.security import generate_password_hash
import app as A
from app import app, q, ex, g, S, now, need, HR, MGR, ADMIN, can, can_see, audit, month_stats, month_bounds, opts, totp_code, totp_ok, EXTRA_SQL, is_off, holiday_set, scope_sql, full_view, subtree_ids, SUB

BASE = A.BASE
UPLOADS = os.path.join(BASE, "data", "uploads")
os.makedirs(UPLOADS, exist_ok=True)


def F(k, l, t="text", o=None, req=0):
    return dict(k=k, l=l, t=t, o=o, req=req)


STAGES = ["Applied", "Screening", "Interview", "Offer", "Hired", "Rejected"]
RATE = ["1", "2", "3", "4", "5"]
MODS = {
    "candidates": dict(title="Recruitment", sub="Track applicants through your hiring pipeline", scope="hr", emp=False, status="stage", default={"stage": "Applied"},
        fields=[F("name", "Candidate name", req=1), F("job", "Position applied for", req=1), F("email", "Email", "email"), F("phone", "Phone"), F("source", "Source", "select", ["LinkedIn", "Referral", "Job portal", "Walk-in", "Other"]),
                F("expected", "Expected salary", "number"), F("stage", "Stage", "select", STAGES), F("interview", "Interview date", "date"), F("notes", "Notes", "textarea")],
        cols=[("name", "Candidate"), ("job", "Position"), ("stage", "Stage", "status"), ("interview", "Interview", "date"), ("source", "Source"), ("expected", "Expected", "money")], edit=["stage", "interview", "notes"]),
    "onboarding": dict(title="Onboarding & Offboarding", sub="Checklists for new joiners and leavers", scope="mgr", emp=True, status="status", default={"status": "To do"},
        fields=[F("category", "Type", "select", ["Onboarding", "Offboarding"]), F("task", "Task", req=1), F("due", "Due date", "date"), F("status", "Status", "select", ["To do", "In progress", "Done"])],
        cols=[("emp", "Employee"), ("category", "Type"), ("task", "Task"), ("due", "Due", "date"), ("status", "Status", "status")], edit=["status", "due"], owner_edit=True),
    "goals": dict(title="Goals & KPIs", sub="Set targets and track progress", scope="own", emp=True, status="status", default={"status": "On track", "progress": "0"}, owner_edit=True, owner_add_any=True,
        fields=[F("title", "Goal / KPI", req=1), F("metric", "How it is measured"), F("due", "Target date", "date"), F("progress", "Progress %", "number"), F("status", "Status", "select", ["On track", "At risk", "Completed"])],
        cols=[("emp", "Employee"), ("title", "Goal"), ("metric", "Measure"), ("due", "Target", "date"), ("progress", "Progress", "pct"), ("status", "Status", "status")], edit=["progress", "status"]),
    "reviews": dict(title="Performance Reviews", sub="Periodic ratings (1 to 5) from managers", scope="mgr", emp=True, hide_status=True, default={},
        fields=[F("period", "Review period (e.g. Q4 2026)", req=1), F("quality", "Quality of work", "select", RATE), F("productivity", "Productivity", "select", RATE), F("teamwork", "Teamwork", "select", RATE),
                F("compliance", "Compliance & accuracy", "select", RATE), F("comments", "Comments", "textarea")],
        cols=[("emp", "Employee"), ("period", "Period"), ("quality", "Quality"), ("productivity", "Productivity"), ("teamwork", "Teamwork"), ("compliance", "Compliance"), ("overall", "Overall", "stars")], edit=[], extra=["overall REAL"]),
    "trainings": dict(title="Training & Certifications", sub="HIPAA, compliance and coding certifications with expiry tracking", scope="mgr", emp=True, status="state", default={},
        fields=[F("name", "Training / certification", req=1), F("completed", "Completed on", "date"), F("expires", "Expires on", "date"), F("notes", "Notes")],
        cols=[("emp", "Employee"), ("name", "Training"), ("completed", "Completed", "date"), ("expires", "Expires", "date"), ("state", "Status", "status")], edit=["expires"], calc=True,
        suggest=["HIPAA Awareness", "Compliance Refresher", "Coding Certification (CPC/CCS)", "Payer Policy Update", "Customer Service"]),
    "expenses": dict(title="Expense Claims", sub="Submit expenses; approved claims are reimbursed in payroll", scope="own", emp=True, status="status", default={"status": "Pending"},
        fields=[F("day", "Expense date", "date", req=1), F("category", "Category", "select", ["Travel", "Internet / phone", "Equipment", "Training", "Medical", "Other"]), F("amount", "Amount", "number", req=1), F("description", "Description", "textarea"), F("status", "Status", "select", ["Pending", "Approved", "Rejected", "Reimbursed"])],
        cols=[("emp", "Employee"), ("day", "Date", "date"), ("category", "Category"), ("amount", "Amount", "money"), ("description", "Description"), ("status", "Status", "status")], edit=["status"], hidef=["status"]),
    "loans": dict(title="Loans & Advances", sub="Salary advances repaid through monthly payroll deductions", scope="own", emp=True, status="status", default={"status": "Pending"},
        fields=[F("kind", "Type", "select", ["Advance", "Loan"]), F("amount", "Amount", "number", req=1), F("installment", "Monthly installment", "number", req=1), F("reason", "Reason", "textarea"), F("status", "Status", "select", ["Pending", "Active", "Rejected", "Closed"])],
        cols=[("emp", "Employee"), ("kind", "Type"), ("amount", "Amount", "money"), ("installment", "Installment", "money"), ("balance", "Balance", "money"), ("status", "Status", "status")], edit=["status", "installment"], extra=["balance REAL"], hidef=["status"]),
    "regularizations": dict(title="Attendance Corrections", sub="Missed a punch? Request a correction for approval", scope="own", emp=True, status="status", default={"status": "Pending"},
        fields=[F("day", "Date", "date", req=1), F("check_in", "Check-in time", "time", req=1), F("check_out", "Check-out time", "time"), F("reason", "Reason", "textarea", req=1), F("status", "Status", "select", ["Pending", "Approved", "Rejected"])],
        cols=[("emp", "Employee"), ("day", "Date", "date"), ("check_in", "In"), ("check_out", "Out"), ("reason", "Reason"), ("status", "Status", "status")], edit=["status"], hidef=["status"]),
    "tickets": dict(title="HR Helpdesk", sub="Ask HR a question or raise an issue", scope="own", emp=True, status="status", default={"status": "Open"},
        fields=[F("category", "Category", "select", ["Payroll", "Leave", "Attendance", "IT / equipment", "Policy", "Other"]), F("subject", "Subject", req=1), F("body", "Details", "textarea"), F("status", "Status", "select", ["Open", "In progress", "Resolved"]), F("response", "HR response", "textarea")],
        cols=[("emp", "Employee"), ("category", "Category"), ("subject", "Subject"), ("status", "Status", "status"), ("response", "HR response")], edit=["status", "response"], hidef=["status", "response"]),
    "tasks": dict(title="Tasks", sub="Assign and track work for your team", scope="mgr", emp=True, status="status", default={"status": "To do", "priority": "Normal"}, owner_edit=True, notify_add="New task assigned: ",
        fields=[F("title", "Task", req=1), F("priority", "Priority", "select", ["Low", "Normal", "High", "Urgent"]), F("due", "Due date", "date"), F("status", "Status", "select", ["To do", "In progress", "Done"])],
        cols=[("emp", "Assigned to"), ("title", "Task"), ("priority", "Priority", "status"), ("due", "Due", "date"), ("status", "Status", "status")], edit=["status", "due"]),
    "letters": dict(title="HR Letters & Certificates", sub="Request employment, salary or experience letters", scope="own", emp=True, status="status", default={"status": "Pending"},
        fields=[F("kind", "Letter", "select", ["Employment verification letter", "Salary certificate", "Experience letter", "No objection certificate (NOC)"]), F("purpose", "Purpose / addressed to"), F("status", "Status", "select", ["Pending", "Approved", "Rejected"])],
        cols=[("emp", "Employee"), ("kind", "Letter"), ("purpose", "Purpose"), ("status", "Status", "status")], edit=["status"], hidef=["status"]),
    "assets": dict(title="Company Assets", sub="Laptops, headsets and equipment issued to staff", scope="hr", emp=True, emp_optional=True, status="status", default={"status": "In stock"},
        fields=[F("name", "Asset", req=1), F("tag", "Asset tag / serial"), F("kind", "Type", "select", ["Laptop", "Desktop", "Headset", "Monitor", "Mobile", "Other"]), F("issued", "Issued on", "date"), F("status", "Status", "select", ["In use", "In stock", "Repair", "Retired"])],
        cols=[("name", "Asset"), ("tag", "Tag"), ("kind", "Type"), ("emp", "Assigned to"), ("issued", "Issued", "date"), ("status", "Status", "status")], edit=["employee_id", "status", "issued"]),
}
for _k, _m in MODS.items():
    cols = ["id INTEGER PRIMARY KEY", "employee_id INTEGER", "created TEXT"] + ["%s %s" % (f["k"], "REAL" if f["t"] == "number" else "TEXT") for f in _m["fields"]] + _m.get("extra", [])
    EXTRA_SQL.append("CREATE TABLE IF NOT EXISTS %s(%s);" % (_k, ", ".join(cols)))
EXTRA_SQL += [
    "CREATE TABLE IF NOT EXISTS productivity(id INTEGER PRIMARY KEY, employee_id INTEGER, day TEXT, claims INTEGER DEFAULT 0, ar INTEGER DEFAULT 0, charts INTEGER DEFAULT 0, calls INTEGER DEFAULT 0, quality REAL, notes TEXT, UNIQUE(employee_id, day));",
    "CREATE TABLE IF NOT EXISTS docs(id INTEGER PRIMARY KEY, employee_id INTEGER, title TEXT, category TEXT, stored TEXT, orig TEXT, expires TEXT, uploaded TEXT, uploader TEXT);",
    "CREATE TABLE IF NOT EXISTS policies(id INTEGER PRIMARY KEY, title TEXT, category TEXT, body TEXT, created TEXT);",
    "CREATE TABLE IF NOT EXISTS acks(id INTEGER PRIMARY KEY, policy_id INTEGER, employee_id INTEGER, ts TEXT, UNIQUE(policy_id, employee_id));"]

NAV = [("People", [("Directory", "employees", "mgr"), ("Org Chart", "org", "all"), ("Recruitment", "m:candidates", "hr"), ("Onboarding", "m:onboarding", "all"), ("Assets", "m:assets", "hr"), ("Recognition", "kudos", "all"), ("Polls", "polls", "all")]),
       ("Time & Leave", [("Attendance", "attendance", "all"), ("Team Calendar", "team_calendar", "mgr"), ("Daily Attendance", "attendance_day", "hr"), ("Leave", "leave", "all"), ("Corrections", "m:regularizations", "all"), ("Holidays", "holidays", "all")]),
       ("Pay", [("Payroll", "payroll", "hr"), ("Expenses", "m:expenses", "all"), ("Loans & Advances", "m:loans", "all")]),
       ("Performance", [("Productivity", "productivity", "all"), ("Dialer", "dialer", "all"), ("Tasks", "m:tasks", "all"), ("Goals & KPIs", "m:goals", "all"), ("Reviews", "m:reviews", "all")]),
       ("Compliance", [("Training & Certs", "m:trainings", "all"), ("Documents", "documents", "all"), ("Policies", "policies", "all")]),
       ("Support", [("HR Helpdesk", "m:tickets", "all"), ("HR Letters", "m:letters", "all"), ("Announcements", "announcements", "all")]),
       ("Admin", [("Reports", "reports", "hr"), ("Users", "users", "hr"), ("Access Rights", "access", "admin"), ("Audit Log", "audit_log", "admin"), ("Settings", "settings", "admin")])]


@app.context_processor
def _nav():
    if not g.get("user"):
        return dict(NAV=[])
    out = []
    for grp, items in NAV:
        its = [(l, url_for("module", key=e[2:]) if e.startswith("m:") else url_for(e), (e[2:] if e.startswith("m:") else e)) for l, e, lvl in items if can(e)]
        if its:
            out.append((grp, its))
    return dict(NAV=out)


def team_ids():
    return subtree_ids(g.user["employee_id"])


def emp_choices():
    sc, sa = scope_sql("id")
    rows = q("SELECT id, full_name FROM employees WHERE status='Active'" + sc + " ORDER BY full_name", sa)
    return opts(rows, "id", "full_name")


def onboard(eid, kind):
    tasks = {"Onboarding": ["Collect documents (ID, contract, certificates)", "Create work email and system accounts", "Issue laptop / headset", "Complete HIPAA awareness training", "Introduce to team and assign a buddy", "Set up payroll and bank details"],
             "Offboarding": ["Return company assets", "Revoke system and EHR access", "Exit interview", "Final settlement", "Update records"]}[kind]
    due = (now().date() + timedelta(days=7)).isoformat()
    for t in tasks:
        ex("INSERT INTO onboarding(employee_id,created,category,task,due,status) VALUES(?,?,?,?,?,'To do')", (eid, datetime.now().isoformat(), kind, t, due))


def settle(rid):
    """On payroll finalize: reduce loan balances and mark approved expenses as reimbursed."""
    for s in q("SELECT * FROM slips WHERE run_id=?", (rid,)):
        if s["loan_ded"]:
            for l in q("SELECT * FROM loans WHERE employee_id=? AND status='Active' ORDER BY id", (s["employee_id"],)):
                pay = min(l["installment"] or 0, l["balance"] or 0)
                nb = round((l["balance"] or 0) - pay, 2)
                ex("UPDATE loans SET balance=?, status=? WHERE id=?", (nb, "Closed" if nb <= 0 else "Active", l["id"]))
        if s["reimb"]:
            ex("UPDATE expenses SET status='Reimbursed' WHERE employee_id=? AND status='Approved'", (s["employee_id"],))


def _hook_loans(old, new):
    if new.get("status") == "Active" and old["balance"] is None:
        ex("UPDATE loans SET balance=amount WHERE id=?", (old["id"],))
        audit("loan_approved", "loan #%s" % old["id"])


def _hook_reg(old, new):
    if new.get("status") == "Approved" and old["status"] != "Approved":
        emp = q("SELECT * FROM employees WHERE id=?", (old["employee_id"],), True)
        sh = datetime.strptime(emp["shift_start"] or "09:00", "%H:%M")
        late = datetime.strptime(old["check_in"] or "09:00", "%H:%M") > sh + timedelta(minutes=int(S("grace")))
        ex("INSERT INTO attendance(employee_id,day,check_in,check_out,status,note) VALUES(?,?,?,?,?,'Corrected on request') ON CONFLICT(employee_id,day) DO UPDATE SET check_in=excluded.check_in, check_out=excluded.check_out, status=excluded.status, note=excluded.note",
           (old["employee_id"], old["day"], old["check_in"], old["check_out"], "Late" if late else "Present"))
        audit("attendance_corrected", "%s %s" % (emp["full_name"], old["day"]))


def _hook_review_add(rid, vals):
    n = [int(vals.get(k) or 0) for k in ("quality", "productivity", "teamwork", "compliance")]
    ex("UPDATE reviews SET overall=? WHERE id=?", (round(sum(n) / 4, 2), rid))


@app.route("/m/<key>", methods=["GET", "POST"])
@need()
def module(key):
    M = MODS.get(key) or abort(404)
    role, me = g.user["role"], g.user["employee_id"]
    scope = M["scope"]
    hr = role in HR or (scope == "hr" and can("m:" + key))
    mgr = (role in MGR or g.has_team) and not hr
    if scope == "hr" and not hr:
        abort(403)
    t = key
    can_add = hr if scope == "hr" else ((role in MGR or g.has_team) if scope == "mgr" else True)
    if M.get("owner_add_any"):
        can_add = True
    team = set(team_ids()) if (mgr or g.has_team) else set()

    def can_edit(rec):
        if hr:
            return True
        if scope == "hr":
            return False
        if rec["employee_id"] == me:
            return bool(M.get("owner_edit"))
        return mgr and rec["employee_id"] in team

    if request.method == "POST":
        act = request.form.get("act")
        if act == "add" and can_add:
            vals = {}
            for f in M["fields"]:
                v = (request.form.get(f["k"]) or "").strip()
                if f["k"] in M.get("hidef", []) and not hr and not mgr:
                    v = ""
                if not v and f["k"] in M["default"]:
                    v = str(M["default"][f["k"]])
                if f["req"] and not v:
                    flash("%s is required." % f["l"], "err")
                    return redirect(url_for("module", key=key))
                vals[f["k"]] = float(v or 0) if f["t"] == "number" else v
            eid = request.form.get("employee_id") or me
            if M["emp"] and (hr or role in MGR or g.has_team):
                eid = int(eid) if str(eid).isdigit() else (None if M.get("emp_optional") else me)
            elif not M.get("emp_optional"):
                eid = me
            if not M["emp"]:
                eid = None
            if key == "loans" or key == "expenses" or key == "regularizations" or key == "tickets":
                if not (hr or mgr):
                    vals["status"] = M["default"]["status"]
                if mgr and not hr and eid == me:
                    vals["status"] = M["default"]["status"]
            cols = ["employee_id", "created"] + list(vals)
            rid = ex("INSERT INTO %s(%s) VALUES(%s)" % (t, ",".join(cols), ",".join("?" * len(cols))), [eid, datetime.now().isoformat()] + list(vals.values()))
            if key == "reviews":
                _hook_review_add(rid, vals)
                audit("review_added", "employee #%s %s" % (eid, vals.get("period")))
            if M.get("notify_add") and eid and eid != me:
                A.notify_emp(eid, M["notify_add"] + str(vals.get("title", "")), url_for("module", key=key))
            flash("Saved.", "ok")
        elif act == "edit":
            rec = q("SELECT * FROM %s WHERE id=?" % t, (request.form.get("id"),), True)
            if rec and can_edit(rec):
                new = {}
                for k in M["edit"]:
                    if k in request.form:
                        v = request.form.get(k, "").strip()
                        new[k] = (int(v) if v.isdigit() else None) if k == "employee_id" else v
                if new:
                    if mgr and not hr and rec["employee_id"] == me and "status" in new and not M.get("owner_edit"):
                        abort(403)
                    ex("UPDATE %s SET %s WHERE id=?" % (t, ",".join(k + "=?" for k in new)), list(new.values()) + [rec["id"]])
                    {"loans": _hook_loans, "regularizations": _hook_reg}.get(key, lambda o, n: None)(rec, new)
                    if key in ("expenses", "loans"):
                        audit(key + "_status", "#%s -> %s" % (rec["id"], new.get("status")))
                    if rec["employee_id"] and rec["employee_id"] != me and ("status" in new or "response" in new):
                        A.notify_emp(rec["employee_id"], "%s: your request was updated to %s" % (M["title"], new.get("status", "a reply from HR")), url_for("module", key=key))
                    flash("Updated.", "ok")
        elif act == "del":
            rec = q("SELECT * FROM %s WHERE id=?" % t, (request.form.get("id"),), True)
            if rec and (hr or (rec["employee_id"] == me and M.get("status") and rec[M["status"]] in ("Pending", "Open", "To do"))):
                ex("DELETE FROM %s WHERE id=?" % t, (rec["id"],))
        return redirect(url_for("module", key=key, status=request.args.get("status", "")))
    sel = "SELECT m.*, e.full_name emp, e.code ecode"
    args = []
    if M.get("calc"):
        td = now().date()
        sel += ", CASE WHEN m.expires IS NULL OR m.expires='' THEN 'No expiry' WHEN m.expires<? THEN 'Expired' WHEN m.expires<=? THEN 'Expiring' ELSE 'Valid' END state"
        args += [td.isoformat(), (td + timedelta(days=30)).isoformat()]
    sql = sel + " FROM %s m LEFT JOIN employees e ON e.id=m.employee_id WHERE 1=1" % t
    if not hr:
        sc, sa = scope_sql("m.employee_id")
        sql += sc; args += sa
    st = request.args.get("status", "")
    if st and M.get("status") and not M.get("calc"):
        sql += " AND m.%s=?" % M["status"]; args.append(st)
    rows = q(sql + (" ORDER BY m.expires" if key == "trainings" else " ORDER BY m.id DESC"), args)
    if st and M.get("calc"):
        rows = [r for r in rows if r["state"] == st]
    counts = {}
    if M.get("status"):
        for r in rows:
            counts[r[M["status"]]] = counts.get(r[M["status"]], 0) + 1
    ch = emp_choices()
    return render_template("module.html", M=M, key=key, rows=rows, can_add=can_add, hr=hr, ch=ch, counts=counts, st=st, edit_ok={r["id"]: can_edit(r) for r in rows},
                           pick_emp=M["emp"] and (hr or role in MGR or g.has_team), emp_edit_ch=opts(q("SELECT id, full_name FROM employees WHERE status='Active' ORDER BY full_name"), "id", "full_name") if "employee_id" in M["edit"] else [], me=me)


@app.route("/m/candidates/<int:cid>/hire", methods=["POST"])
@need(*HR)
def hire(cid):
    c = q("SELECT * FROM candidates WHERE id=?", (cid,), True) or abort(404)
    eid = ex("INSERT INTO employees(code,full_name,email,phone,designation,join_date,status,basic,created) VALUES(?,?,?,?,?,?,'Active',?,?)",
             ("EMP-%03d" % ((q("SELECT max(id) m FROM employees", one=True)["m"] or 0) + 1), c["name"], c["email"], c["phone"], c["job"], now().date().isoformat(), c["expected"] or 0, datetime.now().isoformat()))
    ex("UPDATE candidates SET stage='Hired' WHERE id=?", (cid,)); onboard(eid, "Onboarding"); audit("candidate_hired", c["name"])
    flash("%s was added as an employee. Complete their details and salary, then create a login." % c["name"], "ok")
    return redirect(url_for("employee_view", eid=eid, edit=1))


# ---------- analytics for dashboard ----------
def dash_data():
    n, td = now(), now().date()
    d = {}
    r = g.user["role"]
    if r in HR:
        dep = q("SELECT COALESCE(d.name,'Unassigned') n, count(*) c FROM employees e LEFT JOIN departments d ON d.id=e.department_id WHERE e.status='Active' GROUP BY n ORDER BY c DESC")
        active = max(q("SELECT count(*) c FROM employees WHERE status='Active'", one=True)["c"], 1)
        hol, days, rate = holiday_set(), [], []
        for i in range(20, -1, -1):
            x = td - timedelta(days=i)
            if is_off(x, hol) or x > td:
                continue
            c = q("SELECT count(*) c FROM attendance WHERE day=? AND status IN ('Present','Late','Half Day')", (x.isoformat(),), True)["c"]
            days.append(x.strftime("%d %b")); rate.append(round(c * 100 / active))
        pay = q("SELECT r.month, COALESCE(sum(s.net),0) t FROM runs r LEFT JOIN slips s ON s.run_id=r.id WHERE r.status='Final' GROUP BY r.id ORDER BY r.month DESC LIMIT 6")[::-1]
        lv = q("SELECT t.name, COALESCE(sum(l.days),0) d FROM leave_types t LEFT JOIN leaves l ON l.type_id=t.id AND l.status='Approved' AND substr(l.start,1,4)=? WHERE t.days<365 GROUP BY t.id", (str(td.year),))
        d["charts"] = json.dumps(dict(dep=[[x["n"] for x in dep], [x["c"] for x in dep]], att=[days[-14:], rate[-14:]], pay=[[x["month"] for x in pay], [round(x["t"]) for x in pay]], lv=[[x["name"] for x in lv], [x["d"] for x in lv]]))
        d["alerts"] = dict(leave=q("SELECT count(*) c FROM leaves WHERE status='Pending'", one=True)["c"], exp=q("SELECT count(*) c FROM expenses WHERE status='Pending'", one=True)["c"],
                           reg=q("SELECT count(*) c FROM regularizations WHERE status='Pending'", one=True)["c"], tix=q("SELECT count(*) c FROM tickets WHERE status!='Resolved'", one=True)["c"], loan=q("SELECT count(*) c FROM loans WHERE status='Pending'", one=True)["c"])
        lim = (td + timedelta(days=30)).isoformat()
        d["tr_exp"] = q("SELECT count(*) c FROM trainings WHERE expires!='' AND expires<=?", (lim,), True)["c"]
        d["doc_exp"] = q("SELECT count(*) c FROM docs WHERE expires!='' AND expires IS NOT NULL AND expires<=?", (lim,), True)["c"]
        hip = q("SELECT count(*) c FROM employees e WHERE e.status='Active' AND EXISTS(SELECT 1 FROM trainings t WHERE t.employee_id=e.id AND t.name LIKE '%HIPAA%' AND (t.expires='' OR t.expires IS NULL OR t.expires>=?))", (td.isoformat(),), True)["c"]
        d["hipaa"] = (hip, active)
        d["openings"] = q("SELECT count(*) c FROM candidates WHERE stage NOT IN ('Hired','Rejected')", one=True)["c"]
    mm = "%02d" % td.month
    d["bdays"] = q("SELECT id, photo, full_name, dob FROM employees WHERE status='Active' AND substr(dob,6,2)=? ORDER BY substr(dob,9,2)", (mm,))
    d["anniv"] = q("SELECT id, photo, full_name, join_date FROM employees WHERE status='Active' AND substr(join_date,6,2)=? AND substr(join_date,1,4)<? ORDER BY substr(join_date,9,2)", (mm, str(td.year)))
    d["away"] = q("SELECT DISTINCT e.full_name FROM leaves l JOIN employees e ON e.id=l.employee_id WHERE l.status='Approved' AND l.start<=? AND l.end>=?", (td.isoformat(), td.isoformat()))
    me = g.user["employee_id"]
    import extras2
    d.update(extras2.more_dash())
    d["my_goals"] = q("SELECT * FROM goals WHERE employee_id=? AND status!='Completed' ORDER BY due LIMIT 4", (me,))
    d["my_tasks"] = q("SELECT * FROM onboarding WHERE employee_id=? AND status!='Done' ORDER BY due LIMIT 5", (me,))
    d["kudos_recent"] = q("SELECT k.badge, k.message, a.full_name fname, b.full_name tname, b.id tid, b.photo tphoto FROM kudos k JOIN employees a ON a.id=k.from_emp JOIN employees b ON b.id=k.to_emp ORDER BY k.id DESC LIMIT 3")
    d["polls_open"] = q("SELECT count(*) c FROM polls p WHERE p.status='Open' AND NOT EXISTS(SELECT 1 FROM votes v WHERE v.poll_id=p.id AND v.employee_id=?)", (me,), True)["c"]
    d["my_tasks2"] = q("SELECT * FROM tasks WHERE employee_id=? AND status!='Done' ORDER BY due LIMIT 4", (me,))
    d["unack"] = q("SELECT count(*) c FROM policies p WHERE NOT EXISTS(SELECT 1 FROM acks a WHERE a.policy_id=p.id AND a.employee_id=?)", (me,), True)["c"]
    return d


# ---------- org chart & calendar ----------
@app.route("/org")
@need()
def org():
    rows = q("SELECT e.id, e.full_name, e.designation, e.level, e.manager_id, e.photo, d.name dept FROM employees e LEFT JOIN departments d ON d.id=e.department_id WHERE e.status='Active' ORDER BY e.full_name")
    me = g.user["employee_id"]
    if not full_view():
        keep = set(subtree_ids(me)) | {me}
        rows = [r for r in rows if r["id"] in keep]
    rank = {l: i for i, l in enumerate(A.LEVELS)}
    rows = sorted(rows, key=lambda r: (rank.get(r["level"], 99), r["full_name"]))
    kids = {}
    for r in rows:
        kids.setdefault(r["manager_id"], []).append(r)
    ids = {r["id"] for r in rows}

    def build(p, seen=()):
        return [dict(e=r, kids=build(r["id"], seen + (p,))) for r in kids.get(p, []) if r["id"] not in seen]
    roots = [dict(e=r, kids=build(r["id"], (r["id"],))) for r in rows if not r["manager_id"] or r["manager_id"] not in ids or (not full_view() and r["id"] == me)]
    byl = {}
    for r in rows:
        byl[r["level"] or "Unassigned"] = byl.get(r["level"] or "Unassigned", 0) + 1
    return render_template("org.html", roots=roots, total=len(rows), byl=byl, full=full_view(), me_id=me)


@app.route("/calendar")
@need(*MGR)
def team_calendar():
    m = request.args.get("month") or now().strftime("%Y-%m")
    first, last = month_bounds(m)
    sc, sa = scope_sql("id")
    emps = q("SELECT * FROM employees WHERE status='Active'" + sc + " ORDER BY full_name", sa)
    grid = []
    for e in emps:
        _, days = month_stats(e, m)
        grid.append((e, [s for _, s, _ in days]))
    return render_template("calendar.html", grid=grid, month=m, ndays=last.day, wd=[(first + timedelta(days=i)).strftime("%a")[0] for i in range(last.day)])


# ---------- productivity (billing-specific KPIs) ----------
@app.route("/productivity", methods=["GET", "POST"])
@need()
def productivity():
    role, me = g.user["role"], g.user["employee_id"]
    if request.method == "POST":
        eid = int(request.form.get("emp") or me) if (role in MGR or g.has_team) else me
        if eid != me and not can_see(eid):
            abort(403)
        v = [int(request.form.get(k) or 0) for k in ("claims", "ar", "charts", "calls")]
        ql = request.form.get("quality") or None
        ex("INSERT INTO productivity(employee_id,day,claims,ar,charts,calls,quality,notes) VALUES(?,?,?,?,?,?,?,?) ON CONFLICT(employee_id,day) DO UPDATE SET claims=?,ar=?,charts=?,calls=?,quality=?,notes=?",
           [eid, request.form["day"]] + v + [ql, request.form.get("notes", "")] + v + [ql, request.form.get("notes", "")])
        flash("Productivity saved.", "ok")
        return redirect(url_for("productivity"))
    m = request.args.get("month") or now().strftime("%Y-%m")
    first, last = month_bounds(m)
    sql = ("SELECT e.id, e.photo, e.full_name, e.daily_target, d.name dept, count(p.id) days, COALESCE(sum(p.claims),0) claims, COALESCE(sum(p.ar),0) ar, COALESCE(sum(p.charts),0) charts, COALESCE(sum(p.calls),0) calls, "
           "COALESCE(sum(p.claims+p.ar+p.charts+p.calls),0) units, avg(p.quality) quality FROM employees e LEFT JOIN departments d ON d.id=e.department_id LEFT JOIN productivity p ON p.employee_id=e.id AND p.day BETWEEN ? AND ? WHERE e.status='Active'")
    a = [first.isoformat(), last.isoformat()]
    sc, sa = scope_sql("e.id")
    sql += sc; a += sa
    rows = q(sql + " GROUP BY e.id ORDER BY units DESC", a)
    mine = q("SELECT * FROM productivity WHERE employee_id=? ORDER BY day DESC LIMIT 10", (me,))
    return render_template("productivity.html", rows=rows, mine=mine, month=m, ch=emp_choices() if (role in MGR or g.has_team) else [], chart=json.dumps([[r["full_name"].split()[0] for r in rows[:8]], [r["units"] for r in rows[:8]]]))


# ---------- documents ----------
OKEXT = {"pdf", "png", "jpg", "jpeg", "doc", "docx", "xls", "xlsx"}


@app.route("/documents", methods=["GET", "POST"])
@need()
def documents():
    role, me = g.user["role"], g.user["employee_id"]
    if request.method == "POST":
        f = request.files.get("file")
        eid = int(request.form.get("emp") or me) if (role in MGR or g.has_team) else me
        ext = (f.filename.rsplit(".", 1)[-1].lower() if f and "." in f.filename else "")
        if not f or ext not in OKEXT:
            flash("Choose a PDF, image, Word or Excel file.", "err")
        else:
            stored = secrets.token_hex(16) + "." + ext
            f.save(os.path.join(UPLOADS, stored))
            ex("INSERT INTO docs(employee_id,title,category,stored,orig,expires,uploaded,uploader) VALUES(?,?,?,?,?,?,?,?)",
               (eid, request.form.get("title") or f.filename, request.form.get("category", "Other"), stored, os.path.basename(f.filename), request.form.get("expires", ""), datetime.now().strftime("%Y-%m-%d"), g.user["username"]))
            audit("document_upload", "employee #%s %s" % (eid, request.form.get("title", "")))
            flash("Document uploaded.", "ok")
        return redirect(url_for("documents"))
    sc, sa = scope_sql("d.employee_id")
    rows = q("SELECT d.*, e.full_name emp FROM docs d LEFT JOIN employees e ON e.id=d.employee_id WHERE 1=1" + sc + " ORDER BY d.id DESC", sa)
    return render_template("documents.html", rows=rows, ch=emp_choices() if (role in MGR or g.has_team) else [], lim=(now().date() + timedelta(days=30)).isoformat())


@app.route("/documents/<int:did>")
@need()
def doc_download(did):
    d = q("SELECT * FROM docs WHERE id=?", (did,), True) or abort(404)
    if not can_see(d["employee_id"]):
        abort(403)
    audit("document_download", "doc #%s" % did)
    return send_file(os.path.join(UPLOADS, d["stored"]), as_attachment=True, download_name=d["orig"])


@app.route("/documents/<int:did>/delete", methods=["POST"])
@need(*HR)
def doc_delete(did):
    d = q("SELECT * FROM docs WHERE id=?", (did,), True) or abort(404)
    try:
        os.remove(os.path.join(UPLOADS, d["stored"]))
    except OSError:
        pass
    ex("DELETE FROM docs WHERE id=?", (did,)); audit("document_delete", "doc #%s" % did)
    return redirect(url_for("documents"))


# ---------- policies ----------
@app.route("/policies", methods=["GET", "POST"])
@need()
def policies():
    me, hr = g.user["employee_id"], g.user["role"] in HR
    if request.method == "POST":
        act = request.form.get("act")
        if act == "add" and hr and request.form.get("title"):
            ex("INSERT INTO policies(title,category,body,created) VALUES(?,?,?,?)", (request.form["title"], request.form.get("category", "General"), request.form.get("body", ""), datetime.now().strftime("%Y-%m-%d")))
        elif act == "ack" and me:
            ex("INSERT OR IGNORE INTO acks(policy_id,employee_id,ts) VALUES(?,?,?)", (request.form["id"], me, datetime.now().strftime("%Y-%m-%d %H:%M")))
        elif act == "del" and hr:
            ex("DELETE FROM acks WHERE policy_id=?", (request.form["id"],)); ex("DELETE FROM policies WHERE id=?", (request.form["id"],))
        return redirect(url_for("policies"))
    rows = q("SELECT * FROM policies ORDER BY id DESC")
    total = q("SELECT count(*) c FROM employees WHERE status='Active'", one=True)["c"]
    info = {}
    for p in rows:
        n = q("SELECT count(*) c FROM acks WHERE policy_id=?", (p["id"],), True)["c"]
        mine = q("SELECT 1 FROM acks WHERE policy_id=? AND employee_id=?", (p["id"], me), True) is not None
        miss = [r["full_name"] for r in q("SELECT full_name FROM employees e WHERE status='Active' AND NOT EXISTS(SELECT 1 FROM acks a WHERE a.policy_id=? AND a.employee_id=e.id)", (p["id"],))] if hr else []
        info[p["id"]] = (n, mine, miss)
    return render_template("policies.html", rows=rows, info=info, total=total)


# ---------- audit log & 2FA ----------
@app.route("/audit")
@need(*ADMIN)
def audit_log():
    return render_template("audit.html", rows=q("SELECT * FROM audit ORDER BY id DESC LIMIT 300"))


@app.route("/account/2fa", methods=["POST"])
@need()
def twofa():
    act = request.form.get("act")
    if act == "start":
        session["pending_totp"] = "".join(secrets.choice("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567") for _ in range(32))
    elif act == "confirm" and session.get("pending_totp"):
        if totp_ok(session["pending_totp"], request.form.get("code")):
            ex("UPDATE users SET totp=? WHERE id=?", (session.pop("pending_totp"), g.user["id"])); audit("2fa_enabled", g.user["username"]); flash("Two-factor authentication is on.", "ok")
        else:
            flash("That code did not match. Try again.", "err")
    elif act == "disable":
        from werkzeug.security import check_password_hash
        if check_password_hash(g.user["pw"], request.form.get("pw", "")):
            ex("UPDATE users SET totp=NULL WHERE id=?", (g.user["id"],)); audit("2fa_disabled", g.user["username"]); flash("Two-factor authentication is off.", "ok")
        else:
            flash("Password is incorrect.", "err")
    return redirect(url_for("account"))


@app.errorhandler(413)
def _big(e):
    flash("File is too large (5 MB maximum).", "err")
    return redirect(request.referrer or url_for("dashboard"))
