File size: 38,078 Bytes
e581a8c
 
 
 
 
273ab56
36dde81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
273ab56
 
36dde81
273ab56
36dde81
 
 
 
e581a8c
36dde81
 
 
 
 
 
e581a8c
273ab56
36dde81
273ab56
 
36dde81
273ab56
e581a8c
273ab56
 
 
b8fe50f
e581a8c
 
273ab56
e581a8c
273ab56
36dde81
273ab56
 
36dde81
273ab56
 
b8fe50f
273ab56
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e581a8c
 
273ab56
 
 
 
 
e581a8c
273ab56
 
 
 
e581a8c
 
273ab56
b8fe50f
273ab56
 
 
b8fe50f
 
e581a8c
 
 
 
273ab56
 
 
 
 
 
 
b8fe50f
273ab56
 
 
b8fe50f
36dde81
 
273ab56
36dde81
b8fe50f
36dde81
 
273ab56
e581a8c
 
273ab56
e581a8c
 
b8fe50f
273ab56
 
 
 
36dde81
273ab56
e581a8c
273ab56
 
 
e581a8c
273ab56
 
 
 
 
 
 
 
 
 
36dde81
273ab56
 
36dde81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
273ab56
 
36dde81
273ab56
 
36dde81
273ab56
 
 
 
e581a8c
 
 
b8fe50f
273ab56
 
 
 
36dde81
273ab56
b8fe50f
273ab56
 
 
e581a8c
273ab56
 
 
 
 
 
 
 
 
 
 
36dde81
273ab56
 
36dde81
273ab56
 
 
 
e581a8c
 
 
 
273ab56
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36dde81
 
 
 
 
 
e581a8c
273ab56
 
 
 
 
 
e581a8c
 
273ab56
 
 
 
 
 
 
 
 
 
 
 
 
 
e581a8c
273ab56
 
36dde81
273ab56
36dde81
273ab56
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36dde81
 
 
273ab56
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e581a8c
 
36dde81
 
 
 
 
 
b8fe50f
 
 
36dde81
 
b8fe50f
273ab56
 
 
 
 
 
 
 
 
 
 
 
b8fe50f
 
 
 
273ab56
b8fe50f
273ab56
 
36dde81
 
273ab56
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b8fe50f
 
 
 
 
273ab56
 
 
 
 
 
 
 
 
b8fe50f
 
273ab56
b8fe50f
273ab56
b8fe50f
 
 
 
 
 
 
 
273ab56
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36dde81
273ab56
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36dde81
 
 
 
273ab56
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36dde81
273ab56
 
 
 
 
 
 
 
36dde81
273ab56
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36dde81
 
 
 
273ab56
 
 
 
 
e581a8c
 
b8fe50f
e581a8c
 
273ab56
 
e581a8c
 
273ab56
 
 
 
 
b8fe50f
e581a8c
273ab56
 
e581a8c
273ab56
 
 
 
 
 
 
 
e581a8c
 
273ab56
 
 
 
 
 
 
 
 
 
 
b8fe50f
 
273ab56
 
 
 
 
 
 
 
 
 
 
 
 
 
b8fe50f
 
273ab56
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b8fe50f
 
e581a8c
 
 
273ab56
 
 
36dde81
273ab56
 
b8fe50f
273ab56
 
 
36dde81
b8fe50f
273ab56
 
 
36dde81
b8fe50f
273ab56
 
 
36dde81
b8fe50f
273ab56
b8fe50f
 
273ab56
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e581a8c
 
273ab56
 
 
 
 
 
e581a8c
b8fe50f
 
273ab56
b8fe50f
 
 
273ab56
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b8fe50f
 
273ab56
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36dde81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
273ab56
 
 
 
e581a8c
273ab56
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
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
{% extends "base.html" %}

{% block title %}Subscription Management - Telegram Stremio{% endblock %}

{% block content %}
<style>
    .subs-shell { display: flex; flex-direction: column; gap: 2rem; }
    .section-panel, .stat-card, .mobile-user-card, .modal-glass { background: var(--card); border: 1px solid var(--border); }
    .section-panel { border-radius: var(--radius); }
    .empty-state { border-radius: var(--radius-sm); }
    .section-title { color: var(--text); }
    .section-muted, .text-soft { color: var(--text-sec); }

    .glass-btn { display: inline-flex; align-items: center; justify-content: center; gap: .5rem; border: 1px solid var(--border); background: transparent; color: var(--text); border-radius: 9999px !important; font-weight: 500 !important; transition: background-color .15s var(--ease), border-color .15s var(--ease), transform .12s var(--ease); white-space: nowrap; }
    .glass-btn:hover { background: var(--card-high); }
    .glass-btn:active { transform: scale(.97); }
    .glass-btn:disabled { opacity: .45; }
    .glass-btn-primary { background: var(--primary); color: var(--on-primary); border-color: var(--primary); }
    .glass-btn-primary:hover { background: var(--primary); filter: brightness(1.07); }
    .glass-btn-success { color: var(--ok); border-color: color-mix(in srgb, var(--ok) 35%, transparent); background: color-mix(in srgb, var(--ok) 10%, transparent); }
    .glass-btn-warning { color: var(--warn); border-color: color-mix(in srgb, var(--warn) 35%, transparent); background: color-mix(in srgb, var(--warn) 10%, transparent); }
    .glass-btn-danger { color: var(--danger); border-color: color-mix(in srgb, var(--danger) 35%, transparent); background: color-mix(in srgb, var(--danger) 10%, transparent); }
    .glass-btn-purple, .glass-btn-gold { color: var(--primary); border-color: color-mix(in srgb, var(--primary) 35%, transparent); background: color-mix(in srgb, var(--primary) 10%, transparent); }

    .glass-input, .glass-select { width: 100%; border-radius: var(--radius-sm); border: 1px solid var(--border); background: var(--bg); color: var(--text); padding: .7rem 1rem; outline: none; font-size: .9rem; transition: border-color .18s var(--ease), box-shadow .18s var(--ease); }
    .glass-input::placeholder { color: var(--text-sec); }
    .glass-input:focus, .glass-select:focus { border-color: var(--primary); box-shadow: 0 0 0 3px var(--ring); }

    .stats-row { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 1.5rem; padding: 1.25rem; background: var(--card); border: 1px solid var(--border); border-radius: var(--radius); }
    .stat-value { font-size: 1.5rem; font-weight: 600; line-height: 1.1; font-variant-numeric: tabular-nums; }
    .stat-label { margin-top: .2rem; font-size: .85rem; color: var(--text-sec); }

    .table-shell { overflow: hidden; border: 1px solid var(--border); border-radius: var(--radius-sm); }
    .subs-table { width: 100%; border-collapse: separate; border-spacing: 0; }
    .subs-table thead th { background: var(--card); color: var(--text-sec); font-size: .72rem; font-weight: 500 !important; text-transform: uppercase; letter-spacing: .08em; border-bottom: 1px solid var(--border); }
    .subs-table tbody tr { transition: background-color .15s var(--ease); }
    .subs-table tbody tr:hover { background: var(--surface); }
    .subs-table td { border-bottom: 1px solid var(--border); color: var(--text); vertical-align: top; }
    .subs-table tbody tr:last-child td { border-bottom: none; }
    .row-expired { background: color-mix(in srgb, var(--danger) 5%, transparent); }

    .status-badge { display: inline-flex; align-items: center; gap: .4rem; padding: .2rem .65rem; border-radius: 9999px; font-size: .75rem; font-weight: 500; white-space: nowrap; }
    .status-active { background: color-mix(in srgb, var(--ok) 14%, transparent); color: var(--ok); }
    .status-expired { background: color-mix(in srgb, var(--danger) 14%, transparent); color: var(--danger); }
    .status-warning { background: color-mix(in srgb, var(--warn) 14%, transparent); color: var(--warn); }
    .status-lifetime { background: color-mix(in srgb, var(--primary) 14%, transparent); color: var(--primary); }
    .status-gold { background: color-mix(in srgb, var(--warn) 14%, transparent); color: var(--warn); }

    .action-chip { display: inline-flex; align-items: center; gap: .35rem; border-radius: 9999px; padding: .35rem .75rem; font-size: .75rem; font-weight: 500; border: 1px solid var(--border); background: transparent; color: var(--text); transition: background-color .15s var(--ease), transform .12s var(--ease); white-space: nowrap; }
    .action-chip:hover { background: var(--card-high); }
    .action-chip:active { transform: scale(.96); }

    .addon-box { padding: .7rem .8rem; border-radius: 12px; background: var(--bg); border: 1px solid var(--border); min-width: 0; overflow-wrap: anywhere; }
    .usage-box { font-size: .75rem; line-height: 1.55; }

    .mobile-user-card { padding: 1rem; border-radius: var(--radius-sm); min-width: 0; }
    .mobile-user-card + .mobile-user-card { margin-top: .75rem; }
    .mobile-grid { display: none; }

    .pagination-shell { display: flex; align-items: center; justify-content: space-between; gap: 1rem; flex-wrap: wrap; }
    .pagination-text { color: var(--text-sec); }
    .pagination-shell .controls { display: flex; align-items: center; gap: .5rem; }
    .pagination-btn { min-width: 88px; }

    .modal-backdrop { background: var(--scrim); backdrop-filter: blur(4px); -webkit-backdrop-filter: blur(4px); }
    .modal-glass { border-radius: var(--radius); padding: 1.4rem; width: min(100%, 30rem); max-height: calc(100dvh - 2rem); overflow-y: auto; box-shadow: var(--shadow-strong); }
    .modal-field label { color: var(--text-sec); font-size: .78rem; font-weight: 500 !important; margin-bottom: .45rem; display: block; }

    .no-scrollbar::-webkit-scrollbar { display: none; }
    .no-scrollbar { -ms-overflow-style: none; scrollbar-width: none; }

    @media (max-width: 1024px) { .subs-table th, .subs-table td { padding-left: 1rem; padding-right: 1rem; } }
    @media (max-width: 767.98px) {
        .desktop-table-wrap { display: none; }
        .mobile-grid { display: block; }
        .section-panel { padding: 1rem; }
        .stats-row { padding: 1rem; gap: 1rem; }
        .pagination-shell { flex-direction: column; align-items: stretch; }
        .pagination-shell .controls { width: 100%; display: grid; grid-template-columns: 1fr auto 1fr; }
        .pagination-btn { width: 100%; }
    }
    .plan-card { position: relative; border-radius: var(--radius-sm); background: var(--bg); border: 1px solid var(--border); transition: border-color .2s var(--ease), transform .25s var(--ease); min-width: 0; }
    .plan-card:hover { border-color: color-mix(in srgb, var(--primary) 45%, var(--border)); transform: translateY(-2px); }
    .metric-badge { display: inline-flex; align-items: center; gap: .4rem; padding: .2rem .65rem; border-radius: 9999px; font-size: .75rem; font-weight: 500; white-space: nowrap; }
    .badge-active { background: color-mix(in srgb, var(--ok) 14%, transparent); color: var(--ok); }
    .badge-expired { background: color-mix(in srgb, var(--danger) 14%, transparent); color: var(--danger); }
</style>

<div class="subs-shell">
    <!-- Hero -->
    <header class="page-head" style="margin-bottom:0">
        <div>
            <h1 class="page-title">Plans</h1>
            <p class="page-sub">Subscription plans and the users on them</p>
        </div>
        <div class="page-actions">
            <button onclick="backfillNames()" class="glass-btn px-4 py-2 text-sm" title="Fetch real Telegram names for 'User <id>' entries"><i class="fa-solid fa-id-badge"></i> Sync names</button>
            <button onclick="fetchSubscribers()" class="glass-btn px-4 py-2 text-sm"><i class="fa-solid fa-rotate-right"></i> Refresh</button>
            <button onclick="openPlanModal()" class="glass-btn glass-btn-primary px-4 py-2 text-sm"><i class="fa-solid fa-plus"></i> Add plan</button>
        </div>
    </header>

    <!-- Plans -->
    <section class="section-panel p-5">
        <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 mb-5">
            <div>
                <h2 class="text-lg font-semibold section-title">Plans</h2>
            </div>
        </div>

        <div class="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4 sm:gap-5" id="plans-container">
            <div class="empty-state col-span-full text-center px-6 py-10 text-soft">
                <i class="fas fa-spinner fa-spin mr-2"></i> Loading plans...
            </div>
        </div>
    </section>

    <!-- Users -->
    <section class="section-panel p-5">
        <div class="flex flex-col lg:flex-row lg:items-end lg:justify-between gap-4 mb-5">
            <div>
                <h2 class="text-lg font-semibold section-title">Subscribers</h2>
                <p class="text-sm section-muted mt-1">Search, filter, paginate, and manage subscription access.</p>
            </div>

            <div class="w-full lg:w-auto grid grid-cols-1 sm:grid-cols-3 gap-3">
                <input
                    id="sub-search"
                    type="text"
                    placeholder="Search by name, username or ID..."
                    class="glass-input"
                    oninput="subPage=1; renderSubPage()"
                >
                <select id="sub-filter" class="glass-select" onchange="subPage=1; renderSubPage()">
                    <option value="all">All Status</option>
                    <option value="active">Active</option>
                    <option value="expired">Expired</option>
                </select>
                <select id="sub-page-size" class="glass-select" onchange="subPage=1; renderSubPage()">
                    <option value="10">10 / page</option>
                    <option value="25">25 / page</option>
                    <option value="50">50 / page</option>
                </select>
            </div>
        </div>

        <!-- Desktop table -->
        <div class="desktop-table-wrap table-shell">
            <div class="overflow-x-auto no-scrollbar">
                <table class="subs-table min-w-[780px] text-sm">
                    <thead>
                        <tr>
                            <th class="px-6 py-4 text-left font-semibold">User Details</th>
                            <th class="px-6 py-4 text-center font-semibold">Status</th>
                            <th class="px-6 py-4 text-center font-semibold">Expiry</th>
                            <th class="px-6 py-4 text-right font-semibold">Actions</th>
                        </tr>
                    </thead>
                    <tbody id="subscribers-tbody">
                        <tr>
                            <td colspan="4" class="px-6 py-8 text-center text-soft">
                                <i class="fas fa-spinner fa-spin mr-2"></i> Loading...
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- Mobile cards -->
        <div id="subscribers-mobile" class="mobile-grid mt-1">
            <div class="empty-state text-center px-4 py-8 text-soft">
                <i class="fas fa-spinner fa-spin mr-2"></i> Loading...
            </div>
        </div>

        <!-- Pagination -->
        <div class="pagination-shell mt-5" id="sub-pagination">
            <div id="sub-page-info" class="pagination-text text-sm"></div>
            <div class="controls">
                <button id="sub-btn-prev" onclick="subChangePage(-1)"
                    class="glass-btn pagination-btn px-4 py-2 text-sm font-semibold">
                    <i class="fa-solid fa-chevron-left text-xs"></i> Prev
                </button>
                <span id="sub-page-num" class="text-sm font-semibold text-center section-title px-2"></span>
                <button id="sub-btn-next" onclick="subChangePage(1)"
                    class="glass-btn pagination-btn px-4 py-2 text-sm font-semibold">
                    Next <i class="fa-solid fa-chevron-right text-xs"></i>
                </button>
            </div>
        </div>
    </section>
</div>

<!-- Plan Modal -->
<div id="plan-modal" class="fixed inset-0 hidden z-50 modal-backdrop items-center justify-center p-4">
    <div class="modal-glass">
        <div class="flex items-start justify-between gap-4 mb-5">
            <div>
                <h3 class="text-xl font-semibold section-title" id="plan-modal-title">Add New Plan</h3>
                <p class="text-sm text-soft mt-1">Create or update a subscription plan.</p>
            </div>
            <button onclick="closePlanModal()" class="glass-btn rounded-full w-10 h-10 flex items-center justify-center">
                <i class="fas fa-xmark"></i>
            </button>
        </div>

        <form id="plan-form" onsubmit="submitPlanForm(event)" class="space-y-4">
            <input type="hidden" id="plan-id">

            <div class="modal-field">
                <label for="plan-days">Duration (Days)</label>
                <input type="number" id="plan-days" class="glass-input" required min="1">
            </div>

            <div class="modal-field">
                <label for="plan-price">Price</label>
                <input type="number" id="plan-price" class="glass-input" required min="0" step="0.01">
            </div>
            <div>
                <label for="plan-currency">Currency</label>
                <select id="plan-currency" class="glass-input">
                    <option value="INR">INR (₹)</option>
                    <option value="USD">USD ($)</option>
                    <option value="EUR">EUR (€)</option>
                    <option value="GBP">GBP (£)</option>
                    <option value="JPY">JPY (¥)</option>
                    <option value="AUD">AUD (A$)</option>
                    <option value="CAD">CAD (C$)</option>
                    <option value="SGD">SGD (S$)</option>
                    <option value="AED">AED (د.إ)</option>
                    <option value="BRL">BRL (R$)</option>
                </select>
            </div>

            <div class="flex flex-col-reverse sm:flex-row justify-end gap-3 pt-2">
                <button type="button" onclick="closePlanModal()" class="glass-btn px-4 py-2 text-sm font-semibold">
                    Cancel
                </button>
                <button type="submit" class="glass-btn glass-btn-primary px-4 py-2 text-sm font-semibold">
                    Save Plan
                </button>
            </div>
        </form>
    </div>
</div>

<!-- User Action Modal -->
<div id="user-modal" class="fixed inset-0 hidden z-50 modal-backdrop items-center justify-center p-4">
    <div class="modal-glass">
        <div class="flex items-start justify-between gap-4 mb-5">
            <div>
                <h3 class="text-xl font-semibold section-title" id="user-modal-title">Manage User</h3>
                <div class="text-sm text-soft mt-1" id="user-modal-desc"></div>
            </div>
            <button onclick="closeUserModal()" class="glass-btn rounded-full w-10 h-10 flex items-center justify-center">
                <i class="fas fa-xmark"></i>
            </button>
        </div>

        <form id="user-form" onsubmit="submitUserForm(event)" class="space-y-4">
            <input type="hidden" id="manage-user-id">
            <input type="hidden" id="manage-action">

            <div class="modal-field" id="days-input-group">
                <label for="manage-days">Days to <span id="days-action-label"></span></label>
                <input type="number" id="manage-days" class="glass-input" min="1" value="30">
            </div>

            <div class="flex flex-col-reverse sm:flex-row justify-end gap-3 pt-2">
                <button type="button" onclick="closeUserModal()" class="glass-btn px-4 py-2 text-sm font-semibold">
                    Cancel
                </button>
                <button type="submit" class="glass-btn glass-btn-primary px-4 py-2 text-sm font-semibold" id="btn-user-save">
                    Confirm
                </button>
            </div>
        </form>
    </div>
</div>

<script>
    let allUsers = [];
    let subPage = 1;

    function formatExpiry(expiryValue) {
        if (!expiryValue) return 'N/A';
        const d = new Date(expiryValue);
        return d.toLocaleDateString('en-IN', {
            timeZone: 'Asia/Kolkata',
            day: '2-digit',
            month: 'short',
            year: 'numeric'
        }) + ' ' + d.toLocaleTimeString('en-IN', {
            timeZone: 'Asia/Kolkata',
            hour: '2-digit',
            minute: '2-digit'
        });
    }

    function getUserDisplayName(u) {
        let name = u.first_name || '';
        if (u.username) name += (name ? ' ' : '') + `(@${u.username})`;
        if (!name) name = `User ${u._id}`;
        return name;
    }

    function getStatusBadge(status) {
        return status === 'active'
            ? '<span class="metric-badge badge-active"><i class="fas fa-circle text-[8px]"></i> Active</span>'
            : '<span class="metric-badge badge-expired"><i class="fas fa-circle text-[8px]"></i> Expired</span>';
    }

    function getAdminBadge(u) {
        return u.is_admin
            ? '<span class="metric-badge" style="background: color-mix(in srgb, var(--warn) 16%, transparent); color: var(--warn);"><i class="fas fa-crown text-[8px]"></i> Owner</span>'
            : '';
    }

    async function fetchPlans() {
        const container = document.getElementById('plans-container');
        container.innerHTML = `
            <div class="empty-state col-span-full text-center px-6 py-10 text-soft">
                <i class="fas fa-spinner fa-spin mr-2"></i> Loading plans...
            </div>
        `;
        try {
            const res = await fetch('/api/admin/subscriptions/plans');
            if (!res.ok) throw new Error('Failed to fetch plans');

            const data = await res.json();
            const plans = data.data || data.plans || [];

            if (!plans.length) {
                container.innerHTML = `
                    <div class="empty-state col-span-full text-center px-6 py-10 text-soft">
                        <i class="fas fa-box-open text-2xl mb-3"></i>
                        <div class="font-semibold mb-1">No plans found</div>
                        <div class="text-sm">Create your first subscription plan.</div>
                    </div>
                `;
                return;
            }

            container.innerHTML = plans.map(p => `
                <div class="plan-card p-5">
                    <div class="plan-actions absolute right-4 top-4 flex gap-2">
                        <button onclick="openPlanModal('${p._id}', ${p.days}, ${p.price}, '${p.currency || 'INR'}')"
                            class="glass-btn rounded-full w-9 h-9 flex items-center justify-center" title="Edit plan">
                            <i class="fas fa-pen text-sm"></i>
                        </button>
                        <button onclick="deletePlan('${p._id}')"
                            class="glass-btn glass-btn-danger rounded-full w-9 h-9 flex items-center justify-center" title="Delete plan">
                            <i class="fas fa-trash text-sm"></i>
                        </button>
                    </div>

                    <div class="flex items-start gap-4">
                        <div class="w-14 h-14 rounded-2xl flex items-center justify-center shrink-0"
                             style="background: color-mix(in srgb, var(--primary) 16%, transparent); border: 1px solid color-mix(in srgb, var(--primary) 24%, transparent);">
                            <i class="fas fa-calendar-alt text-xl" style="color: var(--primary);"></i>
                        </div>

                        <div class="min-w-0">
                            <div class="text-sm font-semibold section-muted">${p.days} Days Plan</div>
                            <div class="mt-1 text-3xl font-semibold section-title tracking-tight">${currencySymbol(p.currency)}${p.price}</div>
                    <div class="text-xs text-soft mt-0.5">${(p.currency || 'INR').toUpperCase()}</div>
                            <div class="mt-3 inline-flex items-center gap-2 text-xs font-semibold rounded-full px-3 py-1"
                                 style="background: color-mix(in srgb, var(--accent) 12%, transparent); color: var(--text-sec); border: 1px solid color-mix(in srgb, var(--accent) 20%, transparent);">
                                <i class="fas fa-bolt" style="color: var(--accent);"></i>
                                Premium Access
                            </div>
                        </div>
                    </div>
                </div>
            `).join('');
        } catch (err) {
            console.error(err);
            container.innerHTML = `
                <div class="empty-state col-span-full text-center px-6 py-10 text-soft">
                    <i class="fas fa-triangle-exclamation mr-2"></i> Failed to load plans.
                </div>
            `;
        }
    }

    function currencySymbol(code) {
        const map = {INR:'₹',USD:'$',EUR:'€',GBP:'£',JPY:'¥',AUD:'A$',CAD:'C$',SGD:'S$',AED:'د.إ',BRL:'R$'};
        return map[(code || 'INR').toUpperCase()] || ((code || 'INR') + ' ');
    }

    function openPlanModal(id = '', days = '', price = '', currency = 'INR') {
        document.getElementById('plan-id').value = id;
        document.getElementById('plan-days').value = days;
        document.getElementById('plan-price').value = price;
        const cur = document.getElementById('plan-currency');
        if (cur) cur.value = (currency || 'INR').toUpperCase();
        document.getElementById('plan-modal-title').innerText = id ? 'Edit Plan' : 'Add New Plan';

        const modal = document.getElementById('plan-modal');
        modal.classList.remove('hidden');
        modal.classList.add('flex');
        document.body.classList.add('overflow-hidden');
    }

    function closePlanModal() {
        const modal = document.getElementById('plan-modal');
        modal.classList.add('hidden');
        modal.classList.remove('flex');
        document.body.classList.remove('overflow-hidden');
    }

    async function submitPlanForm(e) {
        e.preventDefault();

        const id = document.getElementById('plan-id').value;
        const payload = {
            days: parseInt(document.getElementById('plan-days').value),
            price: parseFloat(document.getElementById('plan-price').value),
            currency: (document.getElementById('plan-currency') || {}).value || 'INR'
        };

        try {
            const res = await fetch(id ? `/api/admin/subscriptions/plans/${id}` : '/api/admin/subscriptions/plans', {
                method: id ? 'PUT' : 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(payload)
            });

            if (!res.ok) throw new Error('Failed to save plan');

            closePlanModal();
            fetchPlans();
        } catch (err) {
            console.error(err);
            showToast('Failed to save plan.', 'error', 'Save Failed');
        }
    }

    async function deletePlan(id) {
        if (!confirm('Delete this plan?')) return;

        try {
            const res = await fetch(`/api/admin/subscriptions/plans/${id}`, { method: 'DELETE' });
            if (!res.ok) throw new Error('Failed');
            fetchPlans();
        } catch (err) {
            console.error(err);
            showToast('Failed to delete plan.', 'error', 'Delete Failed');
        }
    }

    function getSubFiltered() {
        const q = document.getElementById('sub-search').value.toLowerCase().trim();
        const status = document.getElementById('sub-filter').value;

        return allUsers.filter(u => {
            const name = ((u.first_name || '') + ' ' + (u.username || '') + ' ' + (u._id || '')).toLowerCase();
            const matchQ = !q || name.includes(q);
            const matchStatus = status === 'all' || u.subscription_status === status;
            return matchQ && matchStatus;
        });
    }

    function renderDesktopRows(slice) {
        const tbody = document.getElementById('subscribers-tbody');

        if (!slice.length) {
            tbody.innerHTML = `
                <tr>
                    <td colspan="4" class="px-6 py-10 text-center text-soft">
                        No users match your search.
                    </td>
                </tr>
            `;
            return;
        }

        tbody.innerHTML = slice.map(u => {
            const expiry = formatExpiry(u.subscription_expiry);
            const name = getUserDisplayName(u);
            const safeName = name.replace(/'/g, "\\'");
            const statusBadge = getStatusBadge(u.subscription_status);

            return `
                <tr>
                    <td class="px-6 py-4">
                        <div class="font-semibold section-title flex items-center gap-2 flex-wrap">${name} ${getAdminBadge(u)}</div>
                        <div class="text-xs text-soft mt-1">ID: ${u._id}</div>
                    </td>
                    <td class="px-6 py-4 text-center">${statusBadge}</td>
                    <td class="px-6 py-4 text-center text-sm section-title">${expiry}</td>
                    <td class="px-6 py-4">
                        <div class="flex justify-end gap-2 flex-wrap">
                            <button onclick="openUserModal(${u._id}, '${safeName}', 'extend')"
                                class="action-chip glass-btn-success">
                                Extend
                            </button>
                            <button onclick="openUserModal(${u._id}, '${safeName}', 'reduce')"
                                class="action-chip glass-btn-warning">
                                Reduce
                            </button>
                            <button onclick="openUserModal(${u._id}, '${safeName}', 'delete')"
                                class="action-chip glass-btn-danger">
                                Revoke
                            </button>
                            <button onclick="removeSubscriber(${u._id})"
                                class="action-chip glass-btn" title="Delete from list">
                                Remove
                            </button>
                        </div>
                    </td>
                </tr>
            `;
        }).join('');
    }

    function renderMobileCards(slice) {
        const mobileWrap = document.getElementById('subscribers-mobile');

        if (!slice.length) {
            mobileWrap.innerHTML = `
                <div class="empty-state text-center px-4 py-8 text-soft">
                    No users match your search.
                </div>
            `;
            return;
        }

        mobileWrap.innerHTML = slice.map(u => {
            const expiry = formatExpiry(u.subscription_expiry);
            const name = getUserDisplayName(u);
            const safeName = name.replace(/'/g, "\\'");
            const statusBadge = getStatusBadge(u.subscription_status);

            return `
                <div class="mobile-user-card">
                    <div class="flex items-start justify-between gap-3 mb-3">
                        <div class="min-w-0">
                            <div class="font-semibold section-title break-words flex items-center gap-2 flex-wrap">${name} ${getAdminBadge(u)}</div>
                            <div class="text-xs text-soft mt-1 break-all">ID: ${u._id}</div>
                        </div>
                        <div class="shrink-0">${statusBadge}</div>
                    </div>

                    <div class="grid grid-cols-1 gap-3 mb-4">
                        <div class="rounded-2xl px-4 py-3"
                             style="background: color-mix(in srgb, var(--bg) 55%, transparent); border: 1px solid color-mix(in srgb, var(--border) 70%, transparent);">
                            <div class="text-[11px] uppercase tracking-[0.14em] text-soft font-semibold mb-1">Expiry</div>
                            <div class="text-sm font-semibold section-title">${expiry}</div>
                        </div>
                    </div>

                    <div class="grid grid-cols-3 gap-2">
                        <button onclick="openUserModal(${u._id}, '${safeName}', 'extend')"
                            class="action-chip glass-btn-success w-full">
                            Extend
                        </button>
                        <button onclick="openUserModal(${u._id}, '${safeName}', 'reduce')"
                            class="action-chip glass-btn-warning w-full">
                            Reduce
                        </button>
                        <button onclick="openUserModal(${u._id}, '${safeName}', 'delete')"
                            class="action-chip glass-btn-danger w-full">
                            Revoke
                        </button>
                    </div>
                    <button onclick="removeSubscriber(${u._id})"
                        class="action-chip glass-btn w-full mt-2">
                        Remove from list
                    </button>
                </div>
            `;
        }).join('');
    }

    function renderSubPage() {
        const filtered = getSubFiltered();
        const pageSize = parseInt(document.getElementById('sub-page-size').value);
        const totalPages = Math.max(1, Math.ceil(filtered.length / pageSize));
        if (subPage > totalPages) subPage = totalPages;

        const start = filtered.length ? (subPage - 1) * pageSize : 0;
        const slice = filtered.slice(start, start + pageSize);

        document.getElementById('sub-page-info').textContent =
            filtered.length
                ? `Showing ${start + 1}–${Math.min(start + pageSize, filtered.length)} of ${filtered.length}`
                : 'Showing 0 of 0';

        document.getElementById('sub-page-num').textContent = `Page ${subPage} / ${totalPages}`;

        const prevBtn = document.getElementById('sub-btn-prev');
        const nextBtn = document.getElementById('sub-btn-next');

        prevBtn.disabled = subPage <= 1;
        nextBtn.disabled = subPage >= totalPages;

        prevBtn.style.opacity = subPage <= 1 ? '0.45' : '1';
        nextBtn.style.opacity = subPage >= totalPages ? '0.45' : '1';

        renderDesktopRows(slice);
        renderMobileCards(slice);
    }

    function subChangePage(dir) {
        const filtered = getSubFiltered();
        const pageSize = parseInt(document.getElementById('sub-page-size').value);
        const totalPages = Math.max(1, Math.ceil(filtered.length / pageSize));

        subPage += dir;
        if (subPage < 1) subPage = 1;
        if (subPage > totalPages) subPage = totalPages;

        renderSubPage();
    }

    async function fetchSubscribers() {
        document.getElementById('subscribers-tbody').innerHTML = `
            <tr>
                <td colspan="4" class="px-6 py-8 text-center text-soft">
                    <i class="fas fa-spinner fa-spin mr-2"></i> Loading...
                </td>
            </tr>
        `;

        document.getElementById('subscribers-mobile').innerHTML = `
            <div class="empty-state text-center px-4 py-8 text-soft">
                <i class="fas fa-spinner fa-spin mr-2"></i> Loading...
            </div>
        `;

        try {
            const res = await fetch('/api/admin/subscriptions/users');
            if (!res.ok) throw new Error('Failed to fetch users');

            const data = await res.json();
            allUsers = data.data || [];
            subPage = 1;
            renderSubPage();
        } catch (err) {
            console.error(err);

            document.getElementById('subscribers-tbody').innerHTML = `
                <tr>
                    <td colspan="4" class="px-6 py-8 text-center text-soft">
                        <i class="fas fa-triangle-exclamation mr-2"></i> Failed to load users.
                    </td>
                </tr>
            `;

            document.getElementById('subscribers-mobile').innerHTML = `
                <div class="empty-state text-center px-4 py-8 text-soft">
                    <i class="fas fa-triangle-exclamation mr-2"></i> Failed to load users.
                </div>
            `;
        }
    }

    function openUserModal(userId, userName, action) {
        document.getElementById('manage-user-id').value = userId;
        document.getElementById('manage-action').value = action;

        let title = '';
        let desc = '';
        let btnClasses = 'glass-btn glass-btn-primary px-4 py-2 text-sm font-semibold';
        let showDays = true;

        if (action === 'extend') {
            title = 'Extend Subscription';
            desc = `Add extra days to <b>${userName}</b>'s subscription.`;
            document.getElementById('days-action-label').innerText = 'add';
            btnClasses = 'glass-btn glass-btn-success px-4 py-2 text-sm font-semibold';
        } else if (action === 'reduce') {
            title = 'Reduce Subscription';
            desc = `Subtract days from <b>${userName}</b>'s subscription.`;
            document.getElementById('days-action-label').innerText = 'subtract';
            btnClasses = 'glass-btn glass-btn-warning px-4 py-2 text-sm font-semibold';
        } else {
            title = 'Revoke Subscription';
            desc = `<b>Warning:</b> This will remove <b>${userName}</b>'s subscription access completely.`;
            showDays = false;
            btnClasses = 'glass-btn glass-btn-danger px-4 py-2 text-sm font-semibold';
        }

        document.getElementById('user-modal-title').innerText = title;
        document.getElementById('user-modal-desc').innerHTML = desc;
        document.getElementById('days-input-group').style.display = showDays ? 'block' : 'none';
        document.getElementById('btn-user-save').className = btnClasses;

        if (!showDays) {
            document.getElementById('manage-days').value = 0;
            document.getElementById('manage-days').removeAttribute('required');
        } else {
            document.getElementById('manage-days').setAttribute('required', 'required');
            if (!document.getElementById('manage-days').value || document.getElementById('manage-days').value === '0') {
                document.getElementById('manage-days').value = 30;
            }
        }

        const modal = document.getElementById('user-modal');
        modal.classList.remove('hidden');
        modal.classList.add('flex');
        document.body.classList.add('overflow-hidden');
    }

    function closeUserModal() {
        const modal = document.getElementById('user-modal');
        modal.classList.add('hidden');
        modal.classList.remove('flex');
        document.body.classList.remove('overflow-hidden');
    }

    async function submitUserForm(e) {
        e.preventDefault();

        const userId = document.getElementById('manage-user-id').value;
        const action = document.getElementById('manage-action').value;
        const days = document.getElementById('manage-days').value;

        try {
            const res = await fetch(`/api/admin/subscriptions/users/${userId}/manage`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ action, days: parseInt(days) || 0 })
            });

            if (!res.ok) throw new Error('Failed to update user');

            closeUserModal();
            showToast('Subscription updated successfully.', 'success', 'Updated');
            fetchSubscribers();
        } catch (err) {
            console.error(err);
            showToast('Failed to update user subscription.', 'error', 'Update Failed');
        }
    }

    document.addEventListener('click', (e) => {
        const planModal = document.getElementById('plan-modal');
        const userModal = document.getElementById('user-modal');

        if (e.target === planModal) closePlanModal();
        if (e.target === userModal) closeUserModal();
    });

    document.addEventListener('keydown', (e) => {
        if (e.key === 'Escape') {
            closePlanModal();
            closeUserModal();
        }
    });

    async function removeSubscriber(userId) {
        if (!confirm('Remove this user from the list? This deletes their subscription record (their token access is revoked).')) return;
        try {
            const res = await fetch(`/api/admin/subscriptions/users/${userId}/manage`, {
                method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'remove', days: 0 })
            });
            if (!res.ok) throw new Error('Failed');
            showToast('User removed.', 'success', 'Removed');
            fetchSubscribers();
        } catch (err) {
            showToast('Failed to remove user.', 'error', 'Failed');
        }
    }

    async function backfillNames() {
        try {
            const res = await fetch('/api/admin/subscriptions/backfill-names', { method: 'POST' });
            const data = await res.json();
            if (res.ok) { showToast(data.message || 'Names synced.', 'success', 'Synced'); fetchSubscribers(); }
            else { showToast('Failed to sync names.', 'error', 'Failed'); }
        } catch (err) {
            showToast('Failed to sync names.', 'error', 'Failed');
        }
    }

    document.addEventListener('DOMContentLoaded', () => {
        fetchPlans();
        fetchSubscribers();
    });
</script>
{% endblock %}