File size: 25,840 Bytes
eb862a5
d88622e
eb862a5
d88622e
eb862a5
 
 
 
 
ccf96d3
eb862a5
 
 
d88622e
eb862a5
 
 
 
ccf96d3
 
 
 
 
 
 
eb862a5
ccf96d3
eb862a5
 
 
 
d88622e
 
 
eb862a5
 
 
 
 
 
ccf96d3
d88622e
eb862a5
 
 
 
 
 
 
 
 
 
 
 
d88622e
eb862a5
 
 
 
ccf96d3
d88622e
eb862a5
 
 
 
ccf96d3
 
 
 
 
 
 
 
 
eb862a5
 
 
 
ccf96d3
 
 
 
 
 
 
d88622e
ccf96d3
 
eb862a5
d88622e
 
eb862a5
d88622e
 
 
eb862a5
 
 
 
 
d88622e
 
 
 
 
 
eb862a5
 
 
 
 
 
 
ccf96d3
 
 
d88622e
 
 
 
 
eb862a5
 
 
 
 
 
 
 
 
ccf96d3
d88622e
eb862a5
ccf96d3
eb862a5
 
 
 
 
ccf96d3
 
 
 
d88622e
ccf96d3
 
 
eb862a5
 
 
 
d88622e
eb862a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d88622e
 
 
 
 
 
ccf96d3
 
 
 
 
d88622e
eb862a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d88622e
 
eb862a5
 
d88622e
eb862a5
ccf96d3
d88622e
eb862a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d88622e
 
 
 
 
 
 
 
eb862a5
 
 
 
 
 
 
 
ccf96d3
d88622e
eb862a5
 
 
 
 
 
 
 
 
 
 
d88622e
eb862a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d88622e
ccf96d3
eb862a5
 
ccf96d3
 
eb862a5
ccf96d3
eb862a5
d88622e
eb862a5
 
ccf96d3
 
eb862a5
ccf96d3
eb862a5
 
ccf96d3
 
 
eb862a5
ccf96d3
 
eb862a5
ccf96d3
 
eb862a5
d88622e
 
eb862a5
 
ccf96d3
 
 
 
 
d88622e
ccf96d3
 
 
 
 
 
 
 
d88622e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ccf96d3
eb862a5
ccf96d3
 
eb862a5
 
ccf96d3
 
eb862a5
ccf96d3
d88622e
 
 
eb862a5
d88622e
ccf96d3
 
d88622e
eb862a5
d88622e
eb862a5
ccf96d3
d88622e
eb862a5
ccf96d3
 
eb862a5
 
ccf96d3
 
 
eb862a5
ccf96d3
 
eb862a5
 
ccf96d3
 
 
 
 
d88622e
 
 
 
 
 
 
eb862a5
 
 
 
 
 
d88622e
eb862a5
 
 
 
d88622e
eb862a5
 
 
 
 
 
 
 
 
 
d88622e
eb862a5
 
 
d88622e
 
 
 
 
eb862a5
 
 
 
 
 
d88622e
 
 
 
 
 
 
 
ccf96d3
 
d88622e
ccf96d3
eb862a5
 
 
 
 
d88622e
ccf96d3
eb862a5
 
d88622e
eb862a5
 
ccf96d3
 
 
d88622e
ccf96d3
 
d88622e
ccf96d3
eb862a5
 
 
 
 
 
 
 
 
d88622e
 
 
 
 
 
 
eb862a5
 
 
 
 
d88622e
ccf96d3
eb862a5
 
 
 
 
 
 
 
 
d88622e
eb862a5
 
 
 
 
 
 
 
ccf96d3
 
d88622e
 
eb862a5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d88622e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eb862a5
 
d88622e
 
 
eb862a5
 
d88622e
 
 
 
 
 
 
 
eb862a5
 
 
d88622e
eb862a5
 
 
 
 
 
 
 
 
 
d88622e
eb862a5
 
 
d88622e
 
eb862a5
 
d88622e
eb862a5
 
ccf96d3
d88622e
 
ccf96d3
 
 
 
 
 
 
d88622e
ccf96d3
eb862a5
 
 
 
 
 
 
d88622e
ccf96d3
eb862a5
 
ccf96d3
 
 
 
 
 
 
eb862a5
 
 
d88622e
eb862a5
ccf96d3
 
d88622e
eb862a5
ccf96d3
d88622e
eb862a5
d88622e
ccf96d3
 
eb862a5
 
 
 
 
 
 
ccf96d3
 
 
 
 
d88622e
 
eb862a5
 
 
 
d88622e
eb862a5
 
d88622e
eb862a5
 
 
ccf96d3
eb862a5
d88622e
eb862a5
 
d88622e
eb862a5
 
 
d88622e
eb862a5
d88622e
eb862a5
 
d88622e
eb862a5
 
 
 
 
 
 
 
 
 
 
 
 
d88622e
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
"""
ArianKing β€” Multi-Game License Key Server
Runs on HuggingFace Spaces (Docker SDK)
Supports: CS2, Apex, and future games
"""

from fastapi import FastAPI, HTTPException
from fastapi.responses import HTMLResponse
from pydantic import BaseModel
import json, os, secrets, string, time, shutil
from datetime import datetime, timedelta
from pathlib import Path
from threading import Lock
from typing import Optional

app = FastAPI(title="ArianKing Key Server")

# ── Storage ──────────────────────────────────────────────────────────────────
if Path("/data").exists():
    DATA_DIR = Path("/data")
elif Path("/home/user/app").exists():
    DATA_DIR = Path("/home/user/app")
else:
    DATA_DIR = Path(".")

KEYS_FILE = DATA_DIR / "keys.json"
BACKUP_FILE = DATA_DIR / "keys_backup.json"
file_lock = Lock()

ADMIN_PASSWORD = os.environ.get("ADMIN_PASSWORD", "ArianKing2026")

# Supported games
VALID_GAMES = ["cs2", "apex", "all"]


# ── Models ───────────────────────────────────────────────────────────────────
class CreateKeyRequest(BaseModel):
    admin_password: str
    days: int = 30
    label: str = ""
    username: str = ""
    game: str = "cs2"       # "cs2", "apex", or "all"

class ToggleKeyRequest(BaseModel):
    admin_password: str
    key: str
    active: bool

class DeleteKeyRequest(BaseModel):
    admin_password: str
    key: str

class ListKeysRequest(BaseModel):
    admin_password: str
    game: Optional[str] = None   # filter by game, None = show all

class ValidateRequest(BaseModel):
    key: str
    hwid: str
    username: str = ""
    game: str = "cs2"       # which game is requesting validation


# ── Helpers ──────────────────────────────────────────────────────────────────
def load_keys() -> dict:
    for filepath in [KEYS_FILE, BACKUP_FILE]:
        if filepath.exists():
            try:
                with open(filepath, "r") as f:
                    data = json.load(f)
                    if isinstance(data, dict):
                        return data
            except (json.JSONDecodeError, IOError):
                continue
    return {}

def save_keys(keys: dict):
    with file_lock:
        tmp_file = DATA_DIR / "keys_tmp.json"
        try:
            with open(tmp_file, "w") as f:
                json.dump(keys, f, indent=2)
            shutil.move(str(tmp_file), str(KEYS_FILE))
            with open(BACKUP_FILE, "w") as f:
                json.dump(keys, f, indent=2)
        except Exception:
            with open(KEYS_FILE, "w") as f:
                json.dump(keys, f, indent=2)

def generate_key(game: str) -> str:
    """Generate key like ARIAN-CS2-XXXX-XXXX or ARIAN-APEX-XXXX-XXXX"""
    chars = string.ascii_uppercase + string.digits
    parts = ["".join(secrets.choice(chars) for _ in range(4)) for _ in range(2)]
    prefix = game.upper() if game != "all" else "ALL"
    return f"ARIAN-{prefix}-{parts[0]}-{parts[1]}"

def check_admin(password: str):
    if password != ADMIN_PASSWORD:
        raise HTTPException(status_code=403, detail="Invalid admin password")

def game_matches(key_game: str, request_game: str) -> bool:
    """Check if a key's game matches the requesting game"""
    if key_game == "all":
        return True
    return key_game.lower() == request_game.lower()


# ── API Endpoints ────────────────────────────────────────────────────────────

@app.post("/api/create-key")
def create_key(req: CreateKeyRequest):
    check_admin(req.admin_password)

    if not req.username.strip():
        raise HTTPException(status_code=400, detail="Username is required")

    game = req.game.lower()
    if game not in VALID_GAMES:
        raise HTTPException(status_code=400, detail=f"Invalid game. Valid: {', '.join(VALID_GAMES)}")

    key = generate_key(game)
    now = datetime.utcnow()
    expires = now + timedelta(days=req.days)

    keys = load_keys()
    keys[key] = {
        "created": now.isoformat(),
        "expires": expires.isoformat(),
        "days": req.days,
        "label": req.label,
        "username": req.username.strip(),
        "game": game,
        "active": True,
        "hwid": None,
        "last_used": None,
        "uses": 0
    }
    save_keys(keys)

    return {
        "success": True,
        "key": key,
        "username": req.username.strip(),
        "game": game,
        "expires": expires.isoformat(),
        "days": req.days
    }


@app.post("/api/validate")
def validate_key(req: ValidateRequest):
    """Called by the cheat to check if a key is valid + bind HWID"""
    keys = load_keys()

    if req.key not in keys:
        return {"valid": False, "message": "Invalid key"}

    entry = keys[req.key]

    if not entry["active"]:
        return {"valid": False, "message": "Key deactivated"}

    # Check expiration
    expires = datetime.fromisoformat(entry["expires"])
    if datetime.utcnow() > expires:
        return {"valid": False, "message": "Key expired"}

    # Check game β€” key must match requesting game (or be "all")
    key_game = entry.get("game", "cs2")
    if not game_matches(key_game, req.game):
        game_label = key_game.upper() if key_game != "all" else "All Games"
        return {"valid": False, "message": f"Key is for {game_label}, not {req.game.upper()}"}

    # Check username
    expected_user = entry.get("username", "")
    if expected_user and req.username.strip().lower() != expected_user.strip().lower():
        return {"valid": False, "message": "Invalid username for this key"}

    # HWID binding
    if entry["hwid"] is None:
        entry["hwid"] = req.hwid
    elif entry["hwid"] != req.hwid:
        return {"valid": False, "message": "Key bound to different device"}

    # Update usage
    entry["last_used"] = datetime.utcnow().isoformat()
    entry["uses"] += 1
    keys[req.key] = entry
    save_keys(keys)

    remaining = expires - datetime.utcnow()
    days_left = max(0, remaining.days)
    hours_left = max(0, remaining.seconds // 3600)

    game_display = key_game.upper() if key_game != "all" else "All Games"

    return {
        "valid": True,
        "message": f"Welcome {expected_user}! {days_left}d {hours_left}h remaining [{game_display}]",
        "days_left": days_left,
        "username": expected_user,
        "game": key_game,
        "expires": entry["expires"]
    }


@app.post("/api/toggle-key")
def toggle_key(req: ToggleKeyRequest):
    check_admin(req.admin_password)
    keys = load_keys()
    if req.key not in keys:
        raise HTTPException(status_code=404, detail="Key not found")
    keys[req.key]["active"] = req.active
    save_keys(keys)
    return {"success": True, "key": req.key, "active": req.active}


@app.post("/api/delete-key")
def delete_key(req: DeleteKeyRequest):
    check_admin(req.admin_password)
    keys = load_keys()
    if req.key not in keys:
        raise HTTPException(status_code=404, detail="Key not found")
    del keys[req.key]
    save_keys(keys)
    return {"success": True}


@app.post("/api/reset-hwid")
def reset_hwid(req: DeleteKeyRequest):
    check_admin(req.admin_password)
    keys = load_keys()
    if req.key not in keys:
        raise HTTPException(status_code=404, detail="Key not found")
    keys[req.key]["hwid"] = None
    save_keys(keys)
    return {"success": True, "key": req.key}


@app.post("/api/list-keys")
def list_keys(req: ListKeysRequest):
    check_admin(req.admin_password)
    keys = load_keys()

    result = []
    now = datetime.utcnow()
    for key, data in keys.items():
        # Migrate old keys without game field
        key_game = data.get("game", "cs2")

        # Filter by game if requested
        if req.game and req.game.lower() != "all":
            if not game_matches(key_game, req.game):
                continue

        expires = datetime.fromisoformat(data["expires"])
        remaining = expires - now
        days_left = max(0, remaining.days) if remaining.total_seconds() > 0 else 0
        expired = now > expires

        result.append({
            "key": key,
            "label": data.get("label", ""),
            "username": data.get("username", ""),
            "game": key_game,
            "days": data["days"],
            "days_left": days_left,
            "expired": expired,
            "active": data["active"],
            "hwid": data["hwid"],
            "created": data["created"],
            "expires": data["expires"],
            "last_used": data.get("last_used"),
            "uses": data.get("uses", 0)
        })

    result.sort(key=lambda x: (not x["active"], x["expired"], x["created"]))
    return {"keys": result, "total": len(result)}


# ── Admin Panel (HTML) ───────────────────────────────────────────────────────

ADMIN_HTML = """<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ArianKing - Key Manager</title>
<style>
  * { margin: 0; padding: 0; box-sizing: border-box; }
  body {
    background: #0a0a0f;
    color: #e0e0e8;
    font-family: 'Segoe UI', system-ui, sans-serif;
    min-height: 100vh;
  }

  .header {
    background: linear-gradient(135deg, #7832ff 0%, #2878ff 100%);
    padding: 20px 30px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    box-shadow: 0 4px 20px rgba(120, 50, 255, 0.3);
  }
  .header h1 { font-size: 24px; font-weight: 700; color: white; }
  .header span { color: rgba(255,255,255,0.7); font-size: 14px; }

  .login-container {
    max-width: 400px; margin: 80px auto; padding: 30px;
    background: #12121a; border-radius: 12px; border: 1px solid #1e1e30;
  }
  .login-container h2 { color: #8b5cf6; margin-bottom: 20px; text-align: center; }

  .container { max-width: 1300px; margin: 20px auto; padding: 0 20px; }

  .card {
    background: #12121a; border-radius: 10px; padding: 20px;
    margin-bottom: 16px; border: 1px solid #1e1e30;
  }
  .card h3 { color: #8b5cf6; margin-bottom: 12px; font-size: 16px; }

  input, select {
    background: #1a1a28; border: 1px solid #2a2a40; color: #e0e0e8;
    padding: 10px 14px; border-radius: 6px; font-size: 14px;
    width: 100%; outline: none; transition: border-color 0.2s;
  }
  input:focus, select:focus { border-color: #7832ff; }
  .input-group { margin-bottom: 12px; }
  .input-group label {
    display: block; margin-bottom: 4px; color: #888;
    font-size: 12px; text-transform: uppercase; letter-spacing: 1px;
  }
  .input-row { display: flex; gap: 12px; flex-wrap: wrap; }
  .input-row > * { flex: 1; min-width: 120px; }

  .btn {
    padding: 10px 20px; border: none; border-radius: 6px;
    font-size: 14px; font-weight: 600; cursor: pointer;
    transition: all 0.2s; color: white;
  }
  .btn-primary { background: linear-gradient(135deg, #7832ff, #5a20d0); }
  .btn-primary:hover { background: linear-gradient(135deg, #8b45ff, #6b30e0); box-shadow: 0 4px 15px rgba(120,50,255,0.4); }
  .btn-danger { background: #dc2626; }
  .btn-danger:hover { background: #ef4444; }
  .btn-success { background: #16a34a; }
  .btn-success:hover { background: #22c55e; }
  .btn-warning { background: #d97706; }
  .btn-warning:hover { background: #f59e0b; }
  .btn-sm { padding: 6px 12px; font-size: 12px; }

  .game-filter {
    display: flex; gap: 8px; margin-bottom: 16px;
  }
  .game-btn {
    padding: 8px 18px; border: 2px solid #2a2a40; border-radius: 8px;
    background: transparent; color: #888; cursor: pointer;
    font-size: 13px; font-weight: 600; transition: all 0.2s;
  }
  .game-btn:hover { border-color: #7832ff; color: #c4b5fd; }
  .game-btn.active { border-color: #7832ff; background: rgba(120,50,255,0.15); color: #c4b5fd; }

  .game-badge {
    display: inline-block; padding: 3px 8px; border-radius: 4px;
    font-size: 10px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.5px;
  }
  .game-cs2 { background: rgba(255,165,0,0.2); color: #fbbf24; }
  .game-apex { background: rgba(239,68,68,0.2); color: #f87171; }
  .game-all { background: rgba(120,50,255,0.2); color: #c4b5fd; }

  .keys-table { width: 100%; border-collapse: collapse; }
  .keys-table th {
    text-align: left; padding: 10px; color: #888;
    font-size: 11px; text-transform: uppercase; letter-spacing: 1px;
    border-bottom: 1px solid #1e1e30;
  }
  .keys-table td { padding: 10px; border-bottom: 1px solid #1a1a28; font-size: 13px; }
  .keys-table tr:hover td { background: #1a1a28; }

  .badge { display: inline-block; padding: 3px 8px; border-radius: 4px; font-size: 11px; font-weight: 600; }
  .badge-active { background: rgba(22,163,74,0.2); color: #4ade80; }
  .badge-inactive { background: rgba(220,38,38,0.2); color: #f87171; }
  .badge-expired { background: rgba(217,119,6,0.2); color: #fbbf24; }

  .key-text { font-family: 'Consolas', monospace; color: #c4b5fd; font-size: 13px; cursor: pointer; }
  .key-text:hover { color: #8b5cf6; }
  .username-text { color: #60a5fa; font-weight: 600; font-size: 13px; }
  .hwid-text { font-family: monospace; font-size: 11px; color: #666; max-width: 120px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }

  .stats { display: flex; gap: 16px; margin-bottom: 16px; flex-wrap: wrap; }
  .stat-box {
    background: #12121a; border: 1px solid #1e1e30;
    border-radius: 8px; padding: 16px 20px; flex: 1; text-align: center; min-width: 100px;
  }
  .stat-box .number { font-size: 28px; font-weight: 700; color: #8b5cf6; }
  .stat-box .label { font-size: 12px; color: #666; margin-top: 4px; }

  .toast {
    position: fixed; top: 20px; right: 20px; background: #16a34a;
    color: white; padding: 12px 20px; border-radius: 8px; font-size: 14px;
    display: none; z-index: 1000; box-shadow: 0 4px 15px rgba(0,0,0,0.3);
  }
  .toast.error { background: #dc2626; }
  .actions { display: flex; gap: 4px; flex-wrap: wrap; }
  .hidden { display: none; }
  .overflow-x { overflow-x: auto; }

  .new-key-box {
    margin-top: 12px; padding: 16px; background: #1a1a28;
    border-radius: 8px; border: 1px solid #2a2a40;
  }
  .new-key-box .key-display { font-family: 'Consolas', monospace; font-size: 20px; color: #c4b5fd; letter-spacing: 1px; }
  .new-key-box .user-display { font-size: 14px; color: #60a5fa; margin-top: 4px; }
  .copy-all-btn { margin-top: 8px; display: flex; gap: 8px; }

  ::-webkit-scrollbar { width: 8px; }
  ::-webkit-scrollbar-track { background: #0a0a0f; }
  ::-webkit-scrollbar-thumb { background: #2a2a40; border-radius: 4px; }
</style>
</head>
<body>

<div class="header">
  <h1>ArianKing</h1>
  <span>Multi-Game Key Management</span>
</div>

<div id="toast" class="toast"></div>

<!-- Login -->
<div id="loginScreen" class="login-container">
  <h2>Admin Login</h2>
  <div class="input-group">
    <label>Password</label>
    <input type="password" id="passwordInput" placeholder="Enter admin password..."
           onkeydown="if(event.key==='Enter')login()">
  </div>
  <button class="btn btn-primary" style="width:100%;margin-top:8px" onclick="login()">Login</button>
</div>

<!-- Dashboard -->
<div id="dashboard" class="container hidden">

  <div class="stats">
    <div class="stat-box"><div class="number" id="statTotal">0</div><div class="label">Total Keys</div></div>
    <div class="stat-box"><div class="number" id="statActive">0</div><div class="label">Active</div></div>
    <div class="stat-box"><div class="number" id="statCS2">0</div><div class="label">CS2</div></div>
    <div class="stat-box"><div class="number" id="statApex">0</div><div class="label">Apex</div></div>
    <div class="stat-box"><div class="number" id="statExpired">0</div><div class="label">Expired</div></div>
  </div>

  <!-- Create Key -->
  <div class="card">
    <h3>Create New Key</h3>
    <div class="input-row">
      <div class="input-group">
        <label>Game *</label>
        <select id="keyGame">
          <option value="cs2">CS2</option>
          <option value="apex">Apex Legends</option>
          <option value="all">All Games</option>
        </select>
      </div>
      <div class="input-group">
        <label>Username *</label>
        <input type="text" id="keyUsername" placeholder="Username...">
      </div>
      <div class="input-group">
        <label>Duration (Days)</label>
        <input type="number" id="keyDays" value="30" min="1" max="365">
      </div>
      <div class="input-group">
        <label>Label</label>
        <input type="text" id="keyLabel" placeholder="Notes...">
      </div>
      <div style="display:flex;align-items:flex-end">
        <button class="btn btn-primary" onclick="createKey()">Create</button>
      </div>
    </div>
    <div id="newKeyResult" class="new-key-box hidden">
      <div style="color:#888;font-size:12px;text-transform:uppercase;letter-spacing:1px">New Key Created</div>
      <div class="key-display" id="newKeyText"></div>
      <div class="user-display">Username: <span id="newKeyUser"></span> | Game: <span id="newKeyGame"></span></div>
      <div class="copy-all-btn">
        <button class="btn btn-sm btn-primary" onclick="copyKey()">Copy Key</button>
        <button class="btn btn-sm btn-primary" onclick="copyAll()">Copy All</button>
      </div>
    </div>
  </div>

  <!-- Keys List -->
  <div class="card">
    <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:12px">
      <h3 style="margin:0">License Keys</h3>
      <button class="btn btn-sm btn-primary" onclick="loadKeys()">Refresh</button>
    </div>

    <div class="game-filter">
      <button class="game-btn active" onclick="filterGame(this,'all')">All</button>
      <button class="game-btn" onclick="filterGame(this,'cs2')">CS2</button>
      <button class="game-btn" onclick="filterGame(this,'apex')">Apex</button>
    </div>

    <div class="overflow-x">
      <table class="keys-table">
        <thead>
          <tr>
            <th>Key</th>
            <th>Game</th>
            <th>Username</th>
            <th>Label</th>
            <th>Status</th>
            <th>Days Left</th>
            <th>HWID</th>
            <th>Uses</th>
            <th>Actions</th>
          </tr>
        </thead>
        <tbody id="keysBody">
          <tr><td colspan="9" style="text-align:center;color:#666">Loading...</td></tr>
        </tbody>
      </table>
    </div>
  </div>
</div>

<script>
let adminPassword = '';
let lastCreatedKey = '';
let lastCreatedUser = '';
let lastCreatedGame = '';
let currentFilter = 'all';

function showToast(msg, isError) {
  const t = document.getElementById('toast');
  t.textContent = msg;
  t.className = 'toast' + (isError ? ' error' : '');
  t.style.display = 'block';
  setTimeout(() => t.style.display = 'none', 3000);
}

async function api(endpoint, body) {
  const res = await fetch('/api/' + endpoint, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(body)
  });
  if (!res.ok) {
    const err = await res.json();
    throw new Error(err.detail || 'Request failed');
  }
  return res.json();
}

async function login() {
  adminPassword = document.getElementById('passwordInput').value;
  try {
    await api('list-keys', { admin_password: adminPassword });
    document.getElementById('loginScreen').classList.add('hidden');
    document.getElementById('dashboard').classList.remove('hidden');
    loadKeys();
  } catch(e) {
    showToast('Invalid password', true);
    adminPassword = '';
  }
}

function filterGame(btn, game) {
  currentFilter = game;
  document.querySelectorAll('.game-btn').forEach(b => b.classList.remove('active'));
  btn.classList.add('active');
  loadKeys();
}

function getGameBadge(game) {
  const g = (game || 'cs2').toLowerCase();
  if (g === 'cs2') return '<span class="game-badge game-cs2">CS2</span>';
  if (g === 'apex') return '<span class="game-badge game-apex">APEX</span>';
  if (g === 'all') return '<span class="game-badge game-all">ALL</span>';
  return '<span class="game-badge">' + g.toUpperCase() + '</span>';
}

async function loadKeys() {
  try {
    const body = { admin_password: adminPassword };
    if (currentFilter !== 'all') body.game = currentFilter;
    const data = await api('list-keys', body);
    const keys = data.keys;

    // Stats (always show totals regardless of filter)
    const allData = await api('list-keys', { admin_password: adminPassword });
    const allKeys = allData.keys;
    document.getElementById('statTotal').textContent = allKeys.length;
    document.getElementById('statActive').textContent = allKeys.filter(k => k.active && !k.expired).length;
    document.getElementById('statCS2').textContent = allKeys.filter(k => (k.game||'cs2') === 'cs2').length;
    document.getElementById('statApex').textContent = allKeys.filter(k => k.game === 'apex').length;
    document.getElementById('statExpired').textContent = allKeys.filter(k => k.expired).length;

    const tbody = document.getElementById('keysBody');
    if (keys.length === 0) {
      tbody.innerHTML = '<tr><td colspan="9" style="text-align:center;color:#666">No keys found.</td></tr>';
      return;
    }

    tbody.innerHTML = keys.map(k => {
      let statusBadge;
      if (!k.active) statusBadge = '<span class="badge badge-inactive">Disabled</span>';
      else if (k.expired) statusBadge = '<span class="badge badge-expired">Expired</span>';
      else statusBadge = '<span class="badge badge-active">Active</span>';

      const hwid = k.hwid
        ? '<span class="hwid-text" title="' + k.hwid + '">' + k.hwid.substring(0,16) + '</span>'
        : '<span style="color:#444">Unbound</span>';

      const toggleBtn = k.active
        ? `<button class="btn btn-sm btn-warning" onclick="toggleKey('${k.key}',false)">Disable</button>`
        : `<button class="btn btn-sm btn-success" onclick="toggleKey('${k.key}',true)">Enable</button>`;

      const resetBtn = k.hwid
        ? `<button class="btn btn-sm btn-primary" onclick="resetHwid('${k.key}')">Reset</button>`
        : '';

      return '<tr>' +
        `<td><span class="key-text" onclick="navigator.clipboard.writeText('${k.key}');showToast('Copied!')" title="Click to copy">${k.key}</span></td>` +
        '<td>' + getGameBadge(k.game) + '</td>' +
        '<td><span class="username-text">' + (k.username || '-') + '</span></td>' +
        '<td>' + (k.label || '-') + '</td>' +
        '<td>' + statusBadge + '</td>' +
        '<td>' + (k.expired ? '0' : k.days_left + 'd') + '</td>' +
        '<td>' + hwid + '</td>' +
        '<td>' + k.uses + '</td>' +
        '<td class="actions">' + toggleBtn + resetBtn +
          `<button class="btn btn-sm btn-danger" onclick="deleteKey('${k.key}')">Del</button>` +
        '</td></tr>';
    }).join('');
  } catch(e) {
    showToast('Failed to load keys: ' + e.message, true);
  }
}

async function createKey() {
  const game = document.getElementById('keyGame').value;
  const username = document.getElementById('keyUsername').value.trim();
  const days = parseInt(document.getElementById('keyDays').value) || 30;
  const label = document.getElementById('keyLabel').value;

  if (!username) {
    showToast('Username is required!', true);
    document.getElementById('keyUsername').focus();
    return;
  }

  try {
    const data = await api('create-key', {
      admin_password: adminPassword,
      days, label, username, game
    });
    lastCreatedKey = data.key;
    lastCreatedUser = username;
    lastCreatedGame = game;
    document.getElementById('newKeyText').textContent = data.key;
    document.getElementById('newKeyUser').textContent = username;
    document.getElementById('newKeyGame').textContent = game.toUpperCase();
    document.getElementById('newKeyResult').classList.remove('hidden');
    showToast('Key created for ' + username + ' [' + game.toUpperCase() + ']');
    document.getElementById('keyUsername').value = '';
    document.getElementById('keyLabel').value = '';
    loadKeys();
  } catch(e) {
    showToast('Failed: ' + e.message, true);
  }
}

function copyKey() {
  navigator.clipboard.writeText(lastCreatedKey);
  showToast('Key copied!');
}

function copyAll() {
  navigator.clipboard.writeText('Key: ' + lastCreatedKey + '\\nUsername: ' + lastCreatedUser + '\\nGame: ' + lastCreatedGame.toUpperCase());
  showToast('Copied!');
}

async function toggleKey(key, active) {
  try {
    await api('toggle-key', { admin_password: adminPassword, key, active });
    showToast(active ? 'Key enabled' : 'Key disabled');
    loadKeys();
  } catch(e) { showToast('Failed: ' + e.message, true); }
}

async function resetHwid(key) {
  if (!confirm('Reset HWID for ' + key + '?')) return;
  try {
    await api('reset-hwid', { admin_password: adminPassword, key });
    showToast('HWID reset');
    loadKeys();
  } catch(e) { showToast('Failed: ' + e.message, true); }
}

async function deleteKey(key) {
  if (!confirm('Delete ' + key + '?')) return;
  try {
    await api('delete-key', { admin_password: adminPassword, key });
    showToast('Key deleted');
    loadKeys();
  } catch(e) { showToast('Failed: ' + e.message, true); }
}
</script>
</body>
</html>"""


@app.get("/", response_class=HTMLResponse)
def admin_panel():
    return ADMIN_HTML


@app.get("/api/health")
def health():
    return {"status": "ok", "service": "ArianKing Multi-Game Key Server", "games": VALID_GAMES}