"""Admin Web Panel (Telegram WebApp, Flask). passenger_wsgi.py orqali ishga tushadi.

Bot (main.py) bilan bir xil bazadan (repo.py orqali) foydalanadi, lekin botni
import QILMAYDI - ikkalasi mustaqil jarayonlar. Xodimga xabar yoki adminga fayl
yuborish kerak bo'lsa Telegram Bot API'ga to'g'ridan-to'g'ri HTTP so'rov yuboriladi.

Kirish: muddatli token (auth.py) "X-Auth" sarlavhasida; zaxira sifatida
Telegram initData ("X-Telegram-Init-Data").
"""
import logging
import os
import tempfile
from datetime import datetime
from functools import wraps

import requests
from flask import Flask, Response, jsonify, make_response, redirect, request, send_file

import auth
import config
import database
import logic
import reports
import repo
from config import esc, money

logger = logging.getLogger("attendance_bot.webapp")
app = Flask(__name__)
database.init_db()

with open(os.path.join(config.BASE_DIR, "templates", "admin.html"), encoding="utf-8") as _f:
    ADMIN_PAGE_HTML = _f.read()


# ================= AUTENTIFIKATSIYA =================
# Uch xil kirish:
#   1) X-Auth - Telegram ichidagi Web Panel (muddatli token)
#   2) X-Telegram-Init-Data - Telegram'ning o'z imzosi (zaxira)
#   3) kk_session cookie - web sayt (kompyuter brauzeri), /login orqali.
#      Cookie bilan kelgan o'zgartiruvchi (POST) so'rovlar X-CSRF sarlavhasini talab qiladi.
def current_admin():
    """(admin_id, usul) yoki (None, None)."""
    uid = auth.verify_token(request.headers.get("X-Auth", ""))
    if uid:
        return uid, "token"
    user = auth.validate_init_data(request.headers.get("X-Telegram-Init-Data", ""))
    if user and int(user.get("id", 0)) in config.ADMIN_IDS:
        return int(user["id"]), "initdata"
    sess = auth.get_session(request.cookies.get(auth.SESSION_COOKIE, ""))
    if sess:
        uid, csrf = sess
        if request.method != "GET" and request.headers.get("X-CSRF", "") != csrf:
            return None, "csrf"
        return uid, "cookie"
    return None, None


def admin_api(fn):
    @wraps(fn)
    def wrapper(*args, **kwargs):
        uid, how = current_admin()
        if not uid:
            if how == "csrf":
                return jsonify({"error": "csrf"}), 403
            return jsonify({"error": "unauthorized"}), 401
        return fn(uid, *args, **kwargs)
    return wrapper


def body() -> dict:
    return request.get_json(force=True, silent=True) or {}


def bad(msg="invalid_input", code=400):
    return jsonify({"error": msg}), code


def _uid(src) -> int:
    return int(src["user_id"])


def _month(raw) -> str:
    datetime.strptime(str(raw) + "-01", "%Y-%m-%d")
    return str(raw)


def _date(raw) -> str:
    if not raw:
        return config.today_str()
    return datetime.strptime(str(raw), "%Y-%m-%d").strftime("%Y-%m-%d")


def _amount(raw) -> float:
    v = float(str(raw).replace(" ", "").replace(",", ""))
    if v != v or v <= 0 or v > 1e10:  # NaN / manfiy / juda katta
        raise ValueError
    return v


# ================= TELEGRAM (HTTP) =================
def tg_send(chat_id: int, text: str, parse_mode: str | None = "HTML") -> bool:
    try:
        r = requests.post(f"https://api.telegram.org/bot{config.BOT_TOKEN}/sendMessage",
                          json={"chat_id": chat_id, "text": text, **({"parse_mode": parse_mode} if parse_mode else {})},
                          timeout=10)
        return bool(r.json().get("ok"))
    except Exception as e:
        logger.error(f"sendMessage xatosi ({chat_id}): {e}")
        return False


def tg_send_file(chat_id: int, path: str, filename: str, caption: str) -> bool:
    try:
        with open(path, "rb") as f:
            r = requests.post(f"https://api.telegram.org/bot{config.BOT_TOKEN}/sendDocument",
                              data={"chat_id": chat_id, "caption": caption, "parse_mode": "HTML"},
                              files={"document": (filename, f)}, timeout=60)
        return bool(r.json().get("ok"))
    except Exception as e:
        logger.error(f"sendDocument xatosi ({chat_id}): {e}")
        return False


NUDGE_TEXT = "🔔 Ishga kelgan bo'lsangiz, belgilashni unutmang!"


# ================= SAHIFA =================
def _page(html: str, code: int = 200):
    resp = Response(html, status=code, mimetype="text/html")
    resp.headers["Cache-Control"] = "no-store"
    resp.headers["Referrer-Policy"] = "no-referrer"
    resp.headers["X-Frame-Options"] = "SAMEORIGIN"
    return resp


@app.get("/webapp")
@app.get("/webapp/")
@app.get("/webapp/site")
@app.get("/webapp/site/")
@app.get("/webapp/a/<path:_token>")
def webapp_index(_token=None):
    return _page(ADMIN_PAGE_HTML)


# ================= WEB SAYT: KIRISH / CHIQISH =================
_LOGIN_PAGE = """<!doctype html><html lang="uz"><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1"><meta name="referrer" content="no-referrer">
<title>Kirish - Davomat paneli</title><style>
body{margin:0;min-height:100vh;display:grid;place-items:center;background:#f2f2f7;color:#111;
font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif}
.box{background:#fff;border-radius:16px;padding:28px 26px;max-width:380px;width:calc(100% - 32px);
box-shadow:0 1px 3px rgba(0,0,0,.08);text-align:center}
h1{font-size:19px;margin:0 0 8px}p{opacity:.7;font-size:14px;line-height:1.5;margin:0 0 18px}
button{border:0;border-radius:10px;padding:12px 18px;font-size:15px;font-weight:600;background:#2481cc;color:#fff;
width:100%;cursor:pointer}
@media (prefers-color-scheme: dark){body{background:#17181a;color:#eee}.box{background:#222326}}
</style></head><body><div class="box">%BODY%</div></body></html>"""


def _login_msg(title: str, text: str, code: int = 200, form: str = ""):
    return _page(_LOGIN_PAGE.replace("%BODY%", f"<h1>{esc(title)}</h1><p>{text}</p>{form}"), code)


@app.get("/webapp/login/<token>")
def site_login_confirm(token):
    """Telegram havolani oldindan ko'rib chiqishi (preview) tokenni "ishlatib" qo'ymasligi
    uchun GET faqat tasdiqlash tugmasini ko'rsatadi; kirish POST bilan bo'ladi."""
    if not auth.peek_login_token(token):
        return _login_msg("Havola eskirgan", "Bu havola ishlatilgan yoki 10 daqiqadan oshgan.<br>"
                          "Botga <b>/login</b> yozib, yangisini oling.", 410)
    form = (f'<form method="post" action="{request.path}"><button type="submit">🔐 Panelga kirish</button></form>')
    return _login_msg("Davomat paneli", "Shu brauzerda 30 kun davomida kirgan holda qolasiz.", form=form)


@app.post("/webapp/login/<token>")
def site_login(token):
    uid = auth.consume_login_token(token)
    if not uid:
        return _login_msg("Havola eskirgan", "Botga <b>/login</b> yozib, yangisini oling.", 410)
    sid = auth.create_session(uid, request.headers.get("User-Agent", ""))
    repo.audit(uid, "site_login", None, {"ua": request.headers.get("User-Agent", "")[:120]})
    resp = make_response(redirect("/webapp/site/", code=303))
    secure = request.is_secure or request.headers.get("X-Forwarded-Proto", "") == "https"
    resp.set_cookie(auth.SESSION_COOKIE, sid, max_age=auth.SESSION_TTL_SECONDS, path="/webapp",
                    httponly=True, secure=secure, samesite="Lax")
    return resp


@app.post("/webapp/logout")
@admin_api
def site_logout(_admin):
    auth.delete_session(request.cookies.get(auth.SESSION_COOKIE, ""))
    resp = jsonify({"ok": True})
    resp.delete_cookie(auth.SESSION_COOKIE, path="/webapp")
    return resp


@app.get("/webapp/api/me")
@admin_api
def api_me(admin):
    u = repo.get_user(admin)
    sess = auth.get_session(request.cookies.get(auth.SESSION_COOKIE, ""))
    return jsonify({"admin_id": admin, "name": (u or {}).get("name") or "Admin",
                    "csrf": sess[1] if sess and sess[0] == admin else None,
                    "mode": "cookie" if sess and sess[0] == admin else "token"})


# ================= HOLAT VA XODIMLAR =================
@app.get("/webapp/api/status")
@admin_api
def api_status(_admin):
    st = repo.employee_status(config.today_str())
    return jsonify(dict(st, now=config.get_now().strftime("%Y-%m-%d %H:%M")))


@app.get("/webapp/api/users")
@admin_api
def api_users(_admin):
    return jsonify({"users": [u for u in repo.list_users(include_archived=True) if u["is_approved"] in (0, 1)]})


@app.post("/webapp/api/employee/add")
@admin_api
def api_employee_add(admin):
    b = body()
    try:
        uid, name = _uid(b), str(b["name"]).strip()
        if not name or uid <= 0:
            raise ValueError
    except (KeyError, ValueError, TypeError):
        return bad()
    # Ixtiyoriy: oylik, ish vaqti va ish rejimini qo'shish paytidayoq belgilash
    try:
        salary = float(str(b.get("salary") or "0").replace(" ", "")) if b.get("salary") not in (None, "") else None
        if salary is not None and not (0 <= salary <= 1e10):
            raise ValueError
        start = logic.normalize_hhmm(b["work_start"]) if b.get("work_start") else None
        end = logic.normalize_hhmm(b["work_end"]) if b.get("work_end") else None
        if (start or end) and not (start and end):
            raise ValueError
        if start and logic.validate_schedule(start, end):
            return bad(logic.validate_schedule(start, end))
        mask = str(b["weekdays"]) if b.get("weekdays") else None
        if mask and (len(mask) != 7 or set(mask) - {"0", "1"} or "1" not in mask):
            raise ValueError
    except (ValueError, TypeError):
        return bad("Oylik, ish vaqti yoki rejim noto'g'ri")
    existed = repo.get_user(uid) is not None
    repo.upsert_user(uid, name[:100], admin)
    if salary is not None:
        repo.set_salary(uid, salary, admin)
    if start:
        repo.set_work_time(uid, start, end, admin)
    if mask:
        repo.set_work_regime(uid, mask, admin)
    tg_send(uid, "🎉 Siz davomat tizimiga qo'shildingiz. Botga /start yozing.", parse_mode=None)
    return jsonify({"ok": True, "existed": existed})


@app.post("/webapp/api/employee/approve")
@admin_api
def api_employee_approve(admin):
    try:
        uid = _uid(body())
    except (KeyError, ValueError, TypeError):
        return bad()
    repo.approve_user(uid, admin)
    tg_send(uid, "🎉 <b>Arizangiz tasdiqlandi!</b> Botga /start yozing.")
    return jsonify({"ok": True})


@app.post("/webapp/api/employee/reject")
@admin_api
def api_employee_reject(admin):
    try:
        uid = _uid(body())
    except (KeyError, ValueError, TypeError):
        return bad()
    repo.reject_user(uid, admin)
    tg_send(uid, "❌ Afsuski, arizangiz admin tomonidan rad etildi.", parse_mode=None)
    return jsonify({"ok": True})


@app.post("/webapp/api/employee/delete_forever")
@admin_api
def api_employee_delete_forever(admin):
    """Butunlay o'chirish. Xato bosilmasligi uchun xodimning ismi aynan yozilishi shart."""
    b = body()
    try:
        uid = _uid(b)
        confirm = str(b.get("confirm_name") or "").strip()
    except (KeyError, ValueError, TypeError):
        return bad()
    u = repo.get_user(uid)
    if not u:
        return bad("Xodim topilmadi", 404)
    if confirm.casefold() != (u["name"] or "").strip().casefold():
        return bad("Tasdiqlash uchun xodimning ismini aynan yozing")
    try:
        res = repo.delete_user_permanently(uid, admin)
    except ValueError as e:
        return bad(str(e))
    return jsonify({"ok": True, "deleted": res})


@app.post("/webapp/api/employee/rename")
@admin_api
def api_employee_rename(admin):
    b = body()
    try:
        uid, name = _uid(b), str(b["name"]).strip()
        if not name:
            raise ValueError
    except (KeyError, ValueError, TypeError):
        return bad()
    repo.rename_user(uid, name[:100], admin)
    return jsonify({"ok": True})


@app.post("/webapp/api/employee/salary")
@admin_api
def api_employee_salary(admin):
    b = body()
    try:
        uid, salary = _uid(b), float(b["salary"])
        if salary < 0 or salary > 1e10:
            raise ValueError
    except (KeyError, ValueError, TypeError):
        return bad()
    repo.set_salary(uid, salary, admin)
    return jsonify({"ok": True})


@app.post("/webapp/api/employee/daily_hours")
@admin_api
def api_employee_daily_hours(admin):
    b = body()
    try:
        uid = _uid(b)
        raw = b.get("daily_hours")
        hours = None if raw in (None, "", 0, "0") else float(raw)
        if hours is not None and not (1 <= hours <= 16):
            raise ValueError
    except (KeyError, ValueError, TypeError):
        return bad("Kunlik soat 1..16 oralig'ida bo'lishi kerak (bo'sh = avtomatik)")
    repo.set_daily_hours(uid, hours, admin)
    return jsonify({"ok": True})


@app.post("/webapp/api/schedule")
@admin_api
def api_schedule(admin):
    b = body()
    try:
        uid = _uid(b)
        start, end = logic.normalize_hhmm(b["work_start"]), logic.normalize_hhmm(b["work_end"])
    except (KeyError, ValueError, TypeError):
        return bad("Vaqt HH:MM ko'rinishida bo'lishi kerak")
    err = logic.validate_schedule(start, end)
    if err:
        return bad(err)
    repo.set_work_time(uid, start, end, admin)
    return jsonify({"ok": True})


@app.post("/webapp/api/employee/flags")
@admin_api
def api_employee_flags(admin):
    b = body()
    try:
        uid = _uid(b)
    except (KeyError, ValueError, TypeError):
        return bad()
    repo.set_flags(uid, admin,
                   auto_checkout=b["auto_checkout_enabled"] if "auto_checkout_enabled" in b else None,
                   overtime=b["overtime_eligible"] if "overtime_eligible" in b else None)
    return jsonify({"ok": True})


@app.post("/webapp/api/employee/archive")
@app.post("/webapp/api/employee/delete")  # eski panel bilan moslik: endi o'chirmaydi, arxivlaydi
@admin_api
def api_employee_archive(admin):
    try:
        uid = _uid(body())
    except (KeyError, ValueError, TypeError):
        return bad()
    if uid in config.ADMIN_IDS:
        return bad("Adminni arxivlab bo'lmaydi")
    repo.archive_user(uid, admin)
    return jsonify({"ok": True})


@app.post("/webapp/api/employee/restore")
@admin_api
def api_employee_restore(admin):
    try:
        uid = _uid(body())
    except (KeyError, ValueError, TypeError):
        return bad()
    repo.restore_user(uid, admin)
    return jsonify({"ok": True})


@app.post("/webapp/api/nudge")
@admin_api
def api_nudge(_admin):
    target = body().get("user_id", "all")
    if target == "all":
        st = repo.employee_status(config.today_str())
        return jsonify({"sent": sum(tg_send(x["user_id"], NUDGE_TEXT) for x in st["kelmagan"])})
    try:
        tid = int(target)
    except (TypeError, ValueError):
        return bad()
    if tg_send(tid, NUDGE_TEXT):
        return jsonify({"sent": 1})
    return bad("Xabar yuborilmadi (bot bloklangan bo'lishi mumkin)")


# ================= KALENDAR =================
@app.get("/webapp/api/workdays")
@admin_api
def api_workdays_get(_admin):
    try:
        uid, month = int(request.args.get("user_id")), _month(request.args.get("month"))
    except (TypeError, ValueError):
        return bad()
    return jsonify(repo.workdays_view(uid, month))


@app.post("/webapp/api/employee/regime")
@admin_api
def api_employee_regime(admin):
    """Ish rejimi: weekdays = Du..Ya uchun 7 belgi, masalan '1111100' (5 kunlik)."""
    b = body()
    try:
        label = repo.set_work_regime(_uid(b), str(b["weekdays"]), admin)
    except (KeyError, TypeError):
        return bad()
    except ValueError as e:
        return bad(str(e))
    return jsonify({"ok": True, "regime": label})


# ================= ISHXONA KALENDARI (bayram / dam olish kunlari) =================
@app.get("/webapp/api/holidays")
@admin_api
def api_holidays(_admin):
    try:
        month = _month(request.args.get("month") or config.get_now().strftime("%Y-%m"))
    except ValueError:
        return bad()
    return jsonify(repo.company_calendar(month))


@app.post("/webapp/api/holidays/set")
@admin_api
def api_holiday_set(admin):
    b = body()
    try:
        repo.set_holiday(_date(b["date"]), bool(b.get("is_off", True)), str(b.get("name") or ""), admin)
    except (KeyError, ValueError, TypeError):
        return bad()
    return jsonify({"ok": True})


@app.post("/webapp/api/holidays/clear")
@admin_api
def api_holiday_clear(admin):
    try:
        ok = repo.clear_holiday(_date(body()["date"]), admin)
    except (KeyError, ValueError, TypeError):
        return bad()
    return jsonify({"ok": ok})


@app.post("/webapp/api/holidays/fixed")
@admin_api
def api_holiday_fixed(admin):
    try:
        year = int(body()["year"])
        if not 2000 <= year <= 2100:
            raise ValueError
    except (KeyError, ValueError, TypeError):
        return bad()
    return jsonify({"ok": True, "added": repo.add_fixed_holidays(year, admin)})


@app.post("/webapp/api/workdays/set")
@admin_api
def api_workdays_set(admin):
    b = body()
    try:
        uid, month = _uid(b), _month(b["month"])
        count = repo.set_work_days(uid, month, b.get("days") or [], admin)
    except (KeyError, ValueError, TypeError) as e:
        return bad(str(e) if isinstance(e, ValueError) and str(e) else "invalid_input")
    return jsonify({"ok": True, "count": count})


@app.post("/webapp/api/workdays/clear")
@admin_api
def api_workdays_clear(admin):
    b = body()
    try:
        repo.set_work_days(_uid(b), _month(b["month"]), [], admin)
    except (KeyError, ValueError, TypeError):
        return bad()
    return jsonify({"ok": True})


# ================= DAVOMAT =================
@app.get("/webapp/api/attendance")
@admin_api
def api_attendance_get(_admin):
    try:
        uid, date_str = int(request.args.get("user_id")), _date(request.args.get("date"))
    except (TypeError, ValueError):
        return bad()
    rec, absence = repo.admin_get_attendance(uid, date_str)
    return jsonify({"date": date_str, "record": rec, "absence": absence})


def _notify_change(uid, date_str, what, hhmm):
    when = "bugun" if date_str == config.today_str() else f"{date_str} kuni"
    tg_send(uid, f"ℹ️ Admin tomonidan siz {when} soat {hhmm} da {what} deb belgilandingiz.", parse_mode=None)


@app.post("/webapp/api/attendance/checkin")
@admin_api
def api_attendance_checkin(admin):
    b = body()
    try:
        uid, hhmm, date_str = _uid(b), logic.normalize_hhmm(b["check_in"]), _date(b.get("date"))
    except (KeyError, ValueError, TypeError):
        return bad("Vaqt HH:MM ko'rinishida bo'lishi kerak")
    ok, err = repo.admin_set_checkin(uid, date_str, hhmm, admin)
    if not ok:
        return bad(err)
    _notify_change(uid, date_str, "kelgan", hhmm)
    return jsonify({"ok": True})


@app.post("/webapp/api/attendance/checkout")
@admin_api
def api_attendance_checkout(admin):
    b = body()
    try:
        uid, hhmm, date_str = _uid(b), logic.normalize_hhmm(b["check_out"]), _date(b.get("date"))
    except (KeyError, ValueError, TypeError):
        return bad("Vaqt HH:MM ko'rinishida bo'lishi kerak")
    ok, err = repo.admin_set_checkout(uid, date_str, hhmm, admin)
    if not ok:
        return bad(err)
    _notify_change(uid, date_str, "ketgan", hhmm)
    return jsonify({"ok": True})


@app.post("/webapp/api/attendance/delete")
@admin_api
def api_attendance_delete(admin):
    b = body()
    try:
        uid, date_str = _uid(b), _date(b["date"])
    except (KeyError, ValueError, TypeError):
        return bad()
    if not repo.admin_delete_attendance(uid, date_str, admin):
        return bad("Shu kun uchun yozuv yo'q")
    return jsonify({"ok": True})


# ================= YO'QLIKLAR =================
@app.post("/webapp/api/absence/set")
@admin_api
def api_absence_set(admin):
    b = body()
    try:
        uid, d1 = _uid(b), _date(b["date_from"])
        d2 = _date(b.get("date_to") or d1)
        n = repo.set_absence(uid, d1, d2, str(b["type"]), str(b.get("note") or "")[:200], admin)
    except (KeyError, TypeError):
        return bad()
    except ValueError as e:
        return bad(str(e) or "invalid_input")
    label = config.ABSENCE_TYPES[b["type"]]
    period = d1 if d1 == d2 else f"{d1} — {d2}"
    tg_send(uid, f"📝 Sizga {period} uchun «{label}» belgilandi (to'lanmaydi).", parse_mode=None)
    return jsonify({"ok": True, "days": n})


@app.post("/webapp/api/absence/clear")
@admin_api
def api_absence_clear(admin):
    b = body()
    try:
        uid, d = _uid(b), _date(b["date"])
    except (KeyError, ValueError, TypeError):
        return bad()
    return jsonify({"ok": repo.clear_absence(uid, d, admin)})


# ================= PUL: AVANS, BONUS, JARIMA =================
@app.get("/webapp/api/money")
@admin_api
def api_money(_admin):
    try:
        uid, month = int(request.args.get("user_id")), _month(request.args.get("month"))
    except (TypeError, ValueError):
        return bad()
    return jsonify({"summary": repo.salary_summary(uid, month), "advances": repo.list_advances(uid, month),
                    "adjustments": repo.list_adjustments(uid, month), "absences": repo.list_absences(uid, month)})


@app.post("/webapp/api/employee/advance")
@app.post("/webapp/api/advance/add")
@admin_api
def api_advance_add(admin):
    b = body()
    try:
        uid, amount, date_str = _uid(b), _amount(b["amount"]), _date(b.get("date"))
    except (KeyError, ValueError, TypeError):
        return bad("Summa noto'g'ri")
    repo.add_advance(uid, amount, date_str, admin, str(b.get("note") or "")[:200])
    tg_send(uid, f"💸 Sizga <b>{money(amount)} so'm</b> avans berilgani qayd etildi.")
    return jsonify({"ok": True})


@app.post("/webapp/api/advance/update")
@admin_api
def api_advance_update(admin):
    b = body()
    try:
        adv_id, amount = int(b["id"]), _amount(b["amount"])
    except (KeyError, ValueError, TypeError):
        return bad("Summa noto'g'ri")
    uid = repo.update_advance(adv_id, amount, admin)
    if uid is None:
        return bad("Avans topilmadi", 404)
    tg_send(uid, f"✏️ Avansingiz {money(amount)} so'm qilib tuzatildi.", parse_mode=None)
    return jsonify({"ok": True})


@app.post("/webapp/api/advance/delete")
@admin_api
def api_advance_delete(admin):
    try:
        adv_id = int(body()["id"])
    except (KeyError, ValueError, TypeError):
        return bad()
    if repo.delete_advance(adv_id, admin) is None:
        return bad("Avans topilmadi", 404)
    return jsonify({"ok": True})


@app.post("/webapp/api/adjustment/add")
@admin_api
def api_adjustment_add(admin):
    """kind: 'bonus' yoki 'fine' (jarima). Faqat admin qo'lda kiritadi."""
    b = body()
    try:
        uid, amount = _uid(b), _amount(b["amount"])
        kind = b["kind"]
        if kind not in ("bonus", "fine"):
            raise ValueError
        note = str(b.get("note") or "").strip()[:200]
        date_str = _date(b.get("date"))
    except (KeyError, ValueError, TypeError):
        return bad("Ma'lumot noto'g'ri")
    signed = amount if kind == "bonus" else -amount
    repo.add_adjustment(uid, signed, note, date_str, admin)
    word = "🎁 Bonus" if kind == "bonus" else "🔻 Jarima"
    tg_send(uid, f"{word}: <b>{money(amount)} so'm</b>" + (f"\nIzoh: {esc(note)}" if note else ""))
    return jsonify({"ok": True})


@app.post("/webapp/api/adjustment/delete")
@admin_api
def api_adjustment_delete(admin):
    try:
        adj_id = int(body()["id"])
    except (KeyError, ValueError, TypeError):
        return bad()
    if repo.delete_adjustment(adj_id, admin) is None:
        return bad("Topilmadi", 404)
    return jsonify({"ok": True})


# ================= DASHBOARD, TARIX, AUDIT =================
@app.get("/webapp/api/dashboard")
@admin_api
def api_dashboard(_admin):
    try:
        month = _month(request.args.get("month") or config.get_now().strftime("%Y-%m"))
    except ValueError:
        return bad()
    rows = repo.month_summary_all(month)
    totals = {k: sum(r[k] for r in rows) for k in ("earned", "advances", "bonuses", "fines", "net", "work_hours",
                                                     "lateness_total", "late_days")}
    return jsonify({"month": month, "rows": rows, "totals": totals})


@app.get("/webapp/api/history")
@admin_api
def api_history(_admin):
    try:
        uid, month = int(request.args.get("user_id")), _month(request.args.get("month"))
    except (TypeError, ValueError):
        return bad()
    return jsonify({"days": repo.daily_history(uid, month)})


@app.get("/webapp/api/audit")
@admin_api
def api_audit(_admin):
    raw = request.args.get("user_id")
    try:
        uid = int(raw) if raw else None
    except ValueError:
        return bad()
    names = {u["user_id"]: u["name"] for u in repo.list_users(include_archived=True, include_admins=True)}
    items = repo.list_audit(uid, 50)
    for it in items:
        it["actor_name"] = names.get(it["actor_id"], "Tizim" if it["actor_id"] is None else str(it["actor_id"]))
    return jsonify({"items": items})


# ================= FAYLLARNI TELEGRAMGA YUBORISH =================
@app.post("/webapp/api/report/send")
@admin_api
def api_report_send(admin):
    """Faylni admin'ning Telegram chatiga yuboradi (WebApp ichida yuklab olish
    ko'p qurilmalarda ishlamagani uchun). kind: monthly | daily | payslip"""
    b = body()
    kind = b.get("kind")
    fd, path = tempfile.mkstemp(suffix=".pdf" if kind == "payslip" else ".xlsx")
    os.close(fd)
    try:
        if kind == "monthly":
            month = _month(b["month"])
            reports.generate_monthly_excel(month, path)
            ok = tg_send_file(admin, path, f"Oylik_Hisobot_{month}.xlsx",
                              f"📊 <b>{config.month_label(month)}</b> — oylik hisobot")
        elif kind == "daily":
            d = _date(b.get("date"))
            reports.generate_daily_excel(d, path)
            ok = tg_send_file(admin, path, f"Kunlik_Hisobot_{d}.xlsx", f"📊 <b>{d}</b> — kunlik hisobot")
        elif kind == "payslip":
            uid, month = _uid(b), _month(b["month"])
            reports.generate_payslip_pdf(uid, month, path)
            target = admin if b.get("to") != "employee" else uid
            ok = tg_send_file(target, path, f"Hisob_varaqasi_{month}.pdf",
                              f"📄 <b>{config.month_label(month)}</b> — ish haqi hisob varaqasi")
        else:
            return bad()
    except (KeyError, ValueError, TypeError) as e:
        return bad(str(e) or "invalid_input")
    finally:
        try:
            os.remove(path)
        except OSError:
            pass
    return jsonify({"ok": ok}) if ok else bad("Telegramga yuborilmadi")


# ================= WEB SAYT: JADVAL, GRAFIKLAR, YUKLAB OLISH =================
@app.get("/webapp/api/grid")
@admin_api
def api_grid(_admin):
    try:
        month = _month(request.args.get("month") or config.get_now().strftime("%Y-%m"))
    except ValueError:
        return bad()
    return jsonify(repo.month_grid(month))


@app.get("/webapp/api/charts")
@admin_api
def api_charts(_admin):
    try:
        month = _month(request.args.get("month") or config.get_now().strftime("%Y-%m"))
    except ValueError:
        return bad()
    return jsonify(repo.month_charts(month))


@app.get("/webapp/api/report/download")
@admin_api
def api_report_download(_admin):
    """Brauzerda (web saytda) faylni to'g'ridan-to'g'ri yuklab olish."""
    kind = request.args.get("kind")
    try:
        if kind == "monthly":
            month = _month(request.args.get("month"))
            fd, path = tempfile.mkstemp(suffix=".xlsx")
            os.close(fd)
            reports.generate_monthly_excel(month, path)
            name = f"Oylik_Hisobot_{month}.xlsx"
        elif kind == "daily":
            d = _date(request.args.get("date"))
            fd, path = tempfile.mkstemp(suffix=".xlsx")
            os.close(fd)
            reports.generate_daily_excel(d, path)
            name = f"Kunlik_Hisobot_{d}.xlsx"
        elif kind == "payslip":
            uid, month = int(request.args.get("user_id")), _month(request.args.get("month"))
            fd, path = tempfile.mkstemp(suffix=".pdf")
            os.close(fd)
            reports.generate_payslip_pdf(uid, month, path)
            name = f"Hisob_varaqasi_{month}_{uid}.pdf"
        else:
            return bad()
    except (TypeError, ValueError) as e:
        return bad(str(e) or "invalid_input")
    with open(path, "rb") as f:
        data = f.read()
    os.remove(path)
    import io
    return send_file(io.BytesIO(data), as_attachment=True, download_name=name)
