"""Care HCM modern features: profile photos, notifications, quick search, recognition wall, polls, HR letters, ID cards."""
import os, io, json, time
from datetime import datetime, timedelta
from flask import render_template, request, redirect, url_for, flash, abort, jsonify, send_file, g
import app as A
from app import app, q, ex, S, now, need, HR, MGR, can_see, audit, scope_sql, full_view, opts, notify_emp, notify_user, month_stats, balances, EXTRA_SQL

AV_DIR = os.path.join(A.BASE, "data", "avatars")
os.makedirs(AV_DIR, exist_ok=True)
EXTRA_SQL += [
    "CREATE TABLE IF NOT EXISTS kudos(id INTEGER PRIMARY KEY, from_emp INTEGER, to_emp INTEGER, badge TEXT, message TEXT, created TEXT);",
    "CREATE TABLE IF NOT EXISTS polls(id INTEGER PRIMARY KEY, question TEXT, options TEXT, status TEXT DEFAULT 'Open', created TEXT, author TEXT);",
    "CREATE TABLE IF NOT EXISTS votes(id INTEGER PRIMARY KEY, poll_id INTEGER, employee_id INTEGER, choice INTEGER, UNIQUE(poll_id, employee_id));"]


def _is_jpeg(b): return b[:3] == b"\xff\xd8\xff"
def _is_png(b): return b[:8] == b"\x89PNG\r\n\x1a\n"
def _is_webp(b): return b[:4] == b"RIFF" and b[8:12] == b"WEBP"


def store_photo(eid, fs):
    """Validate, square-crop (when Pillow is installed) and save an uploaded profile photo. Returns (ok, message)."""
    data = fs.read(900_001) if fs else b""
    if not data or len(data) > 900_000 or not (_is_jpeg(data) or _is_png(data) or _is_webp(data)):
        return False, "Choose a JPG, PNG or WebP image under 900 KB."
    try:  # re-encode as a clean 400x400 JPEG when Pillow is available
        from PIL import Image
        im = Image.open(io.BytesIO(data)).convert("RGB"); w, h = im.size; s = min(w, h)
        im = im.crop(((w - s) // 2, (h - s) // 2, (w + s) // 2, (h + s) // 2)).resize((400, 400))
        buf = io.BytesIO(); im.save(buf, "JPEG", quality=86, optimize=True); data = buf.getvalue()
    except ImportError:
        if not _is_jpeg(data):
            return False, "Please upload a JPG image."
    except Exception:
        return False, "That image could not be read."
    with open(os.path.join(AV_DIR, "%d.jpg" % eid), "wb") as fh:
        fh.write(data)
    ex("UPDATE employees SET photo=? WHERE id=?", (int(time.time()), eid)); audit("photo_updated", "employee #%s" % eid)
    return True, "ok"


@app.route("/employees/<int:eid>/photo", methods=["POST"])
@need()
def photo_upload(eid):
    if not (eid == g.user["employee_id"] or g.user["role"] in HR):
        abort(403)
    ok, msg = store_photo(eid, request.files.get("photo"))
    return (jsonify(ok=True, v=int(time.time())) if ok else (jsonify(ok=False, msg=msg), 400))


@app.route("/employees/<int:eid>/photo/delete", methods=["POST"])
@need()
def photo_delete(eid):
    if not (eid == g.user["employee_id"] or g.user["role"] in HR):
        abort(403)
    try:
        os.remove(os.path.join(AV_DIR, "%d.jpg" % eid))
    except OSError:
        pass
    ex("UPDATE employees SET photo=0 WHERE id=?", (eid,))
    flash("Profile photo removed.", "ok")
    return redirect(url_for("employee_view", eid=eid))


@app.route("/avatar/<int:eid>")
@need()
def avatar_img(eid):
    p = os.path.join(AV_DIR, "%d.jpg" % eid)
    if not os.path.exists(p):
        abort(404)
    r = send_file(p, mimetype="image/jpeg", max_age=86400)
    r.headers["Cache-Control"] = "private, max-age=86400"
    return r


@app.route("/notifications")
@need()
def notifications():
    rows = q("SELECT * FROM notifications WHERE user_id=? ORDER BY id DESC LIMIT 12", (g.user["id"],))
    n = q("SELECT count(*) c FROM notifications WHERE user_id=? AND is_read=0", (g.user["id"],), True)["c"]
    return jsonify(unread=n, items=[dict(id=r["id"], text=r["text"], link=r["link"], created=r["created"], read=bool(r["is_read"])) for r in rows])


@app.route("/notifications/read", methods=["POST"])
@need()
def notifications_read():
    nid = (request.get_json(silent=True) or {}).get("id")
    if nid:
        ex("UPDATE notifications SET is_read=1 WHERE id=? AND user_id=?", (nid, g.user["id"]))
    else:
        ex("UPDATE notifications SET is_read=1 WHERE user_id=?", (g.user["id"],))
    return jsonify(ok=True)


@app.route("/search")
@need()
def search():
    t = (request.args.get("q") or "").strip()
    if len(t) < 2:
        return jsonify(items=[])
    sc, sa = scope_sql("e.id")
    rows = q("SELECT e.id, e.full_name, e.designation, e.level, e.photo, e.code FROM employees e WHERE e.status='Active' AND (e.full_name LIKE ? OR e.code LIKE ? OR e.email LIKE ? OR e.designation LIKE ?)" + sc + " ORDER BY e.full_name LIMIT 6",
             ["%" + t + "%"] * 4 + sa)
    return jsonify(items=[dict(id=r["id"], name=r["full_name"], sub=" · ".join(x for x in (r["level"], r["designation"], r["code"]) if x), photo=r["photo"], url=url_for("employee_view", eid=r["id"])) for r in rows])


BADGES = [("Teamwork", "ri-team-fill"), ("Quality Star", "ri-star-smile-fill"), ("Above & Beyond", "ri-rocket-2-fill"), ("Customer Hero", "ri-heart-3-fill"), ("Problem Solver", "ri-lightbulb-flash-fill"), ("Mentor", "ri-user-star-fill")]


@app.route("/kudos", methods=["GET", "POST"])
@need()
def kudos():
    me = g.user["employee_id"]
    if request.method == "POST" and me:
        to = int(request.form.get("to") or 0)
        if to and to != me and request.form.get("message", "").strip():
            ex("INSERT INTO kudos(from_emp,to_emp,badge,message,created) VALUES(?,?,?,?,?)", (me, to, request.form.get("badge", "Teamwork"), request.form["message"].strip()[:300], datetime.now().strftime("%Y-%m-%d %H:%M")))
            notify_emp(to, "%s sent you recognition: %s" % (g.emp["full_name"], request.form.get("badge", "Teamwork")), url_for("kudos"))
            flash("Recognition sent. Thank you for appreciating a colleague!", "ok")
        else:
            flash("Choose a colleague and write a short message.", "err")
        return redirect(url_for("kudos"))
    feed = q("SELECT k.*, a.full_name fname, a.photo fphoto, b.full_name tname, 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 30")
    top = q("SELECT b.id, b.full_name, b.photo, count(k.id) n FROM kudos k JOIN employees b ON b.id=k.to_emp WHERE substr(k.created,1,7)=? GROUP BY b.id ORDER BY n DESC, b.full_name LIMIT 5", (now().strftime("%Y-%m"),))
    people = opts(q("SELECT id, full_name FROM employees WHERE status='Active' AND id!=? ORDER BY full_name", (me or 0,)), "id", "full_name")
    return render_template("kudos.html", feed=feed, top=top, people=people, badges=BADGES, icons=dict(BADGES))


@app.route("/polls", methods=["GET", "POST"])
@need()
def polls():
    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:
            ops = [o.strip() for o in request.form.get("options", "").splitlines() if o.strip()][:8]
            if request.form.get("question", "").strip() and len(ops) >= 2:
                ex("INSERT INTO polls(question,options,created,author) VALUES(?,?,?,?)", (request.form["question"].strip(), json.dumps(ops), datetime.now().strftime("%Y-%m-%d"), g.emp["full_name"] if g.emp else "HR"))
                for u in q("SELECT id FROM users WHERE active=1"):
                    notify_user(u["id"], "New poll: " + request.form["question"].strip()[:80], url_for("polls"))
                flash("Poll published.", "ok")
            else:
                flash("Enter a question and at least two options (one per line).", "err")
        elif act == "vote" and me:
            ex("INSERT OR IGNORE INTO votes(poll_id,employee_id,choice) VALUES(?,?,?)", (request.form["id"], me, int(request.form.get("choice", 0))))
        elif act in ("close", "reopen", "delete") and hr:
            if act == "delete":
                ex("DELETE FROM votes WHERE poll_id=?", (request.form["id"],)); ex("DELETE FROM polls WHERE id=?", (request.form["id"],))
            else:
                ex("UPDATE polls SET status=? WHERE id=?", ("Closed" if act == "close" else "Open", request.form["id"]))
        return redirect(url_for("polls"))
    out = []
    for p in q("SELECT * FROM polls ORDER BY id DESC"):
        ops = json.loads(p["options"]); counts = [0] * len(ops)
        for v in q("SELECT choice, count(*) c FROM votes WHERE poll_id=? GROUP BY choice", (p["id"],)):
            if 0 <= v["choice"] < len(ops):
                counts[v["choice"]] = v["c"]
        mine = q("SELECT choice FROM votes WHERE poll_id=? AND employee_id=?", (p["id"], me), True)
        out.append(dict(p=p, ops=ops, counts=counts, total=sum(counts), mine=mine["choice"] if mine else None))
    return render_template("polls.html", polls=out)


@app.route("/letter/<int:lid>")
@need()
def letter(lid):
    L = q("SELECT * FROM letters WHERE id=?", (lid,), True) or abort(404)
    if L["status"] != "Approved" or not (g.user["role"] in HR or L["employee_id"] == g.user["employee_id"]):
        abort(403)
    e = q("SELECT e.*, d.name dept FROM employees e LEFT JOIN departments d ON d.id=e.department_id WHERE e.id=?", (L["employee_id"],), True)
    gross = (e["basic"] or 0) + (e["house"] or 0) + (e["medical"] or 0) + (e["transport"] or 0) + (e["other"] or 0)
    audit("letter_printed", "letter #%s" % lid)
    return render_template("letter.html", L=L, e=e, gross=gross, today=now().strftime("%d %B %Y"))


@app.route("/idcard/<int:eid>")
@need()
def idcard(eid):
    if not (eid == g.user["employee_id"] or g.user["role"] in HR):
        abort(403)
    e = q("SELECT e.*, d.name dept FROM employees e LEFT JOIN departments d ON d.id=e.department_id WHERE e.id=?", (eid,), True) or abort(404)
    return render_template("idcard.html", e=e, today=now().strftime("%d %b %Y"))
