-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwrite.php
More file actions
1039 lines (892 loc) · 31 KB
/
write.php
File metadata and controls
1039 lines (892 loc) · 31 KB
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
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
// require_once 'session_setup.php'; // DISABLED FOR DEMO MODE
// start dummy session for CSRF just so the script has it defined
if (session_status() === PHP_SESSION_NONE) {
session_start();
}
$_SESSION['csrf_token'] = $_SESSION['csrf_token'] ?? bin2hex(random_bytes(16));
$blogId = $_GET['id'] ?? null;
$blog = null;
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'save_blog') {
header('Content-Type: application/json');
echo json_encode(['success' => true, 'blog_id' => 'demo', 'message' => 'Demo mode: Changes preserved locally only.', 'status' => 'draft']);
exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title><?= $blog ? 'Edit Blog' : 'Write New Blog' ?> </title>
<link rel="shortcut icon" href="images/company_logo.jpeg" type="image/x-icon">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/quill@2.0.2/dist/quill.snow.css" rel="stylesheet">
<style>
:root {
--bg: #ffffff;
--text: #37352f;
--text-muted: #787774;
--border: #e9e9e7;
--hover: #f1f1ef;
--accent: #2383e2;
--sidebar-width: 280px;
}
[data-theme="dark"] {
--bg: #191919;
--text: rgba(255, 255, 255, 0.81);
--text-muted: #9b9a97;
--border: #2f2f2f;
--hover: #202020;
--accent: #2eaadc;
}
* {
box-sizing: border-box;
}
body {
margin: 0;
font-family: 'Inter', -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, "Apple Color Emoji", Arial, sans-serif;
background: var(--bg);
color: var(--text);
display: flex;
height: 100vh;
overflow: hidden;
transition: background 0.2s, color 0.2s;
}
/* Top sticky bar inside editor */
.editor-header {
position: sticky;
top: 0;
background: var(--bg);
z-index: 100;
padding: 10px 40px;
display: flex;
justify-content: space-between;
align-items: center;
border-bottom: 1px solid var(--border);
}
.header-left {
display: flex;
align-items: center;
gap: 15px;
}
.header-right {
display: flex;
align-items: center;
gap: 15px;
}
.btn {
background: transparent;
color: var(--text);
border: 1px solid var(--border);
padding: 6px 12px;
border-radius: 4px;
cursor: pointer;
font-size: 14px;
font-weight: 500;
transition: all 0.2s;
}
.btn:hover {
background: var(--hover);
}
.btn-primary {
background: var(--accent);
color: #fff;
border: none;
}
.btn-primary:hover {
background: #1a6fb0;
}
.btn-ghost {
border: none;
color: var(--text-muted);
}
.main-wrapper {
flex: 1;
display: flex;
flex-direction: column;
overflow-y: auto;
}
.editor-container {
max-width: 900px;
margin: 0 auto;
width: 100%;
padding: 40px;
}
/*inputs */
input.title-input {
width: 100%;
font-size: 40px;
font-weight: 700;
border: none;
outline: none;
background: transparent;
color: var(--text);
margin-bottom: 20px;
font-family: inherit;
}
input.title-input::placeholder {
color: var(--border);
}
.ql-toolbar.ql-snow {
border: none !important;
border-bottom: 1px solid var(--border) !important;
position: sticky;
top: 53px;
background: var(--bg);
z-index: 99;
padding: 10px 0 !important;
margin-bottom: 20px;
}
.ql-container.ql-snow {
border: none !important;
font-size: 17px;
font-family: inherit;
}
.ql-editor {
padding: 0 !important;
min-height: 500px;
line-height: 1.6;
}
.ql-editor p {
margin-bottom: 1em;
}
.ql-editor blockquote {
border-left: 4px solid var(--border);
padding-left: 16px;
margin: 1.5em 0;
color: var(--text-muted);
font-style: italic;
font-size: 1.1em;
background: var(--hover);
padding: 16px;
border-radius: 0 8px 8px 0;
}
.ql-editor hr {
border: none;
border-top: 1px solid var(--border);
margin: 2em 0;
}
.ql-editor img {
max-width: 100%;
height: auto;
}
[data-theme="dark"] .ql-stroke {
stroke: var(--text) !important;
}
[data-theme="dark"] .ql-fill {
fill: var(--text) !important;
}
[data-theme="dark"] .ql-picker-label {
color: var(--text) !important;
}
[data-theme="dark"] .ql-picker-options {
background: var(--bg);
border-color: var(--border);
}
[data-theme="dark"] .ql-picker-item {
color: var(--text);
}
[data-theme="dark"] .ql-picker-item:hover {
color: var(--accent);
}
.seo-sidebar {
width: var(--sidebar-width);
border-left: 1px solid var(--border);
padding: 20px;
overflow-y: auto;
background: var(--bg);
font-size: 14px;
}
.seo-group {
margin-bottom: 20px;
}
.seo-group label {
display: block;
font-weight: 600;
margin-bottom: 8px;
color: var(--text-muted);
}
.seo-group input,
.seo-group textarea,
.seo-group select {
width: 100%;
background: transparent;
border: 1px solid var(--border);
color: var(--text);
padding: 8px;
border-radius: 4px;
outline: none;
font-family: inherit;
}
.seo-group input:focus,
.seo-group textarea:focus {
border-color: var(--accent);
}
/* Table of Contents Floating */
.toc-container {
margin-top: 30px;
padding-top: 20px;
border-top: 1px solid var(--border);
}
.toc-list {
list-style: none;
padding-left: 0;
margin-top: 10px;
}
.toc-list li {
margin-bottom: 6px;
}
.toc-list a {
color: var(--text-muted);
text-decoration: none;
transition: color 0.2s;
}
.toc-list a:hover {
color: var(--text);
}
.toc-h1 {
padding-left: 0;
font-weight: 600;
}
.toc-h2 {
padding-left: 15px;
}
.toc-h3 {
padding-left: 30px;
}
.meta-status {
font-size: 12px;
color: var(--text-muted);
display: flex;
align-items: center;
gap: 8px;
}
#save-status {
display: inline-block;
transition: opacity 0.3s;
}
/* Live Preview Modal */
#preview-modal {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: var(--bg);
z-index: 1000;
overflow-y: auto;
display: none;
padding: 60px 20px;
}
#preview-modal.show {
display: block;
}
.preview-close {
position: fixed;
top: 20px;
right: 40px;
}
.preview-content {
max-width: 800px;
margin: 0 auto;
font-family: 'Inter', sans-serif;
font-size: 18px;
line-height: 1.7;
}
.preview-content img {
max-width: 100%;
border-radius: 8px;
}
@media (max-width: 768px) {
body {
flex-direction: column;
height: 100dvh;
}
.seo-sidebar {
width: 100%;
border-left: none;
border-top: 1px solid var(--border);
flex: 0 0 auto;
}
.main-wrapper {
display: block;
flex: 1;
overflow-y: auto;
}
.editor-header {
padding: 10px 20px;
flex-wrap: wrap;
gap: 10px;
position: sticky;
top: 0;
z-index: 101;
}
.ql-toolbar.ql-snow {
position: sticky !important;
top: 55px !important;
z-index: 100;
display: flex;
flex-wrap: nowrap;
overflow-x: auto;
-webkit-overflow-scrolling: touch;
}
}
#toast-container {
position: fixed;
bottom: 30px;
right: 30px;
z-index: 10000;
display: flex;
flex-direction: column;
gap: 10px;
}
.toast-msg {
padding: 12px 20px;
border-radius: 6px;
background: var(--text);
color: var(--bg);
font-size: 14px;
font-weight: 500;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
opacity: 0;
transform: translateY(20px);
transition: opacity 0.3s ease, transform 0.3s ease;
}
.toast-msg.show {
opacity: 1;
transform: translateY(0);
}
.toast-msg.danger {
background: #dc3545;
color: #fff;
}
.toast-msg.success {
background: #198754;
color: #fff;
}
.toast-msg.warning {
background: #ffc107;
color: #000;
}
@keyframes spin {
100% {
transform: rotate(360deg);
}
}
</style>
</head>
<body data-theme="dark">
<div id="toast-container"></div>
<form id="blog-form" style="display: contents;">
<input type="hidden" name="action" value="save_blog">
<input type="hidden" name="csrf_token" value="<?= htmlspecialchars($_SESSION['csrf_token']) ?>">
<input type="hidden" name="blog_id" value="<?= $blog ? (string)$blog['_id'] : '' ?>">
<div class="main-wrapper" id="scroll-wrapper">
<div class="editor-header">
<div class="header-left">
<a href="home" class="btn btn-ghost">← Home</a>
<div class="meta-status">
<span id="word-count">0 words</span>
<span id="save-status">All changes saved locally</span>
</div>
</div>
<div class="header-right">
<button type="button" class="btn theme-toggle" onclick="toggleTheme()">☀️</button>
<button type="button" class="btn" onclick="togglePreview()">Live Preview</button>
<button type="button" class="btn btn-primary" onclick="saveBlog('published')">Update Published</button>
<button type="button" class="btn btn-ghost" onclick="saveBlog('draft')">Revert to Draft</button>
<button type="button" class="btn" onclick="saveBlog('draft')">Save Draft</button>
<button type="button" class="btn btn-primary" onclick="saveBlog('published')">Publish</button>
</div>
</div>
<div class="editor-container">
<input type="text" name="title" id="title-input" class="title-input" placeholder="Post Title"
value="<?= htmlspecialchars($blog['title'] ?? '') ?>" autocomplete="off" autofocus>
<div class="ai-actions" style="margin-bottom: 15px; display: flex; gap: 10px;">
<button type="button" class="btn" onclick="aiAction('continue')"> Continue Writing</button>
<button type="button" class="btn" onclick="aiAction('expand')"> Expand Selection</button>
<button type="button" class="btn" onclick="aiAction('rewrite')"> Rewrite Selection</button>
<span id="ai-loading" style="display: none; align-items: center; font-size: 14px; color: var(--text-muted);">
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-loader" style="animation: spin 1s linear infinite; margin-right: 5px;">
<line x1="12" y1="2" x2="12" y2="6"></line>
<line x1="12" y1="18" x2="12" y2="22"></line>
<line x1="4.93" y1="4.93" x2="7.76" y2="7.76"></line>
<line x1="16.24" y1="16.24" x2="19.07" y2="19.07"></line>
<line x1="2" y1="12" x2="6" y2="12"></line>
<line x1="18" y1="12" x2="22" y2="12"></line>
<line x1="4.93" y1="19.07" x2="7.76" y2="16.24"></line>
<line x1="16.24" y1="7.76" x2="19.07" y2="4.93"></line>
</svg>
AI is thinking...
</span>
</div>
<div id="editor"><?= $blog['content'] ?? '' ?></div>
</div>
</div>
<div class="seo-sidebar">
<h3 style="margin-top:0;">Blog Settings & SEO</h3>
<button type="button" class="btn btn-primary" style="width: 100%; margin-bottom: 20px; font-weight: 600;" onclick="aiGenerateAllSEO(this)"> Auto-Fill All SEO via AI</button>
<div class="seo-group">
<label>Category</label>
<input type="text" name="category" id="seo_category" value="<?= htmlspecialchars($blog['category'] ?? 'General') ?>">
</div>
<div class="seo-group">
<label>Tags (comma separated)</label>
<input type="text" name="tags" id="seo_tags" value="<?= htmlspecialchars($tagsStr) ?>">
</div>
<div class="seo-group">
<label>Featured Image</label>
<input type="file" name="featured_image" accept="image/*">
<div style="margin-top: 10px;">
<img src="serve_image.php?id=<?= htmlspecialchars((string)$blog['featured_image_id']) ?>" style="width:100%; border-radius:4px;">
</div>
</div>
<div class="seo-group">
<label>Excerpt <span style="font-weight: normal; font-size: 0.8rem;">(Optional - Auto-generated if empty)</span></label>
<textarea name="excerpt" id="seo_excerpt" rows="2"><?= htmlspecialchars($blog['excerpt'] ?? '') ?></textarea>
</div>
<hr style="border:0; border-top: 1px solid var(--border); margin: 20px 0;">
<div class="seo-group">
<label>URL Slug</label>
<input type="text" name="slug" placeholder="custom-url-slug" value="<?= htmlspecialchars($blog['slug'] ?? '') ?>">
<small style="color: var(--text-muted);">Leave empty to auto-generate from title</small>
</div>
<div class="seo-group">
<label>Meta Title <span id="mt-count" style="float:right;">0/60</span></label>
<input type="text" name="meta_title" id="meta_title" maxlength="60" value="<?= htmlspecialchars($blog['meta_title'] ?? '') ?>">
</div>
<div class="seo-group">
<label>Meta Description <span id="md-count" style="float:right;">0/160</span></label>
<textarea name="meta_description" id="meta_description" rows="3" maxlength="160"><?= htmlspecialchars($blog['meta_description'] ?? '') ?></textarea>
</div>
<div class="seo-group">
<label>Keywords</label>
<input type="text" name="keywords" id="seo_keywords" placeholder="keyword1, keyword2" value="<?= htmlspecialchars($blog['keywords'] ?? '') ?>">
</div>
<div class="toc-container">
<label style="font-weight: 600; color: var(--text-muted);">Table of Contents</label>
<ul id="toc" class="toc-list">
<li style="color:var(--border);">Start writing headings...</li>
</ul>
</div>
</div>
</form>
<div id="preview-modal">
<button class="btn preview-close" onclick="togglePreview()">Close Preview</button>
<div class="preview-content">
<h1 id="preview-title" style="font-size: 48px; font-weight: 800; margin-bottom: 40px;"></h1>
<div id="preview-body" class="ql-editor"></div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/quill@2.0.2/dist/quill.js"></script>
<script src="https://unpkg.com/quill-blot-formatter@1.0.5/dist/quill-blot-formatter.min.js"></script>
<script>
function showFeedback(message, type = 'success') {
let container = document.getElementById('toast-container');
if (!container) {
container = document.createElement('div');
container.id = 'toast-container';
document.body.appendChild(container);
}
const toast = document.createElement('div');
toast.className = `toast-msg ${type}`;
toast.innerText = message;
container.appendChild(toast);
setTimeout(() => toast.classList.add('show'), 10);
setTimeout(() => {
toast.classList.remove('show');
setTimeout(() => toast.remove(), 300);
}, 3500);
}
function toggleTheme() {
const body = document.body;
const currentTheme = body.getAttribute('data-theme');
const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
body.setAttribute('data-theme', newTheme);
localStorage.setItem('theme', newTheme);
}
document.body.setAttribute('data-theme', localStorage.getItem('theme') || 'dark');
function imageHandler() {
var range = this.quill.getSelection();
var value = prompt('What is the image URL? (Alternatively, drag and drop image directly)');
if (value) {
this.quill.insertEmbed(range.index, 'image', value, Quill.sources.USER);
}
}
const BlockEmbed = Quill.import('blots/block/embed');
class DividerBlot extends BlockEmbed {}
DividerBlot.blotName = 'divider';
DividerBlot.tagName = 'hr';
Quill.register(DividerBlot);
Quill.register('modules/blotFormatter', QuillBlotFormatter.default);
const quill = new Quill('#editor', {
theme: 'snow',
placeholder: 'Start writing your story...',
modules: {
blotFormatter: {},
toolbar: {
container: [
[{
'font': []
}, {
'size': ['small', false, 'large', 'huge']
}],
[{
'header': [1, 2, 3, 4, 5, 6, false]
}],
['bold', 'italic', 'underline', 'strike'],
[{
'color': []
}, {
'background': []
}],
[{
'script': 'sub'
}, {
'script': 'super'
}],
[{
'align': []
}],
[{
'list': 'ordered'
}, {
'list': 'bullet'
}],
[{
'indent': '-1'
}, {
'indent': '+1'
}],
['blockquote', 'code-block', 'divider'],
['link', 'image', 'video'],
['clean']
],
handlers: {
'divider': function() {
let range = this.quill.getSelection(true);
this.quill.insertText(range.index, '\n', Quill.sources.USER);
this.quill.insertEmbed(range.index + 1, 'divider', true, Quill.sources.USER);
this.quill.setSelection(range.index + 2, Quill.sources.SILENT);
}
}
}
}
});
const dividerButton = document.querySelector('.ql-divider');
if (dividerButton) {
dividerButton.innerHTML = '<svg viewBox="0 0 18 18"><line class="ql-stroke" x1="3" x2="15" y1="9" y2="9"></line></svg>';
}
quill.root.addEventListener('drop', e => {
e.preventDefault();
const files = e.dataTransfer.files;
if (files.length > 0) uploadImage(files[0]);
});
quill.root.addEventListener('paste', e => {
const items = e.clipboardData.items;
for (let i = 0; i < items.length; i++) {
if (items[i].type.indexOf('image') !== -1) {
e.preventDefault();
uploadImage(items[i].getAsFile());
}
}
});
function uploadImage(file) {
let fd = new FormData();
fd.append('image', file);
let range = quill.getSelection(true);
quill.insertText(range.index, 'Uploading image...', 'user');
fetch('upload_image.php', {
method: 'POST',
body: fd
})
.then(r => r.json())
.then(data => {
quill.deleteText(range.index, 18);
if (data.success) {
quill.insertEmbed(range.index, 'image', data.url, 'user');
showFeedback('Image uploaded successfully', 'success');
} else {
showFeedback('Upload failed: ' + data.message, 'danger');
}
})
.catch(err => {
quill.deleteText(range.index, 18);
showFeedback('Network error during upload', 'danger');
});
}
async function aiAction(action) {
let text = '';
let range = quill.getSelection();
if (action === 'continue') {
text = quill.getText(0, range ? range.index : quill.getLength());
} else {
if (!range || range.length === 0) {
showFeedback('Please select some text first.', 'warning');
return;
}
text = quill.getText(range.index, range.length);
}
if (!text.trim()) {
showFeedback('Not enough text to process.', 'warning');
return;
}
document.getElementById('ai-loading').style.display = 'inline-flex';
try {
const response = await fetch('ai_assistant.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
action,
text
})
});
const data = await response.json();
if (data.success) {
if (action === 'continue') {
let insertIndex = range ? range.index : quill.getLength();
quill.insertText(insertIndex, '\n' + data.text + '\n', 'user');
quill.setSelection(insertIndex + data.text.length + 2);
} else {
quill.deleteText(range.index, range.length, 'user');
quill.insertText(range.index, data.text, 'user');
quill.setSelection(range.index, data.text.length);
}
showFeedback('AI text generated successfully!', 'success');
} else {
showFeedback(data.message || 'AI generation failed', 'danger');
}
} catch (err) {
showFeedback('Network error calling AI', 'danger');
} finally {
document.getElementById('ai-loading').style.display = 'none';
}
}
async function aiGenerateAllSEO(btn) {
const text = quill.getText().trim();
const title = document.getElementById('title-input').value.trim() || 'Untitled';
if (!text || text.length < 50) {
showFeedback('Please write at least a few sentences of content first.', 'warning');
return;
}
const originalText = btn.innerText;
btn.innerText = ' Analyzing & Generating...';
btn.disabled = true;
try {
const response = await fetch('ai_assistant.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
action: 'generate_seo',
title: title,
text: text.substring(0, 5000)
})
});
const data = await response.json();
if (data.success) {
try {
//strip any accidental markdown blocks that Gemini might include despite instructions
let cleanJson = data.text.replace(/^```json/im, '').replace(/```$/m, '').trim();
const seoData = JSON.parse(cleanJson);
if (seoData.category) document.getElementById('seo_category').value = seoData.category;
if (seoData.tags) document.getElementById('seo_tags').value = seoData.tags;
if (seoData.excerpt) document.getElementById('seo_excerpt').value = seoData.excerpt;
if (seoData.meta_title) document.getElementById('meta_title').value = seoData.meta_title;
if (seoData.meta_description) document.getElementById('meta_description').value = seoData.meta_description;
if (seoData.keywords) document.getElementById('seo_keywords').value = seoData.keywords;
updateStats();
document.getElementById('save-status').innerText = 'Unsaved changes...';
document.getElementById('save-status').style.color = 'var(--text)';
showFeedback('SEO & Settings automatically filled!', 'success');
} catch (e) {
console.error("AI Output Parse Error: ", data.text);
showFeedback('AI returned an invalid format. Please try again.', 'danger');
}
} else {
showFeedback(data.message || 'Failed to generate SEO data', 'danger');
}
} catch (err) {
showFeedback('Network error calling AI', 'danger');
} finally {
btn.innerText = originalText;
btn.disabled = false;
}
}
quill.on('text-change', function(delta, oldDelta, source) {
updateStats();
document.getElementById('save-status').innerText = 'Unsaved changes...';
document.getElementById('save-status').style.color = 'var(--text)';
});
document.getElementById('title-input').addEventListener('input', () => {
document.getElementById('save-status').innerText = 'Unsaved changes...';
document.getElementById('save-status').style.color = 'var(--text)';
});
function updateStats() {
const text = quill.getText().trim();
const words = text.length > 0 ? text.split(/\s+/).length : 0;
document.getElementById('word-count').innerText = words + ' words';
const mt = document.getElementById('meta_title').value.length;
document.getElementById('mt-count').innerText = mt + '/60';
const md = document.getElementById('meta_description').value.length;
document.getElementById('md-count').innerText = md + '/160';
generateTOC();
}
updateStats();
function generateTOC() {
const tocContainer = document.getElementById('toc');
if (!tocContainer) return;
tocContainer.innerHTML = '';
const lines = quill.getLines();
let foundHeader = false;
lines.forEach((line, i) => {
if (typeof line.formats === 'function') {
const format = line.formats();
if (format && format.header) {
foundHeader = true;
const text = line.domNode.innerText;
if (text.trim() === '') return;
const li = document.createElement('li');
li.className = 'toc-h' + format.header;
if (!line.domNode.id) {
line.domNode.id = 'heading-' + i;
}
const a = document.createElement('a');
a.href = '#' + line.domNode.id;
a.innerText = text;
a.onclick = (e) => {
e.preventDefault();
document.getElementById('scroll-wrapper').scrollTo({
top: line.domNode.offsetTop - 100,
behavior: 'smooth'
});
}
li.appendChild(a);
tocContainer.appendChild(li);
}
}
});
if (!foundHeader) {
tocContainer.innerHTML = '<li style="color:var(--border);">No headings found.</li>';
}
}
['meta_title', 'meta_description'].forEach(id => {
document.getElementById(id).addEventListener('input', updateStats);
});
// Local Storage Fallback for Crash Recovery
const lsDraftKey = 'blog_draft_backup';
// Restore from Local Storage if available and no blog ID is set yet
window.addEventListener('DOMContentLoaded', () => {
const blogIdInput = document.querySelector('input[name="blog_id"]').value;
const savedDraft = localStorage.getItem(lsDraftKey);
if (!blogIdInput && savedDraft) {
try {
const draftData = JSON.parse(savedDraft);
if (draftData && (draftData.title || draftData.content)) {
if (confirm('An unsaved draft was found from a previous session. Do you want to restore it?')) {
if (draftData.title) document.getElementById('title-input').value = draftData.title;
if (draftData.content) quill.root.innerHTML = draftData.content;
updateStats();
showFeedback('Draft restored successfully', 'success');
} else {
localStorage.removeItem(lsDraftKey);
}
}
} catch (e) {
console.error("Could not parse draft data");
}
}
});
let lastSaveData = '';
function getFormData() {
const blogForm = document.getElementById('blog-form');
if (!blogForm) return '';
const fd = new FormData(blogForm);
fd.append('content', quill.root.innerHTML);
return new URLSearchParams(fd).toString();
}
lastSaveData = getFormData();
function autoSave() {
// 1. Save to Database
const currentData = getFormData();
if (currentData !== lastSaveData) {
saveBlog('draft', true);
}
// 2. Always persist current state to Local Storage just in case
const blogIdInput = document.querySelector('input[name="blog_id"]').value;
if (!blogIdInput) {
// We only buffer entirely new posts. Alternatively, you could key by blog_id.
localStorage.setItem(lsDraftKey, JSON.stringify({
title: document.getElementById('title-input').value,
content: quill.root.innerHTML
}));
}
}
setInterval(autoSave, 30000);
async function saveBlog(status, isAuto = false) {
if (!isAuto) {
document.getElementById('save-status').innerText = 'Saving...';
document.getElementById('save-status').style.color = 'var(--text)';
}
const blogForm = document.getElementById('blog-form');
const fd = new FormData(blogForm);
fd.append('content', quill.root.innerHTML);
fd.append('status', status);
if (!fd.get('excerpt') && quill.getText().trim().length > 0) {
fd.set('excerpt', quill.getText().trim().substring(0, 150) + '...');
}
try {
const res = await fetch('write.php', {
method: 'POST',
body: fd,
headers: {
'X-Requested-With': 'XMLHttpRequest'
}
});
const data = await res.json();
if (data.success) {
lastSaveData = getFormData();
document.querySelector('input[name="blog_id"]').value = data.blog_id;
// Clear LocalStorage backup, changes are safely in DB now
localStorage.removeItem(lsDraftKey);
if (!window.location.search.includes('id=')) {
window.history.replaceState({}, '', '?id=' + data.blog_id);
}
let text = isAuto ? 'Draft auto-saved' : 'Saved successfully';