<?php

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

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

# Includes Section
include_once($_SERVER['DOCUMENT_ROOT'] . '/bin/php/Classes/pageNavbar.php');
include_once($_SERVER['DOCUMENT_ROOT'] . '/api/classes/API_apitoken.php');

# Check permissions

# Page functions


# JS Scripts to load for this page
$jsScriptLoadData['enableButtonOnImageUpload'] = true;
$jsScriptLoadData['delete_confirmation'] = true;
$jsScriptLoadData['CopyTargetData'] = true;
$jsScriptLoadData['updateToggle'] = true;

# PageClasses Setup
$pageNavbar = new pageNavbar(false, '<i class="fa-solid fa-address-card"></i>  ' . $_SESSION['user']['user_full_name'] . ' ' . strtolower(__('user_profile')));

# Retrieve Information for the page
$user_groups_data = $GLOBALS['conn']->query("SELECT * FROM vc_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()) {
    array_push($user_groups, $user_group);
    $last_weight = $user_group['user_group_weight'];
}

$user_uuid = $_SESSION['user']['user_uuid'];
$stmt = $GLOBALS['conn']->prepare("SELECT * FROM vc_users INNER JOIN vc_user_groups ON vc_users.user_group_uuid = vc_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) {
    $user_data = $result->fetch_assoc();
}

$_GET['user_uuid'] = $user_uuid;

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

$new_api_token = false;
if (isset($_SESSION['tmp_api_token'])) {
    $new_api_token = $_SESSION['tmp_api_token'];
    unset($_SESSION['tmp_api_token']);
}

if ($API_token->checkPermissions('admin-access-admins', 'RW', true)) {
    $pageNavbar->AddHTMLButton('<a class="btn btn-primary mx-3" type="button" href="?edit=' . $_SESSION['user']['user_uuid'] . '"><i class="fas fa-edit"></i> ' . __('edit') . '</a>');
};

# Set breadcrumb data


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

if ($user_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/users/avatar/" enctype="multipart/form-data">
                        <input type="hidden" name="user_uuid" value="<?php echo $user_data['user_uuid'] ?>">
                        <h1 class="text-center"><?php echo $user_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(($user_data['user_profile_picture'] != null) ? 'data:image/png;base64, ' . $user_data['user_profile_picture'] : '/src/images/user-avatar-default-small.png') ?>" alt="user_profile_picture">
                                    <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">
                                </div>
                            </div>
                        </div>
                        <div class="form-group form-show-validation row justify-content-center">
                            <div class="d-flex flex-column align-items-center">
                                <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>
                            </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 $user_data['user_uuid'] ?></td>
                        </tr>
                        <tr>
                            <td>user_group_uuid:</td>
                            <td><?php echo $user_data['user_group_uuid'] ?></td>
                        </tr>
                        <tr>
                            <td>user_group_name:</td>
                            <td><?php echo $user_data['user_group_name'] ?></td>
                        </tr>
                        <tr>
                            <td>user_group_slugify:</td>
                            <td><?php echo $user_data['user_group_slugify'] ?></td>
                        </tr>
                        <tr>
                            <td>user_email:</td>
                            <td><?php echo $user_data['user_email'] ?></td>
                        </tr>
                        <tr>
                            <td>user_first_name:</td>
                            <td><?php echo $user_data['user_first_name'] ?></td>
                        </tr>
                        <tr>
                            <td>user_last_name:</td>
                            <td><?php echo $user_data['user_last_name'] ?></td>
                        </tr>
                        <tr>
                            <td>user_full_name:</td>
                            <td><?php echo $user_data['user_full_name'] ?></td>
                        </tr>
                        <tr>
                            <td>user_phone_number:&nbsp;&nbsp;</td>
                            <td><?php echo $user_data['user_phone_number'] ?></td>
                        </tr>
                        <tr>
                            <td>user_status:&nbsp;&nbsp;</td>
                            <td><?php echo $user_data['user_status'] ?></td>
                        </tr>
                        <tr>
                            <td>user_password_reset_expires:&nbsp;&nbsp;</td>
                            <td><?php echo $user_data['user_password_reset_expires'] ?></td>
                        </tr>
                        <tr>
                            <td>user_two_factor_enabled:&nbsp;&nbsp;</td>
                            <td><?php echo $user_data['user_two_factor_enabled'] ?></td>
                        </tr>
                        <tr>
                            <td>user_verified_email:&nbsp;&nbsp;</td>
                            <td><?php echo $user_data['user_verified_email'] ?></td>
                        </tr>
                        <tr>
                            <td>user_verified_phone:&nbsp;&nbsp;</td>
                            <td><?php echo $user_data['user_verified_phone'] ?></td>
                        </tr>
                        <tr>
                            <td>user_create_timestamp:&nbsp;&nbsp;</td>
                            <td><?php showTime($user_data['user_create_timestamp']); ?></td>
                        </tr>
                        <tr>
                            <td>user_modified_timestamp:&nbsp;&nbsp;</td>
                            <td><?php showTime($user_data['user_modified_timestamp']); ?></td>
                        </tr>
                        <tr>
                            <td>user_last_login_timestamp:&nbsp;&nbsp;</td>
                            <td><?php showTime($user_data['user_last_login_timestamp']); ?></td>
                        </tr>
                        <tr>
                            <td>user_login_attempts:&nbsp;&nbsp;</td>
                            <td><?php echo $user_data['user_login_attempts'] ?></td>
                        </tr>
                        <tr>
                            <td>user_pref_language:&nbsp;&nbsp;</td>
                            <td><?php echo $user_data['user_pref_language'] ?></td>
                        </tr>
                        <?php if ($GLOBALS['modules_enabled']['office']) { ?>
                            <tr>
                                <td>user_stompable:&nbsp;&nbsp;</td>
                                <td><?php echo $user_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 setttings</h4>
                </div>
                <div class="card-body">
                    to be made later
                </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">
                    <div id="mfa-enabled-row" class="row" style="display: <?php echo(($_SESSION['user']['user_two_factor_enabled'] == 1) ? '' : 'none') ?>">
                        <div class="col-auto">
                            <a href="#" class="btn btn-danger delete-btn" data-item-uuid="<?php echo $user_uuid ?>" data-api-url="/api/v1/users/mfa/" data-delete-action='{"mfa-enabled-row":"hide", "mfa-disabled-row":"show"}' data-item-name='user_uuid'>
                                <i class="fa-solid fa-lock"></i> <?php echo __('reset_mfa') ?>
                            </a>
                        </div>
                    </div>

                    <div id="mfa-disabled-row" class="row" style="display: <?php echo(($_SESSION['user']['user_two_factor_enabled'] == 1) ? 'none' : '') ?>">
                        <div class="col-auto">
                            <a class="btn btn-primary" href="/login/mfaSetup.php">
                                <i class="fa-solid fa-lock"></i> <?php echo __('set_mfa') ?>
                            </a>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-auto">
                            <a class="btn btn-primary mt-2" href="/login/resetPassword.php" disabled="">
                                <i class="fa-solid fa-lock"></i> <?php echo __('reset_password') ?>
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-md-12">
            <div class="card">
                <div class="card-header pt-2 pb-1">
                    <h4 class="mb-0">User history</h4>
                </div>
                <div class="card-body">
                    To be made. Its going show the history of the user.
                </div>
            </div>
        </div>
    </div>

    <?php if ($API_token->checkPermissions('user-apitoken-self', 'RO', true)) { ?>
        <div class="row">
            <div class="col-md-12">
                <?php if ($new_api_token) { ?>
                    <div class="card bg-primary text-center">
                        <div class="card-body">
                            <h4><?php echo __('api_token_created') ?>!</h4>
                            <p>This token will be visible only now, please copy it now if you ever want to use it: </p>
                            <div class="d-flex justify-content-center align-items-center gap-2">
                                <div id="new-api-token" class="text-break" data-copy-data="<?php echo $new_api_token ?>">
                                    <?php echo $new_api_token ?>
                                </div>
                                <button type="button" class="btn btn-sm btn-outline-dark" data-copy-target="new-api-token" title="Copy Token">
                                    <i class="fa-solid fa-copy"></i> Copy
                                </button>
                            </div>
                        </div>
                    </div>
                <?php } ?>

                <div class="card">
                    <div class="card-header d-flex justify-content-between align-items-center pt-2 pb-1">
                        <h4 class="mb-0"><?php echo __('api_tokens') ?></h4>
                        <?php if ($API_token->checkPermissions('user-apitoken-self', 'RW', true)) { ?>
                            <form method="POST" action="/api/v1/users/apitoken/">
                                <input type="hidden" name="user_uuid" value="<?php echo $user_uuid ?>">
                                <input type="hidden" name="_return" value="/userprofile/">
                                <button type="submit" href="#" class="btn btn-primary">
                                    <i class="fa-solid fa-plus"></i> <?php echo __('generate_new_api_token') ?>
                                </button>
                            </form>
                        <?php } ?>
                    </div>
                    <div class="card-body">
                        <table class="table table-hover table-striped">
                            <thead>
                            <tr>
                                <th>Token id</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" style="max-width: 100%;">
                                        <div class="d-flex align-items-center gap-2" style="max-width: 100%;">
                                            <div class="text-truncate" style="max-width: 200px;" 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 Token">
                                                <i class="fa-solid fa-copy"></i>
                                            </button>
                                        </div>
                                    </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/users/apitoken/" <?php echo((($token_data['api_token_revoked'])) ? 'checked' : '') ?>>
                                            <div class="slider"></div>
                                        </label>
                                    </td>
                                    <?php if ($API_token->checkPermissions('user-apitoken-self', 'RW', true)) { ?>
                                        <td class="text-nowrap">
                                            <a href="#" class="btn btn-danger btn-sm btn-rounded delete-btn" data-item-uuid="<?php echo $token_data['api_token_uuid'] ?>" data-item-name="api_token_uuid" data-api-url="/api/v1/users/apitoken/"><i class="fas fa-trash-alt"></i></a>
                                        </td>
                                    <?php } ?>
                                </tr>
                            <?php } ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    <?php } ?><?php } else {
    echo 'user not found';
}