<?php
require_once __DIR__ . '/security.php';
require_once __DIR__ . '/logging.php';

$tenantInput = $_REQUEST['tenant'] ?? ($_SERVER['HTTP_HOST'] ?? '');
$tenant = enrep_tenant_segment((string)$tenantInput);
if (file_exists('../../' . $tenant . '/config.php')) {
    require_once('../../' . $tenant . '/config.php');
}
if (file_exists('/config.php')) {
    require_once('/config.php');
}
enrep_require_admin();

$type = enrep_request_enum('type', ['admins', 'surveyor', 'agents'], '');
$id = enrep_request_int('id', 0);
$op = enrep_request_enum('op', ['seclev', 'edit', 'remove'], '');
$name = enrep_request_string('name', '', 255);
$tenantForRequest = defined('TENANT_URL') ? TENANT_URL : '/' . $tenant;

$idColumnByType = [
    'admins' => 'id',
    'surveyor' => 'id',
    'agents' => 'agent_number',
];

if ($type === '' || $id < 1) {
    enrep_fail(400, 'Invalid user');
}

$idColumn = $idColumnByType[$type];

if (enrep_request_enum('FCN', ['changeSec'], '') === 'changeSec') {
    $sec = (int)enrep_request_enum('sec', ['0', '1', '2', '3'], '0');

    $stmt = $GLOBALS['con']->prepare("UPDATE `$type` SET `access`=? WHERE `$idColumn`=?") or die(mysqli_error($GLOBALS['con']));
    $stmt->bind_param('ii', $sec, $id);
    $stmt->execute();
    $stmt->close();

    enrep_log('users', 'security_level_changed', 'Changed access privileges for ' . $name, [
        'entity_type' => $type,
        'entity_id' => $id,
        'subject' => $name,
        'security_level' => $sec,
    ]);
    exit();
}

$stmt = $GLOBALS['con']->prepare("SELECT * FROM `$type` WHERE `$idColumn`=?") or die(mysqli_error($GLOBALS['con']));
$stmt->bind_param('i', $id);
$stmt->execute();
$a = $stmt->get_result();
$stmt->close();
$i = mysqli_fetch_array($a);

if (!$i) {
    enrep_fail(404, 'User not found');
}

$typeHtml = htmlspecialchars($type, ENT_QUOTES, 'UTF-8');
$nameHtml = htmlspecialchars($name, ENT_QUOTES, 'UTF-8');
$idHtml = htmlspecialchars((string)$id, ENT_QUOTES, 'UTF-8');
?>

<?php switch ($op) {
    default:
        break;

    case "seclev": ?>
<h3>Change security level</h3>
<div class="row">
    <div class="col-md-3 <?php if ($type === "admins") { ?>offset-md-1<?php } ?> text-center"><a
            href="javascript:void(0)"
            class="btn <?php if ((int)$i['access'] === 0) { echo "btn-success"; } else { echo "btn-warning"; } ?>"
            onClick="changeSec('<?= $idHtml ?>','0')">0</a><br>Suspend Access</div>

    <div class="col-md-3 text-center"><a href="javascript:void(0)"
            class="btn <?php if ((int)$i['access'] === 1) { echo "btn-success"; } else { echo "btn-secondary"; } ?>"
            onClick="changeSec('<?= $idHtml ?>','1')">1</a><br>Full administrative access
    </div>

    <?php if ($type !== "admins") { ?>
    <div class="col-md-3 text-center"><a href="javascript:void(0)"
            class="btn <?php if ((int)$i['access'] === 2) { echo "btn-success"; } else { echo "btn-secondary"; } ?>"
            onClick="changeSec('<?= $idHtml ?>','2')">2</a><br>Elevated
        (<?= $typeHtml ?>) access</div>

    <div class="col-md-3 text-center"><a href="javascript:void(0)"
            class="btn <?php if ((int)$i['access'] === 3) { echo "btn-success"; } else { echo "btn-secondary"; } ?>"
            onClick="changeSec('<?= $idHtml ?>','3')">3</a><br>Assigned
        (<?= $typeHtml ?>) access</div>
    <?php } ?>
</div>
<?php break;

    case "edit": ?>
<h3>Editing</h3>

<?php break;

    case "remove": ?>
<h3>Confirm removal</h3>

<?php break;
} ?>

<script>
const editUserId = <?= json_encode((string)$id) ?>;
const editUserType = <?= json_encode($type) ?>;
const editUserName = <?= json_encode($name) ?>;
const editUserOp = <?= json_encode($op) ?>;
const editUserTenant = <?= json_encode($tenantForRequest) ?>;

$('#popupBox .modal-header').html(
    '<a href="javascript:void(0)" class="sa">Security Options: <?= $nameHtml ?></a><div class="pull-right"><a href="javascript:void(0)" class="btn" onclick="cancel()"><i class="fad fa-window-close fa-2x" aria-hidden="true"></i></a></div>'
);

function changeSec(i, s) {
    $.post('functions/edit_user.php', {
        FCN: "changeSec",
        id: i,
        sec: s,
        type: editUserType,
        name: editUserName,
        tenant: editUserTenant
    }, function() {
        const reloadUrl = 'functions/edit_user.php?op=' + encodeURIComponent(editUserOp) +
            '&id=' + encodeURIComponent(editUserId) +
            '&type=' + encodeURIComponent(editUserType) +
            '&name=' + encodeURIComponent(editUserName) +
            '&tenant=' + encodeURIComponent(editUserTenant);
        $('#' + editUserType + 'L' + i).load(reloadUrl);
        $('#' + editUserType + 'A' + i).text(s);
    });
}
</script>
