<?php 
if(file_exists('../../../'.$_REQUEST['tenant'].'/config.php')){require_once('../../../'.$_REQUEST['tenant'].'/config.php');}
if(file_exists('/config.php')){require_once('/config.php');}
$adminProfileMode = (($_REQUEST['profile'] ?? '') === '1');
if ($adminProfileMode) {
    $adminProfileId = (int)($_SESSION['admin_id'] ?? ($_SESSION['userid'] ?? 0));
    $adminProfile = null;
    if ($adminProfileId > 0) {
        $stmt = $GLOBALS['con']->prepare("SELECT `id`, `name`, `tel`, `email`, AES_DECRYPT(`password`, `email`) AS `pass` FROM `admins` WHERE `id`=? LIMIT 1") or die(mysqli_error($GLOBALS['con']));
        $stmt->bind_param('i', $adminProfileId);
        $stmt->execute();
        $adminProfile = $stmt->get_result()->fetch_assoc();
        $stmt->close();
    }
    ?>
<style>
.dt-buttons {
    display: none !important
}
</style>
<?php if (!$adminProfile) { ?>
<div class="alert alert-danger">Unable to load your administrator profile.</div>
<?php } else { ?>
<div class="note note-secondary mb-3">
    Profile settings <small class="muted">Update your administrator login details.</small>
</div>
<form id="adminProfileForm" class="form-horizontal">
    <div class="row">
        <div class="col-12 col-lg-6 mb-5">
            <div class="card">
                <div class="card-header">Login Details</div>
                <div class="card-body">
                    <div class="mb-3">
                        <label class="form-label" for="admin_profile_name">Name</label>
                        <input type="text" id="admin_profile_name" name="name" class="form-control"
                            value="<?= htmlspecialchars((string)$adminProfile['name'], ENT_QUOTES) ?>" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label" for="admin_profile_tel">Phone</label>
                        <input type="tel" id="admin_profile_tel" name="tel" class="form-control"
                            value="<?= htmlspecialchars((string)$adminProfile['tel'], ENT_QUOTES) ?>" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label" for="admin_profile_email">Email</label>
                        <input type="email" id="admin_profile_email" name="email" class="form-control"
                            value="<?= htmlspecialchars((string)$adminProfile['email'], ENT_QUOTES) ?>" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label" for="admin_profile_password">Password</label>
                        <div class="input-group">
                            <input type="password" id="admin_profile_password" name="password" class="form-control"
                                value="<?= htmlspecialchars((string)$adminProfile['pass'], ENT_QUOTES) ?>"
                                autocomplete="new-password" required>
                            <button type="button" class="btn btn-outline-secondary"
                                onclick="toggleAdminPasswordVisibility(this)" aria-label="Show admin password"
                                title="Show password">
                                <i class="fad fa-eye"></i>
                            </button>
                            <button type="button" class="btn btn-outline-secondary"
                                onclick="generateAdminPassword(this)" aria-label="Generate admin password"
                                title="Generate password">
                                <i class="fad fa-key"></i> Generate
                            </button>
                        </div>
                    </div>
                    <input type="hidden" name="FCN" value="profileUpdate">
                    <input type="hidden" name="tenant" value="<?= TENANT_URL ?>">
                    <input id="btn_update" type="submit" name="submit" value="Update" style="display:none">
                </div>
            </div>
        </div>
    </div>
</form>
<script>
function toggleAdminPasswordVisibility(button) {
    const group = button.closest('.input-group');
    const passwordField = group ? group.querySelector('input[name="password"]') : null;
    const toggleIcon = button.querySelector('i');

    if (!passwordField) {
        return;
    }

    const isHidden = passwordField.type === 'password';
    passwordField.type = isHidden ? 'text' : 'password';
    button.setAttribute('aria-label', isHidden ? 'Hide admin password' : 'Show admin password');
    button.setAttribute('title', isHidden ? 'Hide password' : 'Show password');

    if (toggleIcon) {
        toggleIcon.className = isHidden ? 'fad fa-eye-slash' : 'fad fa-eye';
    }
}

function generateAdminPassword(button) {
    const group = button.closest('.input-group');
    const passwordField = group ? group.querySelector('input[name="password"]') : null;
    const toggleButton = group ? group.querySelector('button[onclick^="toggleAdminPasswordVisibility"]') : null;
    const toggleIcon = toggleButton ? toggleButton.querySelector('i') : null;

    if (!passwordField) {
        return;
    }

    const upper = 'ABCDEFGHJKLMNPQRSTUVWXYZ';
    const lower = 'abcdefghijkmnopqrstuvwxyz';
    const numbers = '23456789';
    const all = upper + lower + numbers;
    const length = 16;
    const password = [
        getSecureRandomCharacter(upper),
        getSecureRandomCharacter(lower),
        getSecureRandomCharacter(numbers)
    ];

    while (password.length < length) {
        password.push(getSecureRandomCharacter(all));
    }

    passwordField.value = shuffleSecureCharacters(password).join('');
    passwordField.type = 'text';

    if (toggleButton) {
        toggleButton.setAttribute('aria-label', 'Hide admin password');
        toggleButton.setAttribute('title', 'Hide password');
    }

    if (toggleIcon) {
        toggleIcon.className = 'fad fa-eye-slash';
    }
}

function getSecureRandomCharacter(characters) {
    const values = new Uint32Array(1);
    window.crypto.getRandomValues(values);
    return characters[values[0] % characters.length];
}

function shuffleSecureCharacters(characters) {
    for (let i = characters.length - 1; i > 0; i--) {
        const values = new Uint32Array(1);
        window.crypto.getRandomValues(values);
        const j = values[0] % (i + 1);
        const tmp = characters[i];
        characters[i] = characters[j];
        characters[j] = tmp;
    }

    return characters;
}

document.addEventListener('DOMContentLoaded', function() {
    document.getElementById('navBox').innerHTML = '<li class="breadcrumb-item active">Profile</li>';
    document.getElementById('footerControls').innerHTML =
        '<button class="btn btn-secondary" onclick="triggerAction(\'btn_update\')">UPDATE PROFILE</button>';

    const adminProfileForm = document.getElementById('adminProfileForm');
    adminProfileForm.addEventListener('submit', function(event) {
        event.preventDefault();

        fetch(ROOT_URL + '/includes/admin/admin_functions.php', {
                method: 'POST',
                body: new FormData(adminProfileForm)
            }).then(response => response.text())
            .then(result => {
                if (result.trim() === 'success') {
                    showResponse('success', 'Your profile has been saved successfully');
                } else {
                    showResponse('danger', 'There was an error saving your profile');
                }
            }).catch(error => {
                console.error('Error:', error);
            });
    });
});
</script>
<?php } ?>
<?php return; } ?>

<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>
                            <div class="input-group">
                                <input type="password" name="password" class="form-control" value="" required>
                                <button type="button" class="btn btn-outline-secondary"
                                    onclick="toggleAdminPasswordVisibility(this)" aria-label="Show admin password"
                                    title="Show password">
                                    <i class="fad fa-eye"></i>
                                </button>
                                <button type="button" class="btn btn-outline-secondary"
                                    onclick="generateAdminPassword(this)" aria-label="Generate admin password"
                                    title="Generate password">
                                    <i class="fad fa-key"></i> Generate
                                </button>
                            </div>
                        </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>
                <div class="input-group">
                    <input type="password" name="password" class="form-control" value="<?= $cd['password']?>"
                        form="F<?= $cd['id']?>">
                    <button type="button" class="btn btn-outline-secondary"
                        onclick="toggleAdminPasswordVisibility(this)" aria-label="Show admin password"
                        title="Show password">
                        <i class="fad fa-eye"></i>
                    </button>
                </div>
            </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 toggleAdminPasswordVisibility(button) {
    const group = button.closest('.input-group');
    const passwordField = group ? group.querySelector('input[name="password"]') : null;
    const toggleIcon = button.querySelector('i');

    if (!passwordField) {
        return;
    }

    const isHidden = passwordField.type === 'password';
    passwordField.type = isHidden ? 'text' : 'password';
    button.setAttribute('aria-label', isHidden ? 'Hide admin password' : 'Show admin password');
    button.setAttribute('title', isHidden ? 'Hide password' : 'Show password');

    if (toggleIcon) {
        toggleIcon.className = isHidden ? 'fad fa-eye-slash' : 'fad fa-eye';
    }
}

function generateAdminPassword(button) {
    const group = button.closest('.input-group');
    const passwordField = group ? group.querySelector('input[name="password"]') : null;
    const toggleButton = group ? group.querySelector('button[onclick^="toggleAdminPasswordVisibility"]') : null;
    const toggleIcon = toggleButton ? toggleButton.querySelector('i') : null;

    if (!passwordField) {
        return;
    }

    const upper = 'ABCDEFGHJKLMNPQRSTUVWXYZ';
    const lower = 'abcdefghijkmnopqrstuvwxyz';
    const numbers = '23456789';
    const all = upper + lower + numbers;
    const length = 16;
    const password = [
        getSecureRandomCharacter(upper),
        getSecureRandomCharacter(lower),
        getSecureRandomCharacter(numbers)
    ];

    while (password.length < length) {
        password.push(getSecureRandomCharacter(all));
    }

    passwordField.value = shuffleSecureCharacters(password).join('');
    passwordField.type = 'text';

    if (toggleButton) {
        toggleButton.setAttribute('aria-label', 'Hide admin password');
        toggleButton.setAttribute('title', 'Hide password');
    }

    if (toggleIcon) {
        toggleIcon.className = 'fad fa-eye-slash';
    }
}

function getSecureRandomCharacter(characters) {
    const values = new Uint32Array(1);
    window.crypto.getRandomValues(values);
    return characters[values[0] % characters.length];
}

function shuffleSecureCharacters(characters) {
    for (let i = characters.length - 1; i > 0; i--) {
        const values = new Uint32Array(1);
        window.crypto.getRandomValues(values);
        const j = values[0] % (i + 1);
        const tmp = characters[i];
        characters[i] = characters[j];
        characters[j] = tmp;
    }

    return characters;
}

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>