"""Care HCM - HR, attendance, leave and payroll for Code Care MB. Flask + SQLite."""
import os, sqlite3, secrets, string, csv, io, calendar, hmac, hashlib, base64, struct, time, json
from datetime import datetime, date, timedelta, timezone
from functools import wraps
from flask import Flask, g, render_template, request, redirect, url_for, session, flash, abort, Response
from werkzeug.security import generate_password_hash, check_password_hash
try:
    from zoneinfo import ZoneInfo
except Exception:  # pragma: no cover
    ZoneInfo = None

BASE = os.path.dirname(os.path.abspath(__file__))
DB = os.path.join(BASE, "data", "hcm.db")
KEYF = os.path.join(BASE, "data", "secret.key")
CREDF = os.path.join(BASE, "data", "admin_credentials.txt")
os.makedirs(os.path.join(BASE, "data"), exist_ok=True)


def _key():
    """One secret key shared by every server worker (created atomically so workers never end up with different keys)."""
    k = os.environ.get("HCM_SECRET_KEY", "").strip()
    if k:
        return k
    try:
        fd = os.open(KEYF, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
        with os.fdopen(fd, "w") as f:
            f.write(secrets.token_hex(32))
    except FileExistsError:
        pass
    for _ in range(60):  # another worker may still be writing the file
        try:
            k = open(KEYF).read().strip()
            if len(k) >= 32:
                return k
        except OSError:
            pass
        time.sleep(0.1)
    return secrets.token_hex(32)


app = Flask(__name__)
app.secret_key = _key()
app.config.update(SESSION_COOKIE_NAME="carehcm_session", SESSION_COOKIE_HTTPONLY=True, SESSION_COOKIE_SAMESITE="Lax",
                  SESSION_COOKIE_SECURE=os.environ.get("HCM_SECURE_COOKIES", "1") == "1",
                  PERMANENT_SESSION_LIFETIME=timedelta(hours=10), MAX_CONTENT_LENGTH=5 * 1024 * 1024)

EXTRA_SQL = []  # extras.py appends CREATE TABLE statements here
DEFAULTS = {"bio_mode": "optional", "ot_mult": "1.5", "tax_slabs": "", "company": "Code Care MB", "timezone": "Asia/Karachi", "weekend": "5,6", "grace": "15", "late_per_day": "3",
            "half_day_hours": "4", "tax_pct": "0", "pf_pct": "0", "currency": "PKR"}
DEPTS = ["Medical Billing", "AR Follow-up", "Medical Coding", "Credentialing", "Front Desk Support", "Quality & Compliance", "HR & Admin", "IT", "Management"]
LEAVES = [("Annual Leave", 14, 1), ("Sick Leave", 10, 1), ("Casual Leave", 8, 1), ("Unpaid Leave", 365, 0)]
SCHEMA = """
CREATE TABLE IF NOT EXISTS settings(k TEXT PRIMARY KEY, v TEXT);
CREATE TABLE IF NOT EXISTS departments(id INTEGER PRIMARY KEY, name TEXT UNIQUE);
CREATE TABLE IF NOT EXISTS employees(id INTEGER PRIMARY KEY, code TEXT UNIQUE, full_name TEXT NOT NULL, email TEXT, phone TEXT,
 department_id INTEGER, designation TEXT, manager_id INTEGER, join_date TEXT, status TEXT DEFAULT 'Active', emp_type TEXT DEFAULT 'Full-time',
 shift_start TEXT DEFAULT '09:00', shift_end TEXT DEFAULT '18:00', address TEXT, emergency TEXT, bank TEXT,
 basic REAL DEFAULT 0, house REAL DEFAULT 0, medical REAL DEFAULT 0, transport REAL DEFAULT 0, other REAL DEFAULT 0, fixed_ded REAL DEFAULT 0, created TEXT,
 dob TEXT, ot_eligible INTEGER DEFAULT 0, daily_target REAL DEFAULT 0, incentive_rate REAL DEFAULT 0, level TEXT, photo INTEGER DEFAULT 0);
CREATE TABLE IF NOT EXISTS role_perms(role TEXT, feature TEXT, allowed INTEGER, PRIMARY KEY(role, feature));
CREATE TABLE IF NOT EXISTS user_perms(user_id INTEGER, feature TEXT, allowed INTEGER, PRIMARY KEY(user_id, feature));
CREATE TABLE IF NOT EXISTS users(id INTEGER PRIMARY KEY, username TEXT UNIQUE NOT NULL, pw TEXT NOT NULL, role TEXT DEFAULT 'employee',
 employee_id INTEGER, active INTEGER DEFAULT 1, must_change INTEGER DEFAULT 0, totp TEXT);
CREATE TABLE IF NOT EXISTS notifications(id INTEGER PRIMARY KEY, user_id INTEGER, text TEXT, link TEXT, created TEXT, is_read INTEGER DEFAULT 0);
CREATE TABLE IF NOT EXISTS audit(id INTEGER PRIMARY KEY, ts TEXT, user TEXT, action TEXT, detail TEXT);
CREATE TABLE IF NOT EXISTS attendance(id INTEGER PRIMARY KEY, employee_id INTEGER, day TEXT, check_in TEXT, check_out TEXT, status TEXT, note TEXT, method TEXT, UNIQUE(employee_id, day));
CREATE TABLE IF NOT EXISTS leave_types(id INTEGER PRIMARY KEY, name TEXT UNIQUE, days INTEGER, paid INTEGER DEFAULT 1);
CREATE TABLE IF NOT EXISTS leaves(id INTEGER PRIMARY KEY, employee_id INTEGER, type_id INTEGER, start TEXT, end TEXT, days REAL, reason TEXT,
 status TEXT DEFAULT 'Pending', reviewer TEXT, note TEXT, created TEXT);
CREATE TABLE IF NOT EXISTS holidays(id INTEGER PRIMARY KEY, day TEXT UNIQUE, name TEXT);
CREATE TABLE IF NOT EXISTS announcements(id INTEGER PRIMARY KEY, title TEXT, body TEXT, author TEXT, created TEXT);
CREATE TABLE IF NOT EXISTS runs(id INTEGER PRIMARY KEY, month TEXT UNIQUE, status TEXT DEFAULT 'Draft', created TEXT);
CREATE TABLE IF NOT EXISTS slips(id INTEGER PRIMARY KEY, run_id INTEGER, employee_id INTEGER, working REAL, paid REAL, unpaid REAL, lates INTEGER,
 basic REAL, allow REAL, gross REAL, absent_ded REAL, late_ded REAL, tax REAL, pf REAL, fixed_ded REAL, bonus REAL DEFAULT 0, other_ded REAL DEFAULT 0, net REAL, note TEXT,
 ot_hours REAL DEFAULT 0, ot_pay REAL DEFAULT 0, incentive REAL DEFAULT 0, loan_ded REAL DEFAULT 0, reimb REAL DEFAULT 0);
"""


def db():
    if "db" not in g:
        g.db = sqlite3.connect(DB, timeout=15)
        g.db.row_factory = sqlite3.Row
        g.db.execute("PRAGMA foreign_keys=ON")
    return g.db


@app.teardown_appcontext
def _close(e):
    d = g.pop("db", None)
    if d:
        d.close()


def q(sql, a=(), one=False):
    r = db().execute(sql, a).fetchall()
    return (r[0] if r else None) if one else r


def ex(sql, a=()):
    c = db().execute(sql, a)
    db().commit()
    return c.lastrowid


SOCIAL = [("linkedin", "ri-linkedin-fill", "https://www.linkedin.com/company/codecaremb", "LinkedIn"), ("facebook", "ri-facebook-fill", "https://www.facebook.com/profile.php?id=61559749866358", "Facebook"),
          ("instagram", "ri-instagram-fill", "https://www.instagram.com/codecaremb/", "Instagram")]
SITE = "https://www.codecaremb.com/"


def pick_pw(raw=None):
    """Temporary password: the one typed by HR/admin (8+ characters) or a random one."""
    raw = (raw or "").strip()
    if raw:
        if len(raw) >= 8:
            return raw
        flash("The temporary password you typed was shorter than 8 characters, so a random one was generated instead.", "err")
    return "".join(secrets.choice(string.ascii_letters + string.digits) for _ in range(12))


def notify_user(uid, text, link=None):
    try:
        if uid and not (g.get("user") and g.user["id"] == uid):
            db().execute("INSERT INTO notifications(user_id,text,link,created) VALUES(?,?,?,?)", (uid, text[:200], link, datetime.now().strftime("%Y-%m-%d %H:%M")))
            db().commit()
    except Exception:
        pass


def notify_emp(eid, text, link=None):
    r = q("SELECT id FROM users WHERE employee_id=? AND active=1", (eid,), True)
    if r:
        notify_user(r["id"], text, link)


def notify_roles(roles, text, link=None):
    for r in q("SELECT id FROM users WHERE active=1 AND role IN (%s)" % ",".join("?" * len(roles)), list(roles)):
        notify_user(r["id"], text, link)


def audit(action, detail=""):
    try:
        who = g.user["username"] if g.get("user") else "system"
        db().execute("INSERT INTO audit(ts,user,action,detail) VALUES(?,?,?,?)", (datetime.now().strftime("%Y-%m-%d %H:%M:%S"), who, action, str(detail)[:300]))
        db().commit()
    except Exception:
        pass


def totp_code(secret, t=None, step=30):
    key = base64.b32decode(secret.upper() + "=" * (-len(secret) % 8))
    h = hmac.new(key, struct.pack(">Q", int((t or time.time()) // step)), hashlib.sha1).digest()
    o = h[-1] & 15
    return "%06d" % ((struct.unpack(">I", h[o:o + 4])[0] & 0x7FFFFFFF) % 1000000)


def totp_ok(secret, code):
    return any(hmac.compare_digest(totp_code(secret, time.time() + d * 30), (code or "").strip()) for d in (-1, 0, 1))


def S(k):
    r = q("SELECT v FROM settings WHERE k=?", (k,), True)
    return r["v"] if r else DEFAULTS[k]


def now():
    tz = S("timezone")
    try:
        return datetime.now(ZoneInfo(tz))
    except Exception:  # server without tz database: Pakistan Standard Time is fixed UTC+5
        return datetime.now(timezone(timedelta(hours=5 if tz == "Asia/Karachi" else 0)))


def init_db():
    c = sqlite3.connect(DB)
    c.executescript(SCHEMA)
    for sql in EXTRA_SQL:
        c.executescript(sql)
    for tbl, col, typ in [("employees", "dob", "TEXT"), ("employees", "level", "TEXT"), ("employees", "photo", "INTEGER DEFAULT 0"), ("employees", "ot_eligible", "INTEGER DEFAULT 0"), ("employees", "daily_target", "REAL DEFAULT 0"), ("employees", "incentive_rate", "REAL DEFAULT 0"),
                          ("users", "totp", "TEXT"), ("attendance", "method", "TEXT"), ("slips", "ot_hours", "REAL DEFAULT 0"), ("slips", "ot_pay", "REAL DEFAULT 0"), ("slips", "incentive", "REAL DEFAULT 0"),
                          ("slips", "loan_ded", "REAL DEFAULT 0"), ("slips", "reimb", "REAL DEFAULT 0")]:
        try:
            c.execute("ALTER TABLE %s ADD COLUMN %s %s" % (tbl, col, typ))
        except sqlite3.OperationalError:
            pass
    c.execute("PRAGMA journal_mode=WAL")
    for n in DEPTS:
        c.execute("INSERT OR IGNORE INTO departments(name) VALUES(?)", (n,))
    for n, d, p in LEAVES:
        c.execute("INSERT OR IGNORE INTO leave_types(name,days,paid) VALUES(?,?,?)", (n, d, p))
    if not c.execute("SELECT 1 FROM users").fetchone():
        env = os.environ.get("HCM_ADMIN_PASSWORD", "").strip()
        pw = env or "".join(secrets.choice(string.ascii_letters + string.digits) for _ in range(14))
        eid = c.execute("INSERT INTO employees(code,full_name,designation,join_date,created) VALUES('EMP-001','Admin','Administrator',?,?)",
                        (date.today().isoformat(), datetime.now().isoformat())).lastrowid
        c.execute("INSERT INTO users(username,pw,role,employee_id) VALUES('admin',?,'superadmin',?)", (generate_password_hash(pw), eid))
        if not env:
            with open(CREDF, "w") as f:
                f.write("Care HCM first login\nusername: admin\npassword: %s\n(delete this file after you log in and change the password)\n" % pw)
            os.chmod(CREDF, 0o600)
    # first admin becomes the Super Admin (older installs get promoted automatically)
    c.execute("UPDATE users SET role='superadmin' WHERE id=(SELECT min(id) FROM users WHERE role='admin') AND NOT EXISTS(SELECT 1 FROM users WHERE role='superadmin')")
    c.commit()
    c.close()


# ---------- security ----------
@app.before_request
def _guard():
    g.user = g.emp = None
    g.has_team, g.pr, g.pu = False, {}, {}
    if "_csrf" not in session:
        session["_csrf"] = secrets.token_hex(16)
    if session.get("uid"):
        g.user = q("SELECT * FROM users WHERE id=? AND active=1", (session["uid"],), True)
        if not g.user:
            session.clear()
        else:
            g.emp = q("SELECT * FROM employees WHERE id=?", (g.user["employee_id"],), True)
            if g.user["employee_id"]:
                g.has_team = q("SELECT 1 FROM employees WHERE manager_id=? AND status='Active' LIMIT 1", (g.user["employee_id"],), True) is not None
            g.pr = {r["feature"]: bool(r["allowed"]) for r in q("SELECT * FROM role_perms WHERE role=?", (g.user["role"],))}
            g.pu = {r["feature"]: bool(r["allowed"]) for r in q("SELECT * FROM user_perms WHERE user_id=?", (g.user["id"],))}
    if request.method == "POST" and (request.form.get("_csrf") or request.headers.get("X-CSRF")) != session.get("_csrf"):
        abort(400)
    if g.user and g.user["must_change"] and request.endpoint not in ("account", "logout", "static"):
        return redirect(url_for("account"))
    if g.user:
        f = feature_of(request.endpoint, request.view_args)
        if f and not can(f):
            abort(403)


@app.after_request
def _headers(r):
    r.headers.setdefault("X-Content-Type-Options", "nosniff")
    r.headers.setdefault("X-Frame-Options", "SAMEORIGIN")
    r.headers.setdefault("Referrer-Policy", "strict-origin-when-cross-origin")
    r.headers.setdefault("X-Robots-Tag", "noindex, nofollow")
    if request.endpoint != "static":
        r.headers.setdefault("Cache-Control", "no-store")
    return r


@app.context_processor
def _ctx():
    role = g.user["role"] if g.get("user") else None
    ht = bool(g.get("has_team"))
    return dict(SOCIAL=SOCIAL, SITE=SITE, csrf=session.get("_csrf", ""), role=role, is_hr=role in HR, is_mgr=role in MGR or ht, has_team=ht, can=can, is_admin=role in ADMIN, LEVELS=LEVELS, LEVEL_ROLE=LEVEL_ROLE,
                company=S("company") if os.path.exists(DB) else "Code Care MB", cur=S("currency"), today=now().date().isoformat())


def need(*roles):
    def deco(f):
        @wraps(f)
        def w(*a, **k):
            if not g.user:
                return redirect(url_for("login", next=request.path))
            if roles and g.user["role"] not in roles:
                feat = feature_of(request.endpoint, request.view_args)
                if not ((feat and can(feat)) or (set(roles) == set(MGR) and g.has_team)):
                    abort(403)
            return f(*a, **k)
        return w
    return deco


ADMIN = ("superadmin", "admin")
HR = ("superadmin", "admin", "hr")
MGR = ("superadmin", "admin", "hr", "manager")
ROLES = ["employee", "manager", "hr", "admin", "superadmin"]
FAILED = {}
LEVELS = ["CEO", "COO", "CHRO", "VP", "Director", "Assistant Director", "Senior Manager", "Manager", "Assistant Manager", "Supervisor", "Team Lead", "Representative"]
LEVEL_ROLE = {"CEO": "admin", "COO": "admin", "CHRO": "hr", "VP": "manager", "Director": "manager", "Assistant Director": "manager", "Senior Manager": "manager",
              "Manager": "manager", "Assistant Manager": "manager", "Supervisor": "manager", "Team Lead": "manager", "Representative": "employee"}
# (feature key, label, group, default access: all / team / hr / admin). Keys = endpoint names, or "m:<module>" for generic modules.
FEATURES = [("employees", "Employee directory / My Team", "People", "team"), ("employee_add", "Add & edit employees", "People", "hr"), ("org", "Organization chart", "People", "all"),
            ("m:candidates", "Recruitment", "People", "hr"), ("m:onboarding", "Onboarding & offboarding", "People", "all"), ("m:assets", "Company assets", "People", "hr"),
            ("attendance", "Attendance", "Time & Leave", "all"), ("team_calendar", "Team calendar", "Time & Leave", "team"), ("attendance_day", "Daily attendance (edit records)", "Time & Leave", "hr"),
            ("leave", "Leave", "Time & Leave", "all"), ("m:regularizations", "Attendance corrections", "Time & Leave", "all"), ("holidays", "Holidays", "Time & Leave", "all"),
            ("payroll", "Payroll", "Pay", "hr"), ("m:expenses", "Expense claims", "Pay", "all"), ("m:loans", "Loans & advances", "Pay", "all"),
            ("productivity", "Productivity", "Performance", "all"), ("dialer", "Dialer", "Performance", "all"), ("m:goals", "Goals & KPIs", "Performance", "all"), ("m:reviews", "Performance reviews", "Performance", "all"),
            ("m:trainings", "Training & certifications", "Compliance", "all"), ("documents", "Documents", "Compliance", "all"), ("policies", "Policies", "Compliance", "all"),
            ("m:tickets", "HR helpdesk", "Support", "all"), ("announcements", "Announcements", "Support", "all"), ("kudos", "Recognition wall", "People", "all"), ("polls", "Polls & surveys", "People", "all"), ("m:tasks", "Tasks", "Performance", "all"), ("m:letters", "HR letters & certificates", "Support", "all"),
            ("reports", "Reports", "Admin", "hr"), ("audit_log", "Audit log", "Admin", "admin"), ("settings", "Company settings", "Admin", "admin"),
            ("users", "Users (create & manage logins)", "Admin", "hr"), ("access", "Access rights (menus & settings per role/user)", "Admin", "admin"), ("view_all", "Company-wide data visibility (all employees, whole org chart)", "Admin", "hr")]
FDEFAULT = {f[0]: f[3] for f in FEATURES}
ENDPOINT_FEATURE = {"employees": "employees", "employee_new": "employee_add", "org": "org", "attendance": "attendance", "team_calendar": "team_calendar", "attendance_day": "attendance_day", "leave": "leave",
                    "holidays": "holidays", "payroll": "payroll", "payroll_run": "payroll", "productivity": "productivity", "dialer": "dialer", "documents": "documents", "policies": "policies",
                    "announcements": "announcements", "kudos": "kudos", "polls": "polls", "reports": "reports", "audit_log": "audit_log", "settings": "settings", "users": "users", "access": "access", "hire": "m:candidates"}


def feature_of(endpoint, view_args):
    if endpoint == "module":
        return "m:" + (view_args or {}).get("key", "")
    return ENDPOINT_FEATURE.get(endpoint)


def can(feature):
    """Effective permission: per-user override > per-role setting > built-in default."""
    u = g.get("user")
    if not u:
        return False
    if u["role"] == "superadmin":
        return True
    if feature in g.pu:
        return g.pu[feature]
    if feature in g.pr:
        return g.pr[feature]
    d, role = FDEFAULT.get(feature, "admin"), u["role"]
    return d == "all" or (d == "team" and (role in MGR or g.has_team)) or (d == "hr" and role in HR) or (d == "admin" and role in ADMIN)


def full_view():
    return g.user["role"] in HR or can("view_all")


SUB = "(WITH RECURSIVE t(id) AS (SELECT id FROM employees WHERE manager_id=? UNION SELECT e2.id FROM employees e2 JOIN t ON e2.manager_id=t.id) SELECT id FROM t)"


def subtree_ids(eid):
    return [r["id"] for r in q("WITH RECURSIVE t(id) AS (SELECT id FROM employees WHERE manager_id=? UNION SELECT e2.id FROM employees e2 JOIN t ON e2.manager_id=t.id) SELECT id FROM t", (eid,))]


def scope_sql(col="e.id"):
    """SQL fragment limiting rows to me + everyone below me in the reporting line (unless the user has company-wide visibility)."""
    if full_view():
        return "", []
    me = g.user["employee_id"]
    return " AND (%s IN %s OR %s=?)" % (col, SUB, col), [me, me]


def assignable_roles():
    r = g.user["role"]
    return ROLES if r == "superadmin" else ["employee", "manager", "hr"] if r == "admin" else ["employee", "manager"] if r == "hr" else []


def _ip():
    return (request.headers.get("X-Forwarded-For", request.remote_addr or "") or "").split(",")[0].strip()


def _safe(u):
    return u if u and u.startswith("/") and not u.startswith("//") and "\\" not in u else url_for("dashboard")


@app.route("/login", methods=["GET", "POST"])
def login():
    if request.method == "POST":
        ip, t = _ip(), now().timestamp()
        FAILED[ip] = [x for x in FAILED.get(ip, []) if t - x < 600]
        if len(FAILED[ip]) >= 6:
            return render_template("login.html", error="Too many failed attempts. Please wait 10 minutes.")
        if session.get("pre") and request.form.get("code") is not None:  # step 2: authenticator code
            u = q("SELECT * FROM users WHERE id=? AND active=1", (session["pre"],), True)
            if u and u["totp"] and totp_ok(u["totp"], request.form.get("code")):
                session.clear(); session["uid"] = u["id"]; session.permanent = True; session["_csrf"] = secrets.token_hex(16)
                g.user = u; audit("login", "2FA ok")
                return redirect(_safe(request.args.get("next")))
            FAILED[ip].append(t)
            return render_template("login.html", need_code=True, error="That code is not valid. Try the current code from your authenticator app.")
        u = q("SELECT * FROM users WHERE (lower(username)=? ) AND active=1", (request.form.get("username", "").strip().lower(),), True)
        if u and check_password_hash(u["pw"], request.form.get("password", "")):
            if u["totp"]:
                session.clear(); session["pre"] = u["id"]; session["_csrf"] = secrets.token_hex(16)
                return render_template("login.html", need_code=True)
            session.clear(); session["uid"] = u["id"]; session.permanent = True; session["_csrf"] = secrets.token_hex(16)
            g.user = u; audit("login", "")
            return redirect(_safe(request.args.get("next")))
        FAILED[ip].append(t)
        return render_template("login.html", error="Incorrect username or password.")
    session.pop("pre", None)
    return render_template("login.html")


@app.route("/logout")
def logout():
    session.clear()
    return redirect(url_for("login"))


@app.route("/account", methods=["GET", "POST"])
@need()
def account():
    if request.method == "POST":
        p, p2 = request.form.get("new", ""), request.form.get("new2", "")
        if not check_password_hash(g.user["pw"], request.form.get("old", "")):
            flash("Current password is incorrect.", "err")
        elif len(p) < 10 or p != p2:
            flash("New password must be 10+ characters and match the confirmation.", "err")
        else:
            ex("UPDATE users SET pw=?, must_change=0 WHERE id=?", (generate_password_hash(p), g.user["id"]))
            flash("Password updated.", "ok")
            return redirect(url_for("dashboard"))
    return render_template("account.html", has2fa=bool(g.user["totp"]), pending=session.get("pending_totp"), devices=q("SELECT * FROM webauthn WHERE user_id=?", (g.user["id"],)))


# ---------- calendar logic ----------
def month_bounds(m):
    y, mo = map(int, m.split("-"))
    return date(y, mo, 1), date(y, mo, calendar.monthrange(y, mo)[1])


def holiday_set():
    return {r["day"] for r in q("SELECT day FROM holidays")}


def is_off(d, hol):
    return str(d.weekday()) in S("weekend").split(",") or d.isoformat() in hol


def month_stats(emp, m):
    """Per-day status and counts for an employee in month m (YYYY-MM)."""
    first, last = month_bounds(m)
    hol = holiday_set()
    today = now().date()
    att = {r["day"]: r for r in q("SELECT * FROM attendance WHERE employee_id=? AND day BETWEEN ? AND ?", (emp["id"], first.isoformat(), last.isoformat()))}
    lv = q("SELECT l.*, t.paid FROM leaves l JOIN leave_types t ON t.id=l.type_id WHERE l.employee_id=? AND l.status='Approved' AND l.end>=? AND l.start<=?",
           (emp["id"], first.isoformat(), last.isoformat()))
    join = date.fromisoformat(emp["join_date"]) if emp["join_date"] else first
    c = dict(present=0, late=0, half=0, absent=0, leave_paid=0, leave_unpaid=0, working=0)
    days = []
    d = first
    while d <= last:
        iso, st = d.isoformat(), ""
        if d < join:
            st = "-"
        elif is_off(d, hol):
            st = "Off"
        else:
            c["working"] += 1
            L = next((x for x in lv if x["start"] <= iso <= x["end"]), None)
            a = att.get(iso)
            if L:
                st = "Leave"; c["leave_paid" if L["paid"] else "leave_unpaid"] += 1
            elif a and a["status"] in ("Present", "Late", "Half Day"):
                st = a["status"]
                if st == "Half Day":
                    c["half"] += 1
                else:
                    c["present"] += 1; c["late"] += st == "Late"
            elif d < today:
                st = "Absent"; c["absent"] += 1
            else:
                st = "Pending"
        days.append((iso, st, att.get(iso)))
        d += timedelta(days=1)
    return c, days


def tax_for(taxable):
    slabs = S("tax_slabs").strip()
    if not slabs:
        return taxable * float(S("tax_pct")) / 100
    annual, tax, prev = taxable * 12, 0.0, 0.0
    try:
        for part in slabs.split(","):
            upto, rate = part.split(":")
            upto, rate = float(upto), float(rate)
            if annual > prev:
                tax += (min(annual, upto) - prev) * rate / 100
            prev = upto
    except ValueError:
        return taxable * float(S("tax_pct")) / 100
    return tax / 12


def _hours(a, b):
    try:
        d = (datetime.strptime(b, "%H:%M") - datetime.strptime(a, "%H:%M")).total_seconds() / 3600
        return d + 24 if d < 0 else d
    except Exception:
        return 0


def slip_calc(emp, m):
    c, _ = month_stats(emp, m)
    first, last = month_bounds(m)
    dim = last.day
    allow = (emp["house"] or 0) + (emp["medical"] or 0) + (emp["transport"] or 0) + (emp["other"] or 0)
    gross = (emp["basic"] or 0) + allow
    per = gross / dim
    unpaid = c["absent"] + c["leave_unpaid"] + 0.5 * c["half"]
    lpd = max(int(S("late_per_day")), 1)
    late_ded = (c["late"] // lpd) * per
    # overtime (only for overtime-eligible staff)
    ot_hours = ot_pay = 0.0
    if emp["ot_eligible"]:
        shift = max(_hours(emp["shift_start"] or "09:00", emp["shift_end"] or "18:00"), 1)
        for r in q("SELECT check_in, check_out FROM attendance WHERE employee_id=? AND day BETWEEN ? AND ? AND check_in IS NOT NULL AND check_out IS NOT NULL", (emp["id"], first.isoformat(), last.isoformat())):
            ot_hours += max(0, _hours(r["check_in"], r["check_out"]) - shift)
        ot_pay = ot_hours * (gross / dim / shift) * float(S("ot_mult"))
    # productivity incentive (units above target)
    incentive = 0.0
    if (emp["daily_target"] or 0) > 0 and (emp["incentive_rate"] or 0) > 0:
        units = q("SELECT COALESCE(sum(claims+ar+charts+calls),0) u FROM productivity WHERE employee_id=? AND day BETWEEN ? AND ?", (emp["id"], first.isoformat(), last.isoformat()), True)["u"]
        incentive = max(0, units - emp["daily_target"] * (c["present"] + 0.5 * c["half"])) * emp["incentive_rate"]
    loan = sum(min(l["installment"] or 0, l["balance"] or 0) for l in q("SELECT * FROM loans WHERE employee_id=? AND status='Active'", (emp["id"],)))
    reimb = q("SELECT COALESCE(sum(amount),0) a FROM expenses WHERE employee_id=? AND status='Approved'", (emp["id"],), True)["a"]
    tax = tax_for(gross + ot_pay + incentive)
    pf = (emp["basic"] or 0) * float(S("pf_pct")) / 100
    ab = unpaid * per
    net = gross + ot_pay + incentive + reimb - ab - late_ded - tax - pf - (emp["fixed_ded"] or 0) - loan
    return dict(employee_id=emp["id"], working=c["working"], paid=c["working"] - unpaid, unpaid=unpaid, lates=c["late"], basic=emp["basic"] or 0, allow=allow, gross=gross,
                absent_ded=round(ab, 2), late_ded=round(late_ded, 2), tax=round(tax, 2), pf=round(pf, 2), fixed_ded=emp["fixed_ded"] or 0,
                ot_hours=round(ot_hours, 2), ot_pay=round(ot_pay, 2), incentive=round(incentive, 2), loan_ded=round(loan, 2), reimb=round(reimb, 2), net=round(net, 2))


def recompute(sid):
    s = q("SELECT * FROM slips WHERE id=?", (sid,), True)
    net = s["gross"] + s["bonus"] + s["ot_pay"] + s["incentive"] + s["reimb"] - s["absent_ded"] - s["late_ded"] - s["tax"] - s["pf"] - s["fixed_ded"] - s["other_ded"] - s["loan_ded"]
    ex("UPDATE slips SET net=? WHERE id=?", (round(net, 2), sid))


def can_see(eid):
    if full_view() or g.user["employee_id"] == eid:
        return True
    return eid in subtree_ids(g.user["employee_id"])


# ---------- dashboard ----------
@app.route("/")
@need()
def dashboard():
    t = now().date().isoformat()
    d = dict(ann=q("SELECT * FROM announcements ORDER BY id DESC LIMIT 4"),
             hol=q("SELECT * FROM holidays WHERE day>=? ORDER BY day LIMIT 4", (t,)))
    if g.user["role"] in HR:
        d["total"] = q("SELECT count(*) c FROM employees WHERE status='Active'", one=True)["c"]
        d["present"] = q("SELECT count(*) c FROM attendance WHERE day=? AND status IN ('Present','Late','Half Day')", (t,), True)["c"]
        d["late"] = q("SELECT count(*) c FROM attendance WHERE day=? AND status='Late'", (t,), True)["c"]
        d["onleave"] = q("SELECT count(DISTINCT employee_id) c FROM leaves WHERE status='Approved' AND start<=? AND end>=?", (t, t), True)["c"]
        d["pending"] = q("SELECT count(*) c FROM leaves WHERE status='Pending'", one=True)["c"]
        d["depts"] = 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")
        d["new"] = q("SELECT * FROM employees WHERE status='Active' ORDER BY id DESC LIMIT 5")
    if g.emp:
        d["rec"] = q("SELECT * FROM attendance WHERE employee_id=? AND day=?", (g.emp["id"], t), True)
        d["bal"] = balances(g.emp["id"])
        d["slip"] = q("SELECT s.*, r.month FROM slips s JOIN runs r ON r.id=s.run_id WHERE s.employee_id=? AND r.status='Final' ORDER BY r.month DESC LIMIT 1", (g.emp["id"],), True)
        d["pend_team"] = q("SELECT count(*) c FROM leaves l WHERE l.status='Pending' AND l.employee_id IN " + SUB, (g.emp["id"],), True)["c"]
    d.update(extras.dash_data())
    return render_template("dashboard.html", **d)


# ---------- employees ----------
EFIELDS = ["code", "full_name", "email", "phone", "department_id", "designation", "manager_id", "join_date", "status", "emp_type", "shift_start", "shift_end", "address", "emergency", "bank", "dob", "level"]
NUMS = ["basic", "house", "medical", "transport", "other", "fixed_ded", "daily_target", "incentive_rate"]


@app.route("/employees")
@need(*MGR)
def employees():
    s, dep = request.args.get("q", "").strip(), request.args.get("dept", "")
    sql = "SELECT e.*, d.name dept, m.full_name mgr, m.id mgr_id, m.photo mgr_photo FROM employees e LEFT JOIN departments d ON d.id=e.department_id LEFT JOIN employees m ON m.id=e.manager_id WHERE 1=1"
    a = []
    sc, sa = scope_sql("e.id")
    sql += sc; a += sa
    if s:
        sql += " AND (e.full_name LIKE ? OR e.code LIKE ? OR e.email LIKE ?)"; a += ["%" + s + "%"] * 3
    if dep:
        sql += " AND e.department_id=?"; a.append(dep)
    return render_template("employees.html", rows=q(sql + " ORDER BY e.status, e.full_name", a), depts=q("SELECT * FROM departments ORDER BY name"), s=s, dep=dep)


def mgr_opts(exclude=None):
    rows = q("SELECT id, full_name, level FROM employees WHERE status='Active' ORDER BY full_name")
    bad = set(subtree_ids(exclude)) | {exclude} if exclude else set()
    return [(r["id"], "%s%s" % (r["full_name"], " · " + r["level"] if r["level"] else "")) for r in rows if r["id"] not in bad]


def opts(rows, a="id", b="name"):
    return [(r[a], r[b]) for r in rows]


def _form_data():
    v = {k: request.form.get(k, "").strip() for k in EFIELDS}
    for k, dflt in (("status", "Active"), ("emp_type", "Full-time"), ("shift_start", "09:00"), ("shift_end", "18:00")):
        v[k] = v[k] or dflt
    for k in ("department_id", "manager_id"):
        v[k] = int(v[k]) if v[k] else None
    for k in NUMS:
        try:
            v[k] = float(request.form.get(k) or 0)
        except ValueError:
            v[k] = 0
    v["ot_eligible"] = 1 if request.form.get("ot_eligible") else 0
    return v


@app.route("/employees/new", methods=["GET", "POST"])
@need(*HR)
def employee_new():
    if request.method == "POST":
        v = _form_data()
        if not v["full_name"]:
            flash("Full name is required.", "err")
        else:
            nxt = (q("SELECT max(id) m FROM employees", one=True)["m"] or 0) + 1
            v["code"] = v["code"] or "EMP-%03d" % nxt
            v["join_date"] = v["join_date"] or now().date().isoformat()
            v["created"] = datetime.now().isoformat()
            try:
                eid = ex("INSERT INTO employees(%s) VALUES(%s)" % (",".join(v), ",".join("?" * len(v))), list(v.values()))
            except sqlite3.IntegrityError:
                flash("That employee code already exists.", "err")
                return render_template("employee_form.html", rolesel=assignable_roles(), e=v, dopts=opts(q("SELECT * FROM departments ORDER BY name")), mopts=mgr_opts(), new=True)
            audit("employee_create", v["full_name"])
            ph_ = request.files.get("photo")
            if ph_ and ph_.filename:
                ok_, msg_ = features.store_photo(eid, ph_)
                if not ok_:
                    flash("Employee saved, but the photo was not added: " + msg_, "err")
            extras.onboard(eid, "Onboarding")
            if request.form.get("login") and v["email"]:
                pw = pick_pw(request.form.get("temp_password"))
                try:
                    role_ = request.form.get("role", "employee")
                    role_ = role_ if role_ in assignable_roles() else "employee"
                    ex("INSERT INTO users(username,pw,role,employee_id,must_change) VALUES(?,?,?,?,1)", (v["email"].lower(), generate_password_hash(pw), role_, eid))
                    flash("Login created. Username: %s  |  Temporary password: %s  (shown once, share it securely)" % (v["email"].lower(), pw), "ok")
                except sqlite3.IntegrityError:
                    flash("Employee saved, but that email is already used as a username.", "err")
            else:
                flash("Employee added.", "ok")
            return redirect(url_for("employee_view", eid=eid))
    return render_template("employee_form.html", rolesel=assignable_roles(), e={"status": "Active", "emp_type": "Full-time", "shift_start": "09:00", "shift_end": "18:00"}, dopts=opts(q("SELECT * FROM departments ORDER BY name")),
                           mopts=mgr_opts(), new=True)


@app.route("/employees/<int:eid>", methods=["GET", "POST"])
@need()
def employee_view(eid):
    if not can_see(eid):
        abort(403)
    e = q("SELECT e.*, d.name dept, m.full_name mgr, m.id mgr_id, m.photo mgr_photo FROM employees e LEFT JOIN departments d ON d.id=e.department_id LEFT JOIN employees m ON m.id=e.manager_id WHERE e.id=?", (eid,), True) or abort(404)
    u = q("SELECT * FROM users WHERE employee_id=?", (eid,), True)
    if request.method == "POST" and g.user["role"] in HR:
        act = request.form.get("act")
        if act == "save":
            v = _form_data(); v.pop("code")
            if v["manager_id"] and (v["manager_id"] == eid or v["manager_id"] in subtree_ids(eid)):
                flash("Reporting line not saved: a person cannot report to themselves or to someone in their own team.", "err")
                return redirect(url_for("employee_view", eid=eid, edit=1))
            ex("UPDATE employees SET %s WHERE id=?" % ",".join(k + "=?" for k in v), list(v.values()) + [eid])
            audit("employee_edit", "%s (salary/details)" % e["full_name"])
            ph_ = request.files.get("photo")
            if ph_ and ph_.filename:
                ok_, msg_ = features.store_photo(eid, ph_)
                if not ok_:
                    flash("Details saved, but the photo was not updated: " + msg_, "err")
            if v["status"] == "Inactive" and e["status"] != "Inactive":
                extras.onboard(eid, "Offboarding")
            if v["status"] == "Inactive" and u:
                ex("UPDATE users SET active=0 WHERE employee_id=?", (eid,))
            flash("Saved.", "ok")
        elif act == "role" and u:
            nr = request.form.get("role")
            if nr not in assignable_roles() or (u["role"] in ADMIN and g.user["role"] != "superadmin") or u["id"] == g.user["id"]:
                flash("You are not allowed to set that role for this user.", "err"); return redirect(url_for("employee_view", eid=eid))
            ex("UPDATE users SET role=? WHERE id=?", (nr, u["id"])); audit("role_change", "%s -> %s" % (u["username"], request.form.get("role"))); flash("Role updated.", "ok")
        elif act == "reset" and u:
            if u["role"] in ADMIN and g.user["role"] != "superadmin":
                flash("Only a Super Admin can reset an admin password.", "err"); return redirect(url_for("employee_view", eid=eid))
            pw = pick_pw(request.form.get("temp_password"))
            ex("UPDATE users SET pw=?, must_change=1, active=1 WHERE id=?", (generate_password_hash(pw), u["id"])); audit("password_reset", u["username"])
            flash("Temporary password for %s: %s (shown once)" % (u["username"], pw), "ok")
        elif act == "mklogin" and not u and e["email"]:
            pw = pick_pw(request.form.get("temp_password"))
            try:
                ex("INSERT INTO users(username,pw,role,employee_id,must_change) VALUES(?,?,?,?,1)", (e["email"].lower(), generate_password_hash(pw), "employee", eid, ))
                flash("Login created. Username: %s | Temporary password: %s (shown once)" % (e["email"].lower(), pw), "ok")
            except sqlite3.IntegrityError:
                flash("That email is already a username.", "err")
        return redirect(url_for("employee_view", eid=eid))
    if request.args.get("edit") and g.user["role"] in HR:
        return render_template("employee_form.html", rolesel=assignable_roles(), e=e, dopts=opts(q("SELECT * FROM departments ORDER BY name")), mopts=mgr_opts(eid), new=False, u=u)
    m = now().strftime("%Y-%m")
    c, days_ = month_stats(e, m)
    att = c["present"] + 0.5 * c["half"]; den = att + c["absent"] + c["leave_unpaid"]
    att_rate = round(att * 100 / den) if den else 100
    jd = date.fromisoformat(e["join_date"]) if e["join_date"] else now().date(); mths = (now().year - jd.year) * 12 + now().month - jd.month
    tenure = ("%d yr %d mo" % (mths // 12, mths % 12)) if mths >= 12 else ("%d mo" % mths if mths else "New joiner")
    units = q("SELECT COALESCE(sum(claims+ar+charts+calls),0) u FROM productivity WHERE employee_id=? AND day>=?", (eid, m + "-01"), True)["u"]
    heat = [(iso[8:], st_) for iso, st_, _a in days_ if st_ != "-"]
    slips = q("SELECT s.*, r.month, r.status st FROM slips s JOIN runs r ON r.id=s.run_id WHERE s.employee_id=? ORDER BY r.month DESC LIMIT 6", (eid,))
    if g.user["role"] not in HR:
        slips = [s for s in slips if s["st"] == "Final"] if g.user["employee_id"] == eid else []
    team = q("WITH RECURSIVE t(id,depth) AS (SELECT id,1 FROM employees WHERE manager_id=? UNION SELECT e2.id,t.depth+1 FROM employees e2 JOIN t ON e2.manager_id=t.id) SELECT e.id, e.photo, e.full_name, e.level, e.designation, t.depth, e.status FROM t JOIN employees e ON e.id=t.id WHERE e.status='Active' ORDER BY t.depth, e.full_name", (eid,))
    return render_template("employee_view.html", e=e, u=u, c=c, month=m, bal=balances(eid), slips=slips, team=team, att_rate=att_rate, tenure=tenure, units=units, heat=heat, can_photo=(eid == g.user["employee_id"] or g.user["role"] in HR))


# ---------- attendance ----------
def do_punch(method="Web"):
    """Check in / check out using SERVER time (Pakistan Standard Time by default). Returns (ok, message)."""
    n = now(); t = n.strftime("%H:%M"); day = n.date().isoformat()
    r = q("SELECT * FROM attendance WHERE employee_id=? AND day=?", (g.emp["id"], day), True)
    if not r:
        sh, gr = datetime.strptime(g.emp["shift_start"] or "09:00", "%H:%M"), int(S("grace"))
        late = datetime.strptime(t, "%H:%M") > sh + timedelta(minutes=gr)
        ex("INSERT INTO attendance(employee_id,day,check_in,status,method) VALUES(?,?,?,?,?)", (g.emp["id"], day, t, "Late" if late else "Present", method))
        return True, "Checked in at %s PKT%s%s." % (t, " (late)" if late else "", " with fingerprint/biometric" if method == "Biometric" else "")
    if not r["check_out"]:
        hrs = _hours(r["check_in"], t)
        st = "Half Day" if hrs < float(S("half_day_hours")) else r["status"]
        ex("UPDATE attendance SET check_out=?, status=?, method=COALESCE(method,?) WHERE id=?", (t, st, method, r["id"]))
        return True, "Checked out at %s PKT. Worked %.1f hours." % (t, hrs)
    return False, "You have already checked out today."


@app.route("/attendance/punch", methods=["POST"])
@need()
def punch():
    if not g.emp:
        abort(403)
    ok, msg = do_punch("Web")
    flash(msg, "ok" if ok else "err")
    return redirect(request.referrer or url_for("dashboard"))


@app.route("/attendance")
@need()
def attendance():
    m = request.args.get("month") or now().strftime("%Y-%m")
    eid = int(request.args.get("emp") or (g.emp["id"] if g.emp else 0))
    if not can_see(eid):
        abort(403)
    e = q("SELECT * FROM employees WHERE id=?", (eid,), True) or abort(404)
    c, days = month_stats(e, m)
    sc, sa = scope_sql("id")
    team = q("SELECT id,full_name FROM employees WHERE status='Active'" + sc + " ORDER BY full_name", sa) if (full_view() or g.has_team) else []
    days = [(iso, date.fromisoformat(iso).strftime("%a"), st, a) for iso, st, a in days if st != "-"]
    return render_template("attendance.html", e=e, c=c, days=days, month=m, team=team)


@app.route("/attendance/day", methods=["GET", "POST"])
@need(*HR)
def attendance_day():
    day = request.values.get("day") or now().date().isoformat()
    if request.method == "POST":
        eid, st = int(request.form["emp"]), request.form["status"]
        ci, co, note = request.form.get("check_in") or None, request.form.get("check_out") or None, request.form.get("note", "")
        ex("INSERT INTO attendance(employee_id,day,check_in,check_out,status,note) VALUES(?,?,?,?,?,?) ON CONFLICT(employee_id,day) DO UPDATE SET check_in=?,check_out=?,status=?,note=?",
           (eid, day, ci, co, st, note, ci, co, st, note))
        flash("Attendance saved.", "ok")
        return redirect(url_for("attendance_day", day=day))
    rows = q("SELECT e.id, e.photo, e.full_name, e.code, a.check_in, a.check_out, a.status, a.note FROM employees e LEFT JOIN attendance a ON a.employee_id=e.id AND a.day=? WHERE e.status='Active' ORDER BY e.full_name", (day,))
    return render_template("attendance_day.html", rows=rows, day=day)


# ---------- leave ----------
def balances(eid):
    y = str(now().year)
    out = []
    for t in q("SELECT * FROM leave_types ORDER BY id"):
        used = q("SELECT COALESCE(sum(days),0) d FROM leaves WHERE employee_id=? AND type_id=? AND status='Approved' AND substr(start,1,4)=?", (eid, t["id"], y), True)["d"]
        out.append(dict(id=t["id"], name=t["name"], total=t["days"], used=used, left=t["days"] - used, paid=t["paid"]))
    return out


def leave_days(a, b):
    hol, n, d = holiday_set(), 0, a
    while d <= b:
        n += 0 if is_off(d, hol) else 1
        d += timedelta(days=1)
    return n


@app.route("/leave", methods=["GET", "POST"])
@need()
def leave():
    if request.method == "POST":
        act = request.form.get("act")
        if act == "apply" and g.emp:
            try:
                a, b = date.fromisoformat(request.form["start"]), date.fromisoformat(request.form["end"])
            except ValueError:
                flash("Enter valid dates.", "err"); return redirect(url_for("leave"))
            n = leave_days(a, b) if b >= a else 0
            if n <= 0:
                flash("No working days in that range.", "err")
            else:
                ex("INSERT INTO leaves(employee_id,type_id,start,end,days,reason,created) VALUES(?,?,?,?,?,?,?)",
                   (g.emp["id"], request.form["type"], a.isoformat(), b.isoformat(), n, request.form.get("reason", ""), datetime.now().isoformat()))
                flash("Leave request submitted (%s working days)." % n, "ok")
                mgr_ = g.emp["manager_id"]
                if mgr_:
                    notify_emp(mgr_, "%s requested leave (%s days) starting %s" % (g.emp["full_name"], n, a.isoformat()), url_for("leave"))
                notify_roles(("hr",), "%s requested leave (%s days)" % (g.emp["full_name"], n), url_for("leave"))
        elif act in ("approve", "reject") and (g.user["role"] in MGR or g.has_team):
            L = q("SELECT * FROM leaves WHERE id=?", (request.form["id"],), True)
            if L and can_see(L["employee_id"]) and L["employee_id"] != g.user["employee_id"] or (L and g.user["role"] in HR):
                ex("UPDATE leaves SET status=?, reviewer=?, note=? WHERE id=?", ("Approved" if act == "approve" else "Rejected", g.emp["full_name"] if g.emp else g.user["username"], request.form.get("note", ""), L["id"]))
                audit("leave_" + act, "request #%s" % L["id"]); notify_emp(L["employee_id"], "Your leave request (%s to %s) was %sd" % (L["start"], L["end"], act), url_for("leave")); flash("Request %sd." % act, "ok")
        elif act == "cancel":
            ex("UPDATE leaves SET status='Cancelled' WHERE id=? AND employee_id=? AND status='Pending'", (request.form["id"], g.user["employee_id"]))
        return redirect(url_for("leave"))
    mine = q("SELECT l.*, t.name tname FROM leaves l JOIN leave_types t ON t.id=l.type_id WHERE l.employee_id=? ORDER BY l.id DESC", (g.user["employee_id"],)) if g.emp else []
    todo = []
    if g.user["role"] in MGR or g.has_team:
        sql = "SELECT l.*, t.name tname, e.full_name, e.photo FROM leaves l JOIN leave_types t ON t.id=l.type_id JOIN employees e ON e.id=l.employee_id WHERE l.status='Pending' AND l.employee_id!=?"
        sc, sa = scope_sql("e.id")
        todo = q(sql + sc, [g.user["employee_id"] or 0] + sa)
    return render_template("leave.html", mine=mine, todo=todo, bal=balances(g.user["employee_id"]) if g.emp else [], types=q("SELECT * FROM leave_types"))


# ---------- payroll ----------
@app.route("/payroll", methods=["GET", "POST"])
@need(*HR)
def payroll():
    if request.method == "POST":
        m = request.form["month"]
        if not q("SELECT 1 FROM runs WHERE month=?", (m,), True):
            rid = ex("INSERT INTO runs(month,created) VALUES(?,?)", (m, datetime.now().isoformat()))
            _, last = month_bounds(m)
            for e in q("SELECT * FROM employees WHERE status='Active' AND (join_date IS NULL OR join_date<=?)", (last.isoformat(),)):
                s = slip_calc(e, m)
                if s["gross"] <= 0:
                    continue  # no salary structure set up yet
                s["run_id"] = rid
                ex("INSERT INTO slips(%s) VALUES(%s)" % (",".join(s), ",".join("?" * len(s))), list(s.values()))
            return redirect(url_for("payroll_run", rid=rid))
        flash("A payroll run for that month already exists.", "err")
    runs = q("SELECT r.*, count(s.id) n, COALESCE(sum(s.net),0) total FROM runs r LEFT JOIN slips s ON s.run_id=r.id GROUP BY r.id ORDER BY r.month DESC")
    return render_template("payroll.html", runs=runs, month=now().strftime("%Y-%m"))


@app.route("/payroll/<int:rid>", methods=["GET", "POST"])
@need(*HR)
def payroll_run(rid):
    r = q("SELECT * FROM runs WHERE id=?", (rid,), True) or abort(404)
    if request.method == "POST":
        act = request.form.get("act")
        if r["status"] == "Draft":
            if act == "adjust":
                ex("UPDATE slips SET bonus=?, other_ded=?, note=? WHERE id=? AND run_id=?", (float(request.form.get("bonus") or 0), float(request.form.get("other") or 0), request.form.get("note", ""), request.form["sid"], rid))
                recompute(request.form["sid"])
            elif act == "recalc":
                _, last = month_bounds(r["month"])
                for s in q("SELECT * FROM slips WHERE run_id=?", (rid,)):
                    e = q("SELECT * FROM employees WHERE id=?", (s["employee_id"],), True)
                    n = slip_calc(e, r["month"]); n.pop("employee_id")
                    ex("UPDATE slips SET %s WHERE id=?" % ",".join(k + "=?" for k in n), list(n.values()) + [s["id"]]); recompute(s["id"])
                flash("Recalculated from latest attendance.", "ok")
            elif act == "final":
                ex("UPDATE runs SET status='Final' WHERE id=?", (rid,)); extras.settle(rid); audit("payroll_final", r["month"])
                for s_ in q("SELECT id, employee_id FROM slips WHERE run_id=?", (rid,)):
                    notify_emp(s_["employee_id"], "Your payslip for %s is ready" % r["month"], url_for("payslip", sid=s_["id"]))
                flash("Payroll finalized. Employees can now see their payslips.", "ok")
            elif act == "delete":
                ex("DELETE FROM slips WHERE run_id=?", (rid,)); ex("DELETE FROM runs WHERE id=?", (rid,)); audit("payroll_delete", r["month"]); return redirect(url_for("payroll"))
        elif act == "reopen" and g.user["role"] in ADMIN:
            ex("UPDATE runs SET status='Draft' WHERE id=?", (rid,))
        return redirect(url_for("payroll_run", rid=rid))
    rows = q("SELECT s.*, e.full_name, e.code, e.bank, d.name dept FROM slips s JOIN employees e ON e.id=s.employee_id LEFT JOIN departments d ON d.id=e.department_id WHERE s.run_id=? ORDER BY e.full_name", (rid,))
    if request.args.get("csv"):
        o = io.StringIO(); w = csv.writer(o)
        w.writerow(["Code", "Employee", "Month", "Gross", "Overtime", "Incentive", "Reimbursement", "Absent ded", "Late ded", "Tax", "PF", "Fixed ded", "Loan ded", "Bonus", "Other ded", "Net", "Bank details"])
        for s in rows:
            w.writerow([s["code"], s["full_name"], r["month"], s["gross"], s["ot_pay"], s["incentive"], s["reimb"], s["absent_ded"], s["late_ded"], s["tax"], s["pf"], s["fixed_ded"], s["loan_ded"], s["bonus"], s["other_ded"], s["net"], s["bank"] or ""])
        return Response(o.getvalue(), mimetype="text/csv", headers={"Content-Disposition": "attachment; filename=payroll-%s.csv" % r["month"]})
    dep = {}
    for s_ in rows:
        dep[s_["dept"] or "Unassigned"] = dep.get(s_["dept"] or "Unassigned", 0) + s_["net"]
    return render_template("payroll_run.html", r=r, rows=rows, total=sum(s["net"] for s in rows), dep=sorted(dep.items(), key=lambda x: -x[1]))


@app.route("/payslip/<int:sid>")
@need()
def payslip(sid):
    s = q("SELECT s.*, r.month, r.status, e.full_name, e.code, e.designation, e.bank, d.name dept FROM slips s JOIN runs r ON r.id=s.run_id JOIN employees e ON e.id=s.employee_id LEFT JOIN departments d ON d.id=e.department_id WHERE s.id=?", (sid,), True) or abort(404)
    if g.user["role"] not in HR and not (s["employee_id"] == g.user["employee_id"] and s["status"] == "Final"):
        abort(403)
    return render_template("payslip.html", s=s)


# ---------- announcements, holidays ----------
@app.route("/announcements", methods=["GET", "POST"])
@need()
def announcements():
    if request.method == "POST" and g.user["role"] in HR:
        if request.form.get("del"):
            ex("DELETE FROM announcements WHERE id=?", (request.form["del"],))
        elif request.form.get("title"):
            ex("INSERT INTO announcements(title,body,author,created) VALUES(?,?,?,?)", (request.form["title"], request.form.get("body", ""), g.emp["full_name"] if g.emp else "HR", datetime.now().strftime("%Y-%m-%d %H:%M")))
        return redirect(url_for("announcements"))
    return render_template("announcements.html", rows=q("SELECT * FROM announcements ORDER BY id DESC"))


@app.route("/holidays", methods=["GET", "POST"])
@need()
def holidays():
    if request.method == "POST" and g.user["role"] in HR:
        if request.form.get("del"):
            ex("DELETE FROM holidays WHERE id=?", (request.form["del"],))
        elif request.form.get("day") and request.form.get("name"):
            ex("INSERT OR REPLACE INTO holidays(day,name) VALUES(?,?)", (request.form["day"], request.form["name"].strip()))
        return redirect(url_for("holidays"))
    return render_template("holidays.html", rows=q("SELECT * FROM holidays ORDER BY day"))


# ---------- reports ----------
@app.route("/reports")
@need(*HR)
def reports():
    m = request.args.get("month") or now().strftime("%Y-%m")
    rows = []
    for e in q("SELECT e.*, 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"):
        c, _ = month_stats(e, m); rows.append((e, c))
    if request.args.get("csv"):
        o = io.StringIO(); w = csv.writer(o); w.writerow(["Code", "Employee", "Department", "Working days", "Present", "Late", "Half days", "Absent", "Paid leave", "Unpaid leave"])
        for e, c in rows:
            w.writerow([e["code"], e["full_name"], e["dept"] or "", c["working"], c["present"], c["late"], c["half"], c["absent"], c["leave_paid"], c["leave_unpaid"]])
        return Response(o.getvalue(), mimetype="text/csv", headers={"Content-Disposition": "attachment; filename=attendance-%s.csv" % m})
    import extras2
    daily = json.dumps(extras2.daily_analysis(m, [e_ for e_, _ in rows]))
    lv = q("SELECT t.name, count(l.id) n, 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)=? GROUP BY t.id", (m[:4],))
    return render_template("reports.html", rows=rows, month=m, lv=lv, daily=daily)


# ---------- settings ----------
@app.route("/settings", methods=["GET", "POST"])
@need(*ADMIN)
def settings():
    if request.method == "POST":
        act = request.form.get("act")
        if act == "save":
            for k in DEFAULTS:
                if k == "weekend":
                    val = ",".join(request.form.getlist("weekend"))
                else:
                    val = request.form.get(k, DEFAULTS[k]).strip()
                ex("INSERT OR REPLACE INTO settings(k,v) VALUES(?,?)", (k, val))
            audit("settings_save", "company rules updated"); flash("Settings saved.", "ok")
        elif act == "dept" and request.form.get("name", "").strip():
            ex("INSERT OR IGNORE INTO departments(name) VALUES(?)", (request.form["name"].strip(),))
        elif act == "ltype" and request.form.get("name", "").strip():
            ex("INSERT OR REPLACE INTO leave_types(name,days,paid) VALUES(?,?,?)", (request.form["name"].strip(), int(request.form.get("days") or 0), 1 if request.form.get("paid") else 0))
        return redirect(url_for("settings"))
    return render_template("settings.html", cfg={k: S(k) for k in DEFAULTS}, depts=q("SELECT * FROM departments ORDER BY name"), types=q("SELECT * FROM leave_types"))


@app.errorhandler(403)
@app.errorhandler(404)
@app.errorhandler(400)
def _err(e):
    return render_template("error.html", code=e.code), e.code


import sys  # noqa: E402
sys.modules.setdefault("app", sys.modules[__name__])
import extras  # noqa: E402  (registers extra pages)
import extras2  # noqa: E402  (dialer, assistant, insights, PWA)
import bio  # noqa: E402  (fingerprint / WebAuthn check-in)
import access  # noqa: E402  (users and access rights)
import features  # noqa: E402  (photos, notifications, search, kudos, polls, letters)


def _locked_init():
    """Only one worker at a time may create/upgrade the database (workers can start simultaneously)."""
    lf = None
    try:
        import fcntl
        lf = open(os.path.join(BASE, "data", ".init.lock"), "w")
        fcntl.flock(lf, fcntl.LOCK_EX)
    except Exception:
        lf = None
    try:
        init_db()
    finally:
        if lf:
            lf.close()


_locked_init()
if __name__ == "__main__":
    app.config["SESSION_COOKIE_SECURE"] = False
    app.run(debug=False, port=5050)
