<?php

use api\classes\API;
use api\classes\API_apitoken;
use bin\php\Classes\pageNavbar;

if (!defined('APP_INIT')) {
    exit;
}
# IDE Section

# Includes Section
require_once "{$_SERVER['DOCUMENT_ROOT']}/bin/php/Classes/pageNavbar.php";
require_once "{$_SERVER['DOCUMENT_ROOT']}/api/classes/API_apitoken.php";

# Check permissions
$API = new API();
if (!$API->checkPermissions('admin-access-admins', 'RO', true)) {
    echo 'error 401 unauthorized';
    exit;
}

# Page functions

# JS Scripts to load for this page
$jsScriptLoadData['/src/js/sentri/Generatepassword.js'] = true;
$jsScriptLoadData['/src/js/sentri/passwordShowHide.js'] = true;
$jsScriptLoadData['/src/js/sentri/passwordRegen.js'] = true;
$jsScriptLoadData['/src/js/sentri/enableButtonOnImageUpload.js'] = true;
$jsScriptLoadData['/src/js/sentri/delete_confirmation.js'] = true;
$jsScriptLoadData['/src/js/sentri/breadCrumbs.js'] = true;
$jsScriptLoadData['/src/js/sentri/updateToggle.js'] = true;

# PageClasses Setup
$pageNavbar = new pageNavbar(true);
if ($API->checkPermissions('admin-access-admins', 'RW', true)) {
    $pageNavbar->AddHTMLButton('<button class="btn btn-danger" type="button" disabled><i class="fas fa-trash-alt"></i> ' . __('delete') . '</button>');
    $admin_view = htmlspecialchars($_GET['admin_view'], ENT_QUOTES, 'UTF-8');
    $pageNavbar->AddHTMLButton('<a class="btn btn-primary mx-3" type="button" href="?admin_edit=' . $admin_view . '"><i class="fas fa-edit text-warning"></i> ' . __('edit') . '</a>');
    $pageNavbar->AddHTMLButton('<a href="?admin_add="><button class="btn btn-primary"><i class="fas fa-plus text-success"></i> ' . __('add_admin') . '</button></a>');
}

# Retrieve Information for the page
$user_groups_data = $GLOBALS['conn']->query("SELECT * FROM system_user_groups WHERE user_group_type = 'admin' ORDER BY user_group_weight DESC");
$user_groups = array();
$admin_data = false;
while ($user_group = $user_groups_data->fetch_assoc()) {
    $user_groups[] = $user_group;
    $last_weight = $user_group['user_group_weight'];
}

$user_uuid = $_GET['admin_view'];
$stmt = $GLOBALS['conn']->prepare("SELECT * FROM system_users INNER JOIN system_user_groups ON system_users.user_group_uuid = system_user_groups.user_group_uuid WHERE user_uuid = ?");
$stmt->bind_param("s", $user_uuid);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows == 1) {
    $admin_data = $result->fetch_assoc();
}

$_GET['user_uuid'] = $user_uuid;

$userHashigherGroupWeight = false;
if ($admin_data['user_group_weight'] > $_SESSION['user']['user_group_weight']) {
    $userHashigherGroupWeight = true;
}

$API_token = new API_apitoken();
$requiredFields = ['user_uuid' => ['type' => 'uuid']];
$API_token->validateData($requiredFields);
$apitokens = $API_token->getTokens();

# Set breadcrumb data
$_SESSION['breadCrumbArray'][] = ['display' => __('administrators'), 'href' => '/accesscontrol/#administrators'];
$_SESSION['breadCrumbArray'][] = ['display' => __('view'), 'href' => ''];

# Start page output
$pageNavbar->outPutNavbar();

if ($admin_data) { ?>
    <div class="row d-flex align-items-stretch pb-2">
        <div class="col-md-4 pb-4">
            <div class="card h-100">
                <div class="card-body">
                    <form method="POST" action="/api/v1/user/avatar/" enctype="multipart/form-data">
                        <input type="hidden" name="user_uuid" value="<?php echo $admin_data['user_uuid'] ?>">
                        <h1 class="text-center"><?php echo $admin_data['user_full_name'] ?></h1>
                        <div class="form-group form-show-validation row align-items-center justify-content-center">
                            <div class="col-lg-9 col-md-12 col-sm-10">
                                <div class="input-file input-file-image">
                                    <img class="img-upload-preview w-100" src="<?php echo(($admin_data['user_profile_picture'] != null) ? 'data:image/png;base64, ' . $admin_data['user_profile_picture'] : '/src/images/user-avatar-default-small.png') ?>" alt="user_profile_picture">
                                    <?php if ($API->checkPermissions('admin-access-admins', 'RW', true)) { ?>
                                        <input type="file" class="form-control form-control-file" id="user_profile_picture" name="user_profile_picture" accept="image/png" data-enable-button="user_profile_change">
                                    <?php } ?>
                                </div>
                            </div>
                        </div>
                        <div class="form-group form-show-validation row justify-content-center">
                            <div class="d-flex flex-column align-items-center">
                                <?php if ($API->checkPermissions('admin-access-admins', 'RW', true)) { ?>
                                    <label for="user_profile_picture" class="label-input-file btn btn-black btn-round mb-4">
                                        <span class="btn-label"><i class="fa fa-file-image"></i></span>
                                        <?php echo __('upload_image') ?>
                                    </label>
                                    <button id="user_profile_change" type="submit" class="btn btn-primary opacity-0 transition-opacity" disabled>
                                        <i class="fa-solid fa-floppy-disk"></i> <?php echo __('save') ?>
                                    </button>
                                <?php } ?>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
        <div class="col-md-8 pb-4">
            <div class="card h-100">
                <div class="card-body">
                    <table>
                        <tr>
                            <td>user_uuid:</td>
                            <td><?php echo $admin_data['user_uuid'] ?></td>
                        </tr>
                        <tr>
                            <td>user_group_uuid:</td>
                            <td><?php echo $admin_data['user_group_uuid'] ?></td>
                        </tr>
                        <tr>
                            <td>user_group_name:</td>
                            <td><?php echo $admin_data['user_group_name'] ?></td>
                        </tr>
                        <tr>
                            <td>user_group_slugify:</td>
                            <td><?php echo $admin_data['user_group_slugify'] ?></td>
                        </tr>
                        <tr>
                            <td>user_email:</td>
                            <td><?php echo $admin_data['user_email'] ?></td>
                        </tr>
                        <tr>
                            <td>user_first_name:</td>
                            <td><?php echo $admin_data['user_first_name'] ?></td>
                        </tr>
                        <tr>
                            <td>user_last_name:</td>
                            <td><?php echo $admin_data['user_last_name'] ?></td>
                        </tr>
                        <tr>
                            <td>user_full_name:</td>
                            <td><?php echo $admin_data['user_full_name'] ?></td>
                        </tr>
                        <tr>
                            <td>user_phone_number:&nbsp;&nbsp;</td>
                            <td><?php echo $admin_data['user_phone_number'] ?></td>
                        </tr>
                        <tr>
                            <td>user_status:&nbsp;&nbsp;</td>
                            <td><?php echo $admin_data['user_status'] ?></td>
                        </tr>
                        <tr>
                            <td>user_password_reset_expires:&nbsp;&nbsp;</td>
                            <td><?php echo $admin_data['user_password_reset_expires'] ?></td>
                        </tr>
                        <tr>
                            <td>user_two_factor_enabled:&nbsp;&nbsp;</td>
                            <td><?php echo $admin_data['user_two_factor_enabled'] ?></td>
                        </tr>
                        <tr>
                            <td>user_verified_email:&nbsp;&nbsp;</td>
                            <td><?php echo $admin_data['user_verified_email'] ?></td>
                        </tr>
                        <tr>
                            <td>user_verified_phone:&nbsp;&nbsp;</td>
                            <td><?php echo $admin_data['user_verified_phone'] ?></td>
                        </tr>
                        <tr>
                            <td>user_create_timestamp:&nbsp;&nbsp;</td>
                            <td><?php showTime($admin_data['user_create_timestamp']) ?></td>
                        </tr>
                        <tr>
                            <td>user_modified_timestamp:&nbsp;&nbsp;</td>
                            <td><?php showTime($admin_data['user_modified_timestamp']) ?></td>
                        </tr>
                        <tr>
                            <td>user_last_login_timestamp:&nbsp;&nbsp;</td>
                            <td><?php showTime($admin_data['user_last_login_timestamp']) ?></td>
                        </tr>
                        <tr>
                            <td>user_login_attempts:&nbsp;&nbsp;</td>
                            <td><?php echo $admin_data['user_login_attempts'] ?></td>
                        </tr>
                        <tr>
                            <td>user_pref_language:&nbsp;&nbsp;</td>
                            <td><?php echo $admin_data['user_pref_language'] ?></td>
                        </tr>
                        <?php if ($GLOBALS['modules_enabled']['office']) { ?>
                            <tr>
                                <td>user_stompable:&nbsp;&nbsp;</td>
                                <td><?php echo $admin_data['user_stompable'] ?></td>
                            </tr>
                        <?php } ?>
                    </table>
                </div>
            </div>
        </div>
    </div>
    <div class="row">
        <div class="col-md-6">
            <div class="card">
                <div class="card-header pt-2 pb-1">
                    <h4>email-preferences</h4>
                </div>
                <div class="card-body">
                    to be made
                </div>
            </div>
        </div>

        <div class="col-md-6">
            <div class="card">
                <div class="card-header pt-2 pb-1">
                    <h4><?php echo __('user_management') ?></h4>
                </div>
                <div class="card-body">
                    <?php if ($API->checkPermissions('admin-access-admins-mfa', 'RW', true)) { ?>
                        <div id="mfa-enabled-row" class="row <?= ($admin_data['user_two_factor_enabled'] ? '' : 'd-none') ?>">
                            <div class="col-auto">
                                <a href="#" class="btn btn-danger delete-btn" data-item-uuid="<?= $admin_data['user_uuid'] ?>" data-api-url="/api/v1/user/mfa/" data-item-name="user_uuid" data-delete-action='{"mfa-enabled-row":"hide", "mfa-disabled-row":"show"}'>
                                    <i class="fa-solid fa-lock"></i> <?= __('reset_mfa') ?>
                                </a>
                            </div>
                        </div>

                        <div id="mfa-disabled-row" class="row <?= ($admin_data['user_two_factor_enabled'] ? 'd-none' : '') ?>">
                            <div class="col-auto">
                                <button class="btn btn-danger delete-btn" disabled>
                                    <i class="fa-solid fa-lock"></i> <?= __('reset_mfa') ?>
                                </button>
                            </div>
                        </div>
                    <?php }
                    if ($API->checkPermissions('admin-access-admins-resetpassword', 'RW', true)) { ?>
                        <form method="post" action="/api/v1/user/resetpassword/">
                            <input type="hidden" name="user_uuid" value="<?= $user_uuid ?>">
                            <button class="btn btn-primary mt-2">
                                <i class="fa-solid fa-lock"></i> <?= __('send_password_reset') ?>
                            </button>
                        </form>
                    <?php } ?>

                    reset the verified email (to be made)<br>
                </div>
            </div>
        </div>
    </div>

    <?php if ($API_token->checkPermissions('user-apitoken-others', 'RO', true)) { ?>
        <div class="row">
            <div class="col-md-12">
                <div class="card">

                    <div class="card-header d-flex justify-content-between align-items-center pt-2 pb-1">
                        <h4 class="mb-0">API Tokens</h4>
                        <?php if ($API_token->checkPermissions('user-apitoken-others', 'RW', true)) { ?>
                            <form method="POST" action="/api/v1/user/apitoken/">
                                <input type="hidden" name="user_uuid" value="<?php echo $user_uuid ?>">
                                <input type="hidden" name="_return" value="/userprofile/">
                                <div class="input-group mb-3">
                                    <input type="text" name="api_token_name" class="form-control" placeholder="API Token name..." aria-label="API Token name..." aria-describedby="button-addon2" <?php echo($userHashigherGroupWeight ? '' : 'disabled') ?>>
                                    <button type="submit" href="#" class="btn btn-success" <?php echo($userHashigherGroupWeight ? '' : 'disabled') ?>>
                                        <i class="fa-solid fa-plus"></i> <?php echo __('generate_new_api_token') ?>
                                    </button>
                                </div>
                            </form>
                        <?php } ?>
                    </div>
                    <div class="card-body">
                        <table class="table table-hover table-striped">
                            <thead>
                            <tr>
                                <th>Token id</th>
                                <th>Token Name</th>
                                <th>Expiration</th>
                                <th>Created</th>
                                <th>Last used</th>
                                <th>Revoked</th>
                            </tr>
                            </thead>
                            <tbody>
                            <?php foreach ($apitokens as $token_data) { ?>
                                <tr>
                                    <td class="text-nowrap">
                                        <div class="d-flex align-items-center gap-2">
                                            <div class="text-truncate" id="<?php echo $token_data['api_token_uuid'] ?>" data-copy-data="<?php echo $token_data['api_token_uuid']; ?>">
                                                <?php echo $token_data['api_token_uuid']; ?>
                                            </div>
                                            <button type="button" class="btn btn-sm btn-outline-secondary" data-copy-target="<?php echo $token_data['api_token_uuid'] ?>" title="Copy ID">
                                                <i class="fa-solid fa-copy"></i>
                                            </button>
                                        </div>
                                    </td>
                                    <td><?php echo $token_data['api_token_name'] ?></td>
                                    <td><?php showTime($token_data['api_token_expiration_timestamp']) ?></td>
                                    <td><?php showTime($token_data['api_token_created_timestamp']) ?></td>
                                    <td><?php showTime($token_data['api_token_last_used_timestamp']) ?></td>
                                    <td>
                                        <label class="switch">
                                            <input type="checkbox" class="checkbox" data-api-data='<?php echo json_encode(['api_token_uuid' => $token_data['api_token_uuid'], 'api_token_revoked' => $token_data['api_token_revoked'] ? 1 : 0]) ?>' data-api-changevalue="api_token_revoked" data-api-url="/api/v1/user/apitoken/" <?php echo((($token_data['api_token_revoked'])) ? 'checked' : '') ?> <?php echo($userHashigherGroupWeight ? '' : 'disabled') ?>>
                                            <span class="slider"></span>
                                        </label>
                                    </td>
                                    <?php if ($API_token->checkPermissions('user-apitoken-others', 'RW', true)) { ?>
                                        <td class="text-nowrap">
                                            <a href="#" class="btn btn-danger btn-sm btn-rounded delete-btn <?php echo($userHashigherGroupWeight ? '' : 'disabled') ?>" data-item-uuid="<?php echo $token_data['api_token_uuid'] ?>" data-item-name="api_token_uuid" data-api-url="/api/v1/user/apitoken/"><i class="fas fa-trash-alt"></i></a>
                                        </td>
                                    <?php } ?>
                                </tr>
                            <?php } ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    <?php } ?>

    <div class="row">
        <div class="col-md-12">
            <div class="card">
                <div class="card-header pt-2 pb-1">
                    <h4>User history</h4>
                </div>
                <div class="card-body">
                    To be made. It's going show the history of the administrator.
                </div>
            </div>
        </div>
    </div>

<?php } else {
    echo 'admin not found';
}