File size: 31,020 Bytes
f127b6f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
<!DOCTYPE html>
<html>

<head>
    <title>Knowledge Base</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
    <!-- Include AdminLTE CSS -->
    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/adminlte.min.css">
    <!-- Include DataTables CSS -->
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.25/css/dataTables.bootstrap4.min.css">
    <!-- Include AdminLTE JS -->
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/adminlte.min.js"></script>
    <!-- Include DataTables JS -->
    <script src="https://cdn.datatables.net/1.10.25/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.10.25/js/dataTables.bootstrap4.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" />
    <style>

        body {

            background-color: transparent !important;

        } 

        .content-wrapper{

            flex: 1;

            overflow-y: auto;

        }



        .wrapper {

            display: flex;

            flex-direction: column;

            height: 100vh;

        }

    



        .modal-content {

            background-color: #fff;

        }



        .content-header {

            padding: 1rem;

        }

        

        h1 {

            text-align: center;

            margin-bottom: 30px;

        }



        .card {

            padding: 0;

            margin-top: -15px;

            margin-left: -40px;

        }



        .table-responsive {

            width: 100%;

            overflow-x: auto;

            /*overflow-y: scroll;*/

            /* Allows horizontal scrolling if necessary */

        }



        .table,

        .table-bordered {

            width: 100%;

            border-collapse: collapse;

            margin-right: 7.5px;

        }



       

        .text-wrap {

            white-space: normal !important;

            word-break: break-word;

        }

        div.dataTables_wrapper div.dataTables_length select{

            width: 60px;

            display: inline-block;

        }

       

        th {

            white-space: nowrap;

        }



        th:nth-child(1),

        td:nth-child(1) {

            /* Sno column */

            width: 2%;

        }



        th:nth-child(2),

        td:nth-child(2) {

            /* Document Name column */

            width: auto;

        }



        th:nth-child(3),

        td:nth-child(3) {

            /* Document Description column */

            width: auto;

        }



        th:nth-child(4),

        td:nth-child(4) {

            /* Document Version column */

            width: 20%;

        }



        th:nth-child(5),

        td:nth-child(5) {

            /* VectorDB Flag column */

            width: auto;

        }



        th:nth-child(6),

        td:nth-child(6) {

            /* View column */

            width: 10%;

        }



        th:nth-child(7),

        td:nth-child(7) {

            /* Edit column */

            width: 10%;

        }



        th:nth-child(8),

        td:nth-child(8) {

            /* Delete column */

            width: auto;

        }

      .alert {

    position: relative;

    padding: 15px;

    margin-bottom: 20px;

    border: 1px solid transparent;

    border-radius: 4px;

}



.alert-success {

    color: #3c763d;

    background-color: #dff0d8;

    border-color: #d6e9c6;

}



.alert-danger {

    color: #a94442;

    background-color: #f2dede;

    border-color: #ebccd1;

}



.close {

    position: absolute;

    bottom: 10px;

    right: 10px;

    border: none;

    background: none;

    font-size: 16px;

    cursor: pointer;

}



    </style>
</head>

<body>
    {% include 'sidepane.html' %}
    <div class="wrapper">
        <div class="main-header" style="border-bottom: none;">
            <div class="container mt-2">
                <div class="form-group left-align" >
                    <label for="company" class="mr-1" style="margin-left:-40px; margin-top: 12px;">Company Name <span class="text-danger">*</span></label>
                    <select type="text" id="company" name="company" class="form-control" style="width:20%;margin-left:-40px;"required>
                        <option value="" selected>Select</option>
                    </select>
                    <div class="col-12 d-flex justify-content-end mb-3">
                        <button class="btn btn-primary" style="margin-top:-40px;margin-right: -10px;position: fixed;"

                            id="add"  data-action="add">Add</button>
                    </div>
                </div>
            </div>
            <div class="row">
                <div id="message-container" style="margin-left: 200px;width:600px;"></div>
            </div>

            <section class="content" id="contentSection" style="display: none;">
                <div class="container-fluid">
                    <div>
                        <div class="form-group">
                            <!-- <label for="company_id">company_id</label>--->
                            <input type="hidden" id="company_id" name="company_id" class="form-control" required>
                        </div>
                        <div class="row">
                            <div class="col-12">
                                <div class="card">
                                    <div id="message-container">
                                        <div class="card-body table-container">
                                            <table id="knowledgeTable" class="table table-bordered table-striped">
                                                <thead>
                                                    <tr>
                                                    
                                                        <th>Sno</th>
                                                        <th>Document Name</th>
                                                        <th>Document Description</th>
                                                        <th>Document Version</th>
                                                        <th>VectorDB Flag</th>
                                                        <th>View</th>
                                                        <th>Edit</th>
                                                        <th>Delete</th>
                                                       <!-- <th style="display:none;">Company ID</th>  -->
                                                    </tr>
                                                </thead>
                                                <tbody>

                                                </tbody>
                                            </table>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
            </section>
        </div>
        
        <div class="modal fade" id="addModal" tabindex="-1" role="dialog" aria-labelledby="addModalLabel"

            aria-hidden="true">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="addModalLabel">Add Document Details</h5>
                        <button type="button" class="btn-close" data-dismiss="modal" >
                            <span aria-hidden="true" data-backdrop="static" data-keyboard="false"></span>
                        </button>
                    </div>
                    <div class="modal-body">
                        <div class="form-group">
                            <!-- <label for="company_id">company_id</label>--->
                            <input type="hidden" id="company_id" name="company_id" class="form-control" required>
                        </div>
                        <form id="documentForm">
                            <div class="form-group">
                                <label for="uploadFile">Upload File<span class="text-danger">*</span></label>
                                <span id="file-name"></span>
                                <input type="hidden" id="file_name" name="file_name" class="form-control" required>
                                <input type="file" class="form-control-file" id="uploadFile" name="uploadFile" required

                                    accept=".pdf,.doc,.docx">
                                <small class="form-text text-muted">Accepted formats: .pdf, .doc, .docx</small>
                            </div>
                            <div class="form-group">
                                <label for="documentName">Document Name<span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="documentName" name="documentName" required>
                            </div>
                            <div class="form-group">
                                <label for="documentDescription">Document Description<span

                                        class="text-danger">*</span></label>
                                <textarea class="form-control" id="documentDescription" name="documentDescription"

                                    rows="3" required></textarea>
                            </div>
                            <div class="form-group">
                                <label for="department">Department<span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="department" name="department" required>
                            </div>
                            <div class="form-group">
                                <label for="version">Version<span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="version" name="version" required>
                            </div>
                            <div class="form-group">
                                <label for="lastUpdated">Last Updated<span class="text-danger">*</span></label>
                                <input type="text" class="form-control" id="lastUpdated" name="lastUpdated" required>
                            </div>
                        </form>
                    </div>
                    <div class="modal-footer">
                        <!-- <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> -->
                        <button type="button" id="saveupdate"  class="btn btn-primary" style="display: none;">Update</button>
                        <button type="button" id="save" onclick="save_file()" class="btn btn-primary">Save</button>
                    </div>
                </div>
            </div>
        </div>
    </div>

        {%include 'footer.html'%}
    
    <!-- JavaScript to handle modal display -->
    <script>

        document.addEventListener("DOMContentLoaded", function () {

            now = new Date().toISOString().replace('T', ' ').substr(0, 19);

            document.getElementById('lastUpdated').value = now;

            const inputs = document.querySelectorAll("#documentForm input, textarea");



            inputs.forEach((input, index) => {

                input.addEventListener("keydown", function (event) {

                    if (event.key === "Enter") {

                        event.preventDefault();

                        moveToNextInput(inputs, index);

                    }

                });

            });



            function moveToNextInput(inputs, currentIndex) {

                const nextInput = inputs[currentIndex + 1];

                if (nextInput) {

                    nextInput.focus();

                } else {

                    // Optionally, submit the form or trigger the save button

                    document.getElementById("save").focus();

                }

            }

//             $(document).on('click', '.btn-view', function () {

//                 const companyId = $(this).data('id');

//                 console.log("company_id in view",companyId);

//                 viewCompany(companyId);

//             });



//             // Edit company details

//             $(document).on('click', '.btn-edit', function () {

//                 const companyId = $(this).data('id');

//                 console.log("company_id in edit",companyId);

//                 editCompany(companyId);

//             });



//             // Delete company

//             $(document).on('click', '.btn-delete', function () {

//              const kid = $(this).data('id'); // Get the company ID from the da     

//              console.log("company_id in delete",kid);

//              if (confirm("Are you sure you want to delete this company?")) {

//                       deleteCompany(kid); // Call the delete function with the company ID

//     }

// });

            fetchCompanies();



            const companySelect = document.getElementById('company');

            const documentForm = document.getElementById('documentForm');

            const table = $('#knowledgeTable').DataTable(); // Initialize DataTable at the start



            companySelect.addEventListener('change', async function () {

                $("#message-container").empty();

                const selectedCompanyName = companySelect.options[companySelect.selectedIndex].text;

                console.log(`Selected Company Name: ${selectedCompanyName}`);



                if (selectedCompanyName !== "Select") {

                    try {

                        const response = await fetch(`/api/company_id?company_name=${encodeURIComponent(selectedCompanyName)}`);

                        if (!response.ok) {

                            contentSection.style.display = 'none';

                            displayErrorMessage("Document details do not exist for this company. Please fill in the details.");

                            throw new Error('Network response was not ok');

                        }

                        const data = await response.json();

                        console.log('data returned', data);

                        const companyId = data.company_id;

                        document.getElementById('company_id').value = companyId;



                        if (companyId) {

                            try {

                                const Response = await fetch(`/api/document_upload?company_id=${companyId}&company_name=${selectedCompanyName}`);

                                const connectorsResponse = await Response.json();

                                console.log("knowledge data table after connecting to table", connectorsResponse);

                                table.clear();

                                if (!Array.isArray(connectorsResponse) || connectorsResponse.length === 0) {

                                    //displayEmptyTable();



                                    displayErrorMessage("Document details do not exist for this company. Please fill in the details.");

                                    contentSection.style.display = 'none';

                                } else {



                                    connectorsResponse.forEach((company, index) => {

                                        table.row.add([

                                           

                                            index + 1,

                                            company.document_name,

                                            company.document_desc,

                                            company.version,

                                            company.vectorDBflag,

                                            `<a href='#' class='btn btn-info btn-sm'data-kid-id='${company.row_id}' data-action="view" onclick='viewCompany(this)''><i class='fas fa-eye'></i></a>`,

                                            `<a href='#' class='btn btn-warning btn-sm'data-kid-id='${company.row_id}' data-action="edit" onclick='editCompany(this)'><i class='fas fa-edit'></i></a>`,

                                            //`<a href='#' class='btn btn-danger btn-sm' onclick='deleteCompany(${company.company_id})'><i class='fas fa-trash'></i></a>`,

                                            `<a href='#' class='btn btn-danger btn-sm' data-kid-id='${company.row_id}' onclick='deleteCompany(this)'><i class='fas fa-trash'></i></a>`,

                                            company.row_id

                                            // "<a href='#' class='btn btn-info btn-sm'><i class='fas fa-eye'></i></a>",

                                            // "<a href='#' class='btn btn-warning btn-sm'><i class='fas fa-edit'></i></a>",

                                            // "<a href='#' class='btn btn-danger btn-sm'><i class='fas fa-trash'></i></button>"

                                        ]).draw(false);

                                    });

                                    contentSection.style.display = 'block';

                                }

                            } catch (error) {

                                console.error('Error fetching company documents:', error);

                                //displayEmptyTable();



                                displayErrorMessage("Document details1 do not exist for this company. Please fill in the details.");

                                contentSection.style.display = 'none';

                            }

                        } else {

                            // displayEmptyTable();



                            displayErrorMessage("Document details2 for knowledge do not exist for this company. Please fill in the details.");

                        }

                    } catch (error) {

                        console.error('No details for this company ID or data documents:', error);

                        // displayEmptyTable();



                        displayErrorMessage("Document details3 do not exist for this company. Please fill in the details.");

                        contentSection.style.display = 'none';

                    }

                } else {

                    table.clear().draw();

                    document.getElementById('contentSection').style.display = 'none';

                    clearFormFields();

                }

            });



            function displayErrorMessage(message) {

                const messageContainer = document.getElementById('message-container');

                if (messageContainer) {

                    messageContainer.innerHTML = `<div class='alert alert-danger'>${message}</div>`;

                }

            }

           

        });



        function clearFormFields() {

            document.getElementById('file-name').textContent=""

            document.getElementById('uploadFile').value = "";

            document.getElementById('documentName').value = "";

            document.getElementById('documentDescription').value = "";

            document.getElementById('department').value = "";

            document.getElementById('version').value = "";

            //document.getElementById('lastUpdated').value = "";

        }





        $(document).ready(function () {

            // Show modal function

            $('#add').on('click', function () {

                const modalTitle = document.getElementById('addModalLabel');

                modalTitle.textContent = 'Add Document Details';

                $('#uploadFile').show();

                $('#saveupdate').hide();

                clearFormFields();

                $('#message-container').empty(); // Clear the message container

                $('#addModal').modal('show');

            });





            $('.modal-footer .btn-secondary, .modal-header .btn-close').on('click', function () {

                $('#addModal').modal('hide');

            });

            $('#KnowledgeTable').DataTable({

                autoWidth: false

            });



        });

        function viewCompany(button) {

            var companyId = $(button).data('kid-id');

            const modalTitle = document.getElementById('addModalLabel');

            modalTitle.textContent = 'View Document Details';

            $.getJSON(`/api/getknowledgebase/${companyId}`, function (company) {

                $('#uploadFile').hide();

                $('#file-name').text(company.file_path).attr('readonly','readonly');

                $('#documentName').val(company.document_name).attr('readonly', 'readonly');

                $('#documentDescription').val(company.document_desc).attr('readonly', 'readonly');

                $('#department').val(company.department).attr('readonly', 'readonly');

                $('#version').val(company.version).attr('readonly', 'readonly');

                //$('#lastUpdated').val(company.last_updated).attr('readonly', 'readonly');

                var lastUpdated = company.last_updated;

                $('#lastUpdated').val(lastUpdated).attr('readonly', 'readonly');

                $('#save').hide();// Disable the "Save" button when the modal opens

                $('#addModal').modal('show');

            }).fail(function () {

                alert("Error retrieving company details.");

            });

        }



        // Edit company details

        function editCompany(button) {

            var companyId = $(button).data('kid-id');

            const modalTitle = document.getElementById('addModalLabel');

            modalTitle.textContent = 'Edit Document Details';

            // Fetch company details by ID

            $.getJSON(`/api/getknowledgebase/${companyId}`, function (company) {

                $('#uploadFile').hide();

                $('#file-name').text(company.file_path).attr('readonly','readonly');

                $('#documentName').removeAttr('readonly');

                $('#documentDescription').removeAttr('readonly');

                $('#department').removeAttr('readonly');

                $('#version').removeAttr('readonly');

                $('#lastUpdated').removeAttr('readonly');

              //  $('#vectorDBflag').removeAttr('readonly');

                $('#company_id').removeAttr('readonly');

                $('#save').hide();

                $('#saveupdate').show();

                // Populate the form with the company's details

                $('#uploadFile').hide();

                $('#file_name').val(company.file_path);

                $('#file-name').val(company.file_path);

                $('#documentName').val(company.document_name);

                $('#documentDescription').val(company.document_desc);

                $('#department').val(company.department);

                $('#version').val(company.version);

                $('#lastUpdated').val(company.last_updated);

                $('#company_id').val(company.company_id);

                $('#addModal').modal('show');

                $('saveupdate').show();

                // Update the save button to save the edited company

                $('#saveupdate').off('click').on('click', function () {

                 

                   saveupdate(companyId); // Pass the company ID for updating

                });

           }).fail(function () {

                alert("Error retrieving company details.");

            });

        }



        // Delete company

        function deleteCompany(button) {

            var companyId = $(button).data('kid-id');

            console.log("k_id deleted",companyId);

            $.ajax({

                type: "DELETE",

                url: `/api/delknowledgebase/${companyId}`,

                success: function () {

                    var table = $('#knowledgeTable').DataTable();

                    table.row($(button).closest('tr')).remove().draw();

                 

                    alert("Company deleted successfully.");

                    fetchCompanies(); // Refresh the table

                },

                error: function (xhr) {

                    alert("Error deleting company: " + xhr.responseJSON.detail);

                }

            });

        }

        function saveupdate(companyId) {

    console.log("k_id", companyId);



    var fileInput = document.getElementById('uploadFile'); // Assuming an input element for file upload

   // var filePath = $('#file-name').text();

   // console.log("k_id path", filePath);

    var formData = new FormData();

    formData.append('company_id', $('#company_id').val());

    formData.append('file_name', $('#file_name').val());

    formData.append('uploadFile', fileInput.files[0]); // Assuming a file input for upload

    formData.append('documentName', $('#documentName').val());

    formData.append('documentDescription', $('#documentDescription').val());

    formData.append('department', $('#department').val());

    formData.append('version', $('#version').val());

    formData.append('vectorDBFlag', "NO");

    formData.append('lastUpdated', $('#lastUpdated').val());



    $.ajax({

        url: `/api/putknowledgebase/${companyId}`,

        type: 'PUT',

        data: formData,

        processData: false, // Required for FormData

        contentType: false, // Required for FormData

        success: function (response) {

            alert('Knowledgebase details updated successfully.');

            $('#addModal').modal('hide'); // Close the modal after saving

            fetchCompanies();

        },

        error: function () {

            alert('Failed to update company details.');

        }

    });

}



        function save_file() {

            const form = document.getElementById('documentForm');



            // Check if the form is valid

            if (!form.checkValidity()) {

                // If the form is invalid, show validation messages and stop the submission

                form.reportValidity();

                return;

            }

            const uploadFile = document.getElementById("uploadFile").files[0];

            const documentName = document.getElementById("documentName").value;

            const documentDescription = document.getElementById("documentDescription").value;

            const department = document.getElementById("department").value;

            const version = document.getElementById("version").value;

            const lastUpdated = document.getElementById("lastUpdated").value;

            const company_id = document.getElementById("company_id").value;



            //const formData = new FormData();

            var formData = new FormData($('#documentForm')[0]);

            const vectorDBFlag = "NO"; // Example value

            const view = "<a href='#' class='btn btn-info btn-sm'><i class='fas fa-eye'></i></a>";

            const edit = "<a href='#' class='btn btn-warning btn-sm'><i class='fas fa-edit'></i></a>";

            const dele= "<a href='#' class='btn btn-danger btn-sm'><i class='fas fa-trash'></i></a>";





            formData.append("uploadFile", uploadFile);

            formData.append("documentName", documentName);

            formData.append("documentDescription", documentDescription);

            formData.append("department", department);

            formData.append("version", version);

            formData.append("lastUpdated", lastUpdated);

            formData.append("vectorDBflag", vectorDBFlag);

            formData.append("company_id", company_id);



            fetch('/upload_document', {

                method: 'POST',

                body: formData

            })

                .then(response => {

                    if (!response.ok) {

                        throw new Error('Network response was not ok');

                    }

                    return response.text();

                })

                .then(data => {

                    var table = $('#knowledgeTable').DataTable();

                    var rowCount = table.rows().count();

                    table.row.add([

                        rowCount + 1,

                        documentName,

                        documentDescription,

                        version,

                        vectorDBFlag,

                        view,

                        edit,

                        dele

                    ]).draw(false);

                

                    const messageContainer = document.getElementById('message-container');

                        if(messageContainer)

                        messageContainer.innerHTML = `

                <div class='alert alert-success'>

                    Data saved successfully

                    <button class='close' onclick='dismissMessage()'>OK</button>

                </div>`;

                   // alert('Document saved successfully');

                    $('#addModal').modal('hide');

                    document.getElementById('contentSection').style.display = 'block'; // Show the table section

                })

                .catch(error => console.error('Error:', error));

        }

        function dismissMessage() {

    const messageContainer = document.getElementById('message-container');

    if (messageContainer) {

        messageContainer.innerHTML = '';

    }

}

        async function fetchCompanies() {

            try {

                const response = await fetch('/api/companies');

                if (!response.ok) {

                    throw new Error('Network response was not ok');

                }

                const data = await response.json();

                displayCompanies(data.companies);

            } catch (error) {

                console.error('Error fetching companies:', error);

            }

        }



        function displayCompanies(companies) {

            const companySelect = document.getElementById('company');

            companySelect.innerHTML = '<option value="" selected>Select</option>'; // Reset the dropdown

            companies.forEach(company => {

                const option = document.createElement('option');

                option.value = company.name;

                option.textContent = company.name;

                companySelect.appendChild(option);

            });

        }

    </script>
</body>

</html>