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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Company Profile</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">
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css" rel="stylesheet" />
    <link href="https://cdn.jsdelivr.net/npm/@ttskch/[email protected]/dist/select2-bootstrap4.min.css"

        rel="stylesheet" />
    <link rel="stylesheet" href="/static/css/company_profile.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" />
   
</head>
<style>

    #add{

       position: absolute;

       right: 0%;

    }

    #companyTable_filter{

       margin-right: 70px;

       margin-top: -25px;

    }

</style>

<body>
    {% include 'sidepane.html' %}

    <div class="wrapper">
        <div class="content-wrapper">
            <!-- Content Header (Page header) -->
            <div class="content-header">
                <div class="container-fluid">
                    <div class="row mb-2">
                        <!-- <div class="col-12">

                            <div class="col-12 d-flex justify-content-end mb-3">

                                <button class="btn btn-primary" style="margin-bottom:-30px;position:fixed"               id="add">Add</button>

                            </div>

                        </div> -->
                        <input type="hidden" id="userRole" name="userRole" value={{role}}>
                        <div class="row">
                            <div id="message-container" style="margin-left: 200px;width:600px;"></div>
                        </div>
                    </div>
                </div>
            </div>
            <!-- Main content -->
            <section class="content" id="startTable" style="display: none;">

                <div class="row">
                    <div class="col-12">
                        <div class="card">
                            <div class="card-body table-container">
                                <div class="dataTables_wrapper">
                                    <div class="row">
                                        <button class="btn btn-primary me-3" id="add">Add</button>
                                        <div class="dataTables_length">
                                            <label

                                                style="display: inline-block;margin-right:800px; margin-bottom: -40px;">Show
                                                entries:
                                                <div class="custom-dropdown">
                                                    <button class="dropdown-button">5</button>
                                                    <div class="dropdown-content">
                                                        <a href="#" data-length="5">5</a>
                                                        <a href="#" data-length="10">10</a>
                                                        <a href="#" data-length="50">50</a>
                                                        <a href="#" data-length="100">100</a>
                                                    </div>
                                                </div>
                                            </label>
                                        </div>
                                        <table id="companyTable"

                                            class="table display mb-4 dataTablesCard dataTable table-responsive-xl card-table">
                                            <thead>
                                                <tr>
                                                    <th>Sno</th>
                                                    <th>Company Name</th>
                                                    <th>Company code</th>
                                                    <th>Domain</th>
                                                    <th>LLM Tools</th>
                                                    <th>View</th>
                                                    <th>Edit</th>
                                                    <th>Delete</th>
                                                </tr>
                                            </thead>

                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
            </section>
        </div>
    </div>
    <!-- Modal -->
    <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 Company Profile</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true" data-backdrop="static" data-keyboard="false">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form id="companyForm">
                        <div class="form-group">
                            <label for="companyName">Company Name<span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="company_name" name="company_name" required>
                        </div>
                        <div class="form-group">
                            <label for="companyCode">Company Code<span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="company_code" name="company_code" required>
                        </div>
                        <div class="form-group">
                            <label for="domain">Domain<span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="domain" name="domain" required>
                        </div>
                        <div class="form-group">
                            <label for="llm_tools">LLM Tools<span class="text-danger">*</span></label>
                            <select class="form-select" id="llm_tools" name="llm_tools[]" multiple required>
                                <option value="Database">Database</option>
                                <option value="Static Documents">Static Documents</option>
                                <option value="API">API</option>
                            </select>

                            <div class="invalid-feedback">
                                Please select at least one LLM tool.
                            </div>
                        </div>

                        <div class="form-group">
                            <label for="domain">UserName<span class="text-danger">*</span></label>
                            <input type="text" class="form-control" id="username" name="username" required>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" id="saveupdate" class="btn btn-primary" style="display: none;">Update</button>
                    <button type="button" id="save" onclick="saveProfile()" class="btn btn-primary">Save</button>
                </div>
            </div>
        </div>
    </div>
    {%include 'footer.html'%}
    <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>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>
    <script>

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



            const role = sessionStorage.getItem('userRole');

            const company_id = sessionStorage.getItem('company_id');

            console.log('Current role:', role); // Debug statement to check the role

            document.getElementById('userRole').value = role;

            const passedCompanyName = sessionStorage.getItem('company_name')

            document.getElementById('selectedCompany').innerText = `Company Name: ${passedCompanyName}`;

            $('#addModal').hide();  // Make sure this is called initially

            function checkForAddButton() {

                const addButton = document.getElementById('add');



                if (addButton) {

                    // Stop checking once the element is found

                    clearInterval(checkInterval);

                    if (role === 'superadmin') {

                        console.log("insidse compamy profile super admin");



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

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

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





                    } else {

                        console.log("insidse company profile admin");

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

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

                        modalTitle.textContent = 'Company Details';

                        viewCompany(company_id);

                    }

                }

            }

            const checkInterval = setInterval(checkForAddButton, 100); //

            document.querySelector('.dropdown-button').addEventListener('click', function () {

                const dropdownContent = document.querySelector('.dropdown-content');

                dropdownContent.style.display = dropdownContent.style.display === 'block' ? 'none' : 'block';

            });

            fetchCompanies();

        });

        window.addEventListener('click', function (event) {

            if (!event.target.matches('.dropdown-button')) {

                const dropdownContents = document.querySelectorAll('.dropdown-content');

                dropdownContents.forEach(function (content) {

                    content.style.display = 'none';

                });

            }

        });

        window.addEventListener('pageshow', function (event) {

            if (event.persisted || (window.performance && window.performance.navigation.type === 2)) {

                window.location.reload();

            }

        });





        $(document).ready(function () {

            // Initialize DataTable

            //$('#companyTable').DataTable();

            $('#companyTable').DataTable({



                "paging": true,

                "pageLength": 5,

                "lengthChange": false,

                "searching": true,

                "ordering": true,

                "info": true,

                "autoWidth": false,

                "responsive": true

            });



            // Initialize Select2

            $('select').select2({

                theme: 'bootstrap4',

                placeholder: 'Select',

                allowClear: true,

                dropdownParent: $('#addModal')

            });



            // Show modal function

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

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

                modalTitle.textContent = 'Add Company Details';

                console.log('Modal title after setting:', modalTitle.textContent); // This should log the new title

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

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

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

                $('select').prop('disabled', false);

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

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

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

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





                clearmodal();

                $('#save').prop('disabled', false); // Disable the "Save" button when the modal opens

            });

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

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

            });

            $('#addModal').on('shown.bs.modal', function () {

                $('#companyTable').DataTable().columns.adjust().draw();

                // Initialize Select2 only if not already initialized

                if (!$('#llm_tools').hasClass('select2-hidden-accessible')) {

                    $('select').select2({

                        theme: 'bootstrap4',

                        placeholder: 'Select LLM Tools',

                        allowClear: true,

                        dropdownParent: $('#addModal')

                    });

                }

            });



            $(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);

                if (companyId) {

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

                    modalTitle.textContent = 'Edit Company Details';

                    console.log('Modal title:', modalTitle.textContent);



                    Editcompany(companyId);

                }

            });



            // Delete company

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

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

                console.log("company_id in delete", companyId);

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

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

                }

            });

        });

        // View company details

        function viewCompany(companyId) {

            const username = sessionStorage.getItem('username');

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

            modalTitle.textContent = 'View Company Details';



            // Fetch company details by ID

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

                console.log("Fetched company details:", company);



                // Set the company fields to readonly

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

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

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

                $('select').val(company.llm_tools.split(',')).trigger('change');

                $('select').prop('disabled', true);

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



                // Show the modal

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

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

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

            }).fail(function () {

                console.error("Error retrieving company details.");

            });

        }

        // Edit company details

        function Editcompany(companyId) {



            const username = sessionStorage.getItem('username');

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

            modalTitle.textContent = 'Edit Company Details';

            console.log('Modal title after setting:', modalTitle.textContent); // Should log "Edit Company Details"

            // Fetch company details by ID

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

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

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

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

                $('select').prop('disabled', false);

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

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

                // Populate the form with the company's details

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

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

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

                $('select').val(company.llm_tools.split(',')).trigger('change');

                $('#username').val(username).attr('readonly', 'readonly');// Disable the select input



                //sessionStorage.setItem('llmTools', company.llm_tools); // Store as a string

                $('#addModal').modal('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(companyId) {

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

            $.ajax({

                type: "DELETE",

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

                success: function () {

                    //  alert("Company deleted successfully.");

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

                    if (messageContainer)

                        messageContainer.innerHTML = `

                <div class='alert alert-danger'>

                   Company details deleted successfully.

                    <button class='close' style='font-size:medium;margin-top:6px;'  onclick='dismissMessage()'>OK</button>

                </div>`;

                    fetchCompanies(); // Refresh the table

                },

                error: function (xhr) {

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

                }

            });

        }

        function saveupdate(companyId) {

            console.log("company_id", companyId);

            const llm_tools = $('#llm_tools').select2("val");

            var formData = new FormData();

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

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

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

            formData.append('llm_tools', llm_tools); // Assuming llm_tools is a multi-select



            console.log("company_data", formData);



            $.ajax({

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

                type: 'PUT',

                data: formData,

                processData: false,  // Important for FormData

                contentType: false,

                success: function (response) {

                    // alert('Company details updated successfully.');

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

                    if (messageContainer)

                        messageContainer.innerHTML = `

                <div class='alert alert-success'>

                   Company  Data Updated successfully

                    <button class='close' style='font-size:medium;margin-top:6px;' onclick='dismissMessage()'>OK</button>

                </div>`;

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

                    fetchCompanies();

                },

                error: function () {



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

                    if (messageContainer)

                        messageContainer.innerHTML = `

                <div class='alert alert-danger'>

                  No changes have been made  to update company details.

                    <button class='close' style='font-size:medium;margin-top:6px;' onclick='dismissMessage()'>OK</button>

                </div>`;

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

                    //alert('No changes have been made  to update company details.');

                }

            });

        }



        function saveProfile() {

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



            // Check if the form is valid

            if (!form.checkValidity()) {

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

                form.reportValidity();

                return;

            }



            // Gather form data

            const company_name = document.getElementById('company_name').value;

            const company_code = document.getElementById('company_code').value;

            const domain = document.getElementById('domain').value;

            const llm_tools = $('#llm_tools').select2("val");

            console.log("Selected LLM Tools:", llm_tools);

            // console.log("llm_tools element:", document.getElementById('llm_tools'));

            const username = $('#username').val();





            // Prepare FormData

            let formData = new FormData();

            const password = "password";

            const rolesave = "admin";

            formData.append("company_name", company_name);

            formData.append("company_code", company_code);

            formData.append("domain", domain);

            formData.append("llm_tools", llm_tools);

            formData.append("username", username);

            formData.append("password", password);

            formData.append("role", rolesave);



            $.ajax({

                type: "POST",

                url: "/submit_company_profile",

                data: formData,

                processData: false,

                contentType: false,

                success: function (response) {

                    // alert("Data saved successfully"); // Show success message

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

                    if (messageContainer)

                        messageContainer.innerHTML = `

                <div class='alert alert-success'>

                    Data saved successfully

                    <button class='close' style='font-size:medium;margin-top:6px;' onclick='dismissMessage()'>OK</button>

                </div>`;

                    fetchCompanies(); // Refresh table data



                    // Clear the form and close the modal

                    // $('#companyForm')[0].reset();

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

                },

                error: function (xhr) {

                    alert("An error occurred: " + xhr.responseJSON.detail); // Show error message

                }

            });

        }

        function dismissMessage() {

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

            if (messageContainer) {

                messageContainer.innerHTML = '';

            }

        }

        async function fetchCompanies() {

            try {

                console.log("Fetching companies...");

                const response = await fetch(`/api/companydetails`);

                const companies = await response.json();

                console.log(companies); // Inspect the data here



                if (!Array.isArray(companies)) {

                    throw new TypeError('Expected an array of companies');

                }



                const table = $('#companyTable').DataTable();

                table.clear(); // Clear existing table data



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

                    table.row.add([

                        index + 1,

                        company.company_name,

                        company.company_code,

                        company.domain,

                        company.llm_tools, // Join array of tools into a string

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

                        `<a href='#' class='btn btn-warning btn-sm'onclick='Editcompany(${company.company_id})'><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>`



                    ])

                }); table.draw(false);

            } catch (error) {

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

            }

        }

        function clearmodal() {

            $('#companyForm')[0].reset();  // Reset all form fields

            $('#llm_tools').val(null).trigger('change');  // Clear and reset the Select2 field without reinitializing

        }



        document.querySelectorAll('.dropdown-content a').forEach(function (item) {

            item.addEventListener('click', function () {

                const length = item.getAttribute('data-length');

                // Set the DataTable page length

                $('#companyTable').DataTable().page.len(parseInt(length)).draw();

                document.querySelector('.dropdown-button').textContent = length;

            });

        });





    </script>
</body>

</html>