<?php 
if(file_exists('../../../'.$_REQUEST['tenant'].'/config.php')){require_once('../../../'.$_REQUEST['tenant'].'/config.php');}
if(file_exists('/config.php')){require_once('/config.php');}
?>

<style>
.dt-buttons {
    display: none !important
}
</style>
<div class="row">
    <p class="lead">Register New Global System Administrator</p>
</div>
<div class="row alert-info mb-5 p-2 pb-0">

    <div class="col-12">
        <table class="table table-striped table-sm table-hover table-responsive rounded" width="100%">
            <thead class="bg-primary text-white">
                <tr>
                    <th>Name</th>
                    <th>Phone</th>
                    <th>Email</th>
                    <th>Password</th>
                    <th>Permissions</th>
                    <th class="no-sort noExport"></th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <form id="Fnew">
                        <td><input type="text" name="name" class="form-control" value="" required></td>
                        <td><input type="tel" name="tel" class="form-control" value="" required></td>
                        <td><input type="email" name="email" class="form-control" value="" required></td>
                        <td><input type="text" name="password" class="form-control" value="" required></td>
                        <td>
                            <div class="form-check form-check-inline">
                                <input class="form-check-input" type="radio" name="permissions" id="standard" value="1" checked>
                                <label class="form-check-label" for="standard">Standard</label>
                            </div>
                            <div class="form-check form-check-inline">
                                <input class="form-check-input" type="radio" name="permissions" id="super" value="999">
                                <label class="form-check-label" for="super">Super</label>
                            </div>
                        </td>
                        <td class="text-center">
                            <div class="btn-group" role="group">
                                <input type="hidden" name="FCN" value="new">
                                <input type="hidden" name="tenant" value="<?= TENANT_URL?>">
                                <a href="javascript:void(0)" onclick="create()" class="btn btn-success me-4"><i class="fad fa-save text-light"></i> Register</a>
                            </div>
                        </td>
                    </form>
                </tr>
            </tbody>
        </table>
    </div>
</div>
<div class="note note-secondary mb-3">
    <strong>Permissions:</strong> <i><b>Standard</b></i> users can only access the clients assigned to them, whereas Super is intended as the owners account. <i><b>Super</b></i> has access to all administrative features and no limitation on
    access.
</div>
<div id="exportTitle" style="display: none">EnRep: System Admins <small>Generated: <?= date('d-m-Y')?></small></div>
<p class="lead">Registered Administrators</p>
<table id="datatable" class="table table-striped table-sm table-bordered table-hover responsive nowrap" width="100%">
    <thead>
        <tr>
            <th>Name</th>
            <th>Phone</th>
            <th>Email</th>
            <th>Password</th>
            <th>Permissions</th>
            <th class="no-sort noExport"></th>
        </tr>
    </thead>
    <tbody>
        <?php $idList=[];
$cc=mysqli_query($GLOBALS['con'],"SELECT * FROM `admins` ")or die(mysqli_error($GLOBALS['con']));
while($cd=mysqli_fetch_array($cc)){
$stmt2 = $GLOBALS['con']->prepare("SELECT AES_DECRYPT(password,email) AS pass FROM `admins` WHERE `id`=?")or die(mysqli_error($GLOBALS['con']));
$stmt2->bind_param('i',$cd['id']);$stmt2->execute();$p=$stmt2->get_result();$stmt2->close();
$data=mysqli_fetch_array($p);
$idList[]=$cd['id'];
$cd['password']=$data['pass'];
?>
        <tr>

            <td><input type="text" name="name" class="form-control" value="<?= $cd['name']?>" form="F<?= $cd['id']?>"></td>
            <td><input type="tel" name="tel" class="form-control" value="<?= $cd['tel']?>" form="F<?= $cd['id']?>"></td>
            <td><input type="email" name="email" class="form-control" value="<?= $cd['email']?>" form="F<?= $cd['id']?>"></td>
            <td><input type="text" name="password" class="form-control" value="<?= $cd['password']?>" form="F<?= $cd['id']?>"></td>
            <td>
                <div class="form-check form-check-inline">
                    <input class="form-check-input" type="radio" name="permissions<?= $cd['id']?>" id="standard<?= $cd['id']?>" value="1" <?php if($cd['access']==1){?>checked<?php }?> form="F<?= $cd['id']?>">
                    <label class="form-check-label" for="standard<?= $cd['id']?>">Standard</label>
                </div>
                <div class="form-check form-check-inline">
                    <input class="form-check-input" type="radio" name="permissions<?= $cd['id']?>" id="super<?= $cd['id']?>" value="999" <?php if($cd['access']==999){?>checked<?php }?> form="F<?= $cd['id']?>">
                    <label class="form-check-label" for="super<?= $cd['id']?>">Super</label>
                </div>
            </td>

            <td class="text-center">
                <a href="javascript:void(0)" onclick="openAccessModal('<?= $cd['id']?>')" class="btn btn-info noprint me-4 text-light"><i class="fad fa-cogs"></i> Set Access</a>
                <a href="javascript:void(0)" onclick="save('F<?= $cd['id']?>')" class="btn btn-secondary noprint me-4 text-light"><i class="fad fa-save"></i></a>
                <a href="javascript:void(0)" onclick="remove('<?= $cd['id']?>')" class="btn btn-danger noprint text-light"><i class="fad fa-trash"></i></a>
                <input type="hidden" name="FCN" value="update" form="F<?= $cd['id']?>">
                <input type="hidden" name="id" value="<?= $cd['id']?>" form="F<?= $cd['id']?>">
                <input type="hidden" name="tenant" value="<?= TENANT_URL?>" form="F<?= $cd['id']?>">
            </td>

        </tr>
        <?php }?>
    </tbody>
</table>

<?php
 $table="datatable";
 $dateTarget="8";
 $sortTarget="1";
 $length="25";
 $sortCell="nth-child(2)";
 $logo="yes";
 $scroller="";
require_once(ROOT_URL.'/includes/tables/single_table.php');?>
<?php foreach($idList as $id){
echo '<form id="F'.$id.'"></form>';
} ?>

<script>
function create() {
    const formData = new FormData(document.getElementById('Fnew'));
    fetch(ROOT_URL + '/includes/admin/admin_functions.php', {
            method: 'POST',
            body: formData
        }).then(response => response.text())
        .then(result => {

            if (result.trim() === "success") {
                showResponse('success', 'Your changes have been saved successfully');
                window.location.href = 'index.php?t=includes/master&p=admin.php&view=list';
            }
        }).catch(error => {
            console.error('Error:', error);
        });
}

function save(formId) {
    // Ensure that formId is correctly referencing the form element
    const form = document.getElementById(formId);

    if (form) {
        const formData = new FormData(form); // This will work if 'form' is a valid HTMLFormElement

        fetch(ROOT_URL + '/includes/admin/admin_functions.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.text())
            .then(result => {
                debug(result)
                if (result.trim() === "success") {
                    showResponse('success', 'Your changes have been saved successfully');
                    window.location.href = 'index.php?t=includes/master&p=admin.php&view=list';
                } else {
                    showResponse('danger', 'There was an error saving the data');
                }
            })
            .catch(error => {
                console.error('Error:', error);
            });
    } else {
        console.error('Form not found: ', formId);
    }
}


function remove(id) {
    var dest = '<p>Are you sure you wish to remove this administrator?</p>';
    loadModalContent(dest, "popupBox", "modal-lg", 1060, "true", "Administrator Removal", "cancelConfirm", () => removeConfirm(id));
}

function removeConfirm(id) {
    fetch(ROOT_URL + '/includes/admin/admin_functions.php', {
            method: 'POST',
            body: new URLSearchParams({
                FCN: 'remove',
                id: id,
                tenant: TENANT_URL
            })
        }).then(response => response.text())
        .then(result => {
            if (result.trim() === "success") {
                showResponse('success', 'Administrator removed successfully');
                window.location.href = 'index.php?t=includes/master&p=admin.php&view=list';
            }
        }).catch(error => {
            console.error('Error:', error);
        });
}

// Declare selectedClients outside the functions so it is available globally
var selectedClients = new Set();

function openAccessModal(adminId) {
    var dest = `
    <div class="note note-warning mb-3">
        <strong>Granting Access:</strong> Here you can decide precisely which clients your administrators have access to. All <b>Standard</b> administrator accounts require access to be given.
    </div>
    <form id="accessForm">
        <div class="input-group mb-3">
            <!-- Search input with clear button -->
            <input type="text" id="searchClient" class="form-control" placeholder="Search Clients...">
            <button class="btn btn-outline-secondary" type="button" id="clearSearch">
                <i class="fad fa-trash-undo"></i> <!-- MDB Icon for clear -->
            </button>
            <button class="btn btn-outline-secondary" type="button" id="selectAll">Select All</button>
            <button class="btn btn-outline-secondary" type="button" id="deselectAll">Deselect All</button>
        </div>
        <div style="max-height:400px; overflow:auto">
            <div id="clientList"></div>
        </div>
        <input type="hidden" name="admin_id" id="admin_id" value="${adminId}">
        <input type="hidden" name="tenant" id="tenant" value="${TENANT_URL}">
        <input type="hidden" name="FCN" value="setPermissions">
    </form>`;

    var clients = []; // Store client data to filter

    // Call the modal generator with the content first
    loadModalContent(dest, "clientBox", "modal-xl", 1060, "true", "Client Assignments", "cancelConfirm", saveAccess);

    // Fetch client details and existing access permissions
    fetch(ROOT_URL + '/includes/master/get_client_access.php?admin_id=' + adminId + '&tenant=' + TENANT_URL)
        .then(response => response.json())
        .then(data => {
            clients = data.clients; // Store fetched clients for filtering

            // Populate selectedClients from preselected clients (from the database)
            data.clients.forEach(client => {
                if (client.access) {
                    selectedClients.add(client.clientnumber.toString());
                }
            });

            // Ensure the clientList div exists before setting the content
            setTimeout(() => {
                const clientListElement = document.getElementById('clientList');
                if (clientListElement) {
                    // Build and display the client list dynamically
                    clientListElement.innerHTML = buildClientList(clients, selectedClients);
                } else {
                    console.error('Error: clientList element not found.');
                }

                // Now that the client list is loaded, we can add event listeners
                const searchClientInput = document.getElementById('searchClient');
                const clearSearchButton = document.getElementById('clearSearch');
                const selectAllButton = document.getElementById('selectAll');
                const deselectAllButton = document.getElementById('deselectAll');

                // Handle search input
                if (searchClientInput) {
                    searchClientInput.addEventListener('input', function() {
                        const searchValue = this.value.toLowerCase();
                        const filteredClients = clients.filter(client => client.clientname.toLowerCase().includes(searchValue));
                        document.getElementById('clientList').innerHTML = buildClientList(filteredClients, selectedClients);
                    });
                }

                // Handle clear search button
                if (clearSearchButton) {
                    clearSearchButton.addEventListener('click', function() {
                        searchClientInput.value = ''; // Clear the input field
                        document.getElementById('clientList').innerHTML = buildClientList(clients, selectedClients); // Reset client list
                    });
                }

                // Select all button handler
                if (selectAllButton) {
                    selectAllButton.addEventListener('click', function() {
                        clients.forEach(client => selectedClients.add(client.clientnumber.toString())); // Add all clients to the set
                        document.getElementById('clientList').innerHTML = buildClientList(clients, selectedClients);
                    });
                }

                // Deselect all button handler
                if (deselectAllButton) {
                    deselectAllButton.addEventListener('click', function() {
                        clients.forEach(client => selectedClients.delete(client.clientnumber.toString())); // Remove all clients from the set
                        document.getElementById('clientList').innerHTML = buildClientList(clients, selectedClients);
                    });
                }

                // Track checkbox changes
                document.getElementById('clientList').addEventListener('change', function(event) {
                    const target = event.target;
                    if (target.type === 'checkbox') {
                        const clientNumber = target.value;
                        if (target.checked) {
                            selectedClients.add(clientNumber); // Add client to the selected set
                        } else {
                            selectedClients.delete(clientNumber); // Remove client from the selected set
                        }
                    }
                });

            }, 100); // Delay added to ensure modal content is rendered
        })
        .catch(error => console.error('Error fetching client access data:', error));
}

// Function to build client list
function buildClientList(clientList, selectedClients) {
    let clientListData = '';
    clientList.forEach(client => {
        const isChecked = selectedClients.has(client.clientnumber.toString()) ? 'checked' : '';
        clientListData += `
            <div class="form-check form-switch">
                <input class="form-check-input" type="checkbox" role="switch" id="client${client.clientnumber}" name="clientnumbers[]" value="${client.clientnumber}" ${isChecked}>
                <label class="form-check-label" for="client${client.clientnumber}">
                    ${client.clientname} (${client.statuslive === 1 ? 'Active' : 'Inactive'})
                </label>
            </div>
        `;
    });
    return clientListData;
}

// Save function to send the selected clients to the server
function saveAccess() {
    const formData = new FormData(document.getElementById('accessForm'));

    // Append selected clients to formData before submitting
    selectedClients.forEach(clientNumber => {
        formData.append('clientnumbers[]', clientNumber);
    });

    fetch(ROOT_URL + '/includes/admin/admin_functions.php', {
            method: 'POST',
            body: formData
        }).then(response => response.text())
        .then(result => {
            if (result.trim() === "success") {
                showResponse('success', 'Access permissions saved successfully');
                const accessModal = mdb.Modal.getInstance(document.getElementById('clientBox'));
                accessModal.hide();
                killModal('clientBox');
            }
        }).catch(error => console.error('Error saving access permissions:', error));
}


document.getElementById('navBox').innerHTML = '<li class="breadcrumb-item">Tools <i class="fad fa-angle-double-right mx-2 mt-1" aria-hidden="true"></i></li><li class="breadcrumb-item active">Admin Management</li>';
</script>