<?php
require "../../../src/config.php";

if (!auth::isadmin()) {
    error("You dont have permission to access this page");
}

if (isset($_GET['id'])) {

    $user = users::get($_GET['id']);
    if (!$user) {
        error("Invalid URL");
    } else {
        $user_id = $user['id'];
    }
} else {
    $user = users::defaults();
}

$warnings = [];

if (page::submitted()) {

    $input = $_POST;
    $user = $input;

    display($input);

    if ($input['password1'] != "" || $input['password2'] != "") {

        if ($input['password1'] != $input['password2']) {
            $warnings[] = "Passwords don't match";
        } else if (!validator::password($input['password1'])['success']) {
            $warnings = validator::password($input['password1'])['warnings'];
        } else {
            $input['password'] = md5($input['password1']);
        }
    }

    if (isset($_GET['id'])) {
        $response = users::update($_GET['id'], $input);
    } else {
        $response = users::create($input);
    }

    if ($response['success']) {
        //error("Failed");
        if (!isset($_GET['id'])) {
            $user_id = $response["id"];
        }

        foreach (userroles::types() as $value) {

            if (isset($input["state_" . $value['id']])) {
                if (!userroles::has_roleassigned($user_id, $value['id'])) {
                    userroles::assign($user_id, $value['id']);
                }
            } else {
                if (userroles::has_roleassigned($user_id, $value['id'])) {
                    userroles::remove($user_id, $value['id']);
                }
            }
        }

        if (!isset($_GET['id'])) {
            header("location: ../update?id=" . $user_id);
        }
    } else {
        $user = $input;
    }
}

page::set([
    "nav-id" => "user_useraccount",
    "title" => "Update Profile",
    "layout" => "admin",
    "scripts" => ["pickday", "chosen"],
    "size" => "box-md"
]);

page::header();
?>

<form class="card" method="post" enctype="multipart/form-data">

    <div class="card-top">
        <div class="title">Update Profile</div>
    </div>

    <div class="card-body">

        <?php if (page::submitted()) {
            form::response_summary($response);
        } ?>

        <?= ($warnings) ? UI::warning("Update Failed", $warnings) : "" ?>

        <div class="text-primary text-lg my-3">Basic Information</div>

        <div>

            <div class="form-group">
                <label for="name">Name</label>
                <div class="input-group">
                    <input class="form-control" placeholder="Display Name" name='name' value="<?= $user["name"] ?>" type="text" required>
                </div>
            </div>

            <div class="form-group">
                <label for="designation">Designation</label>
                <div class="input-group">
                    <input class="form-control" placeholder="designation" name='designation' value="<?= $user["designation"] ?>" type="text">
                </div>
            </div>

            <div class="form-group">

                <label for="institution">Institution</label>

                <div class="input-group">
                    <select name="institution" id="institution" class="form-control">
                        <?php foreach (institutions::all() as $value) {
                            echo '<option value="' . $value['ins_id'] . '" ' . ($value["ins_id"] == $user["institution"] ? "selected" : "") . '>' . $value['ins_name'] . '</option>';
                        }  ?>
                    </select>
                </div>
            </div>

        </div>

        <div class="text-primary text-lg my-3">User Account</div>

        <div>

            <div class="form-group">
                <label for="username">Username</label>
                <div class="input-group">
                    <input class="form-control" placeholder="Username" name='username' value="<?= $user["username"] ?>" type="text" required>
                </div>
            </div>

            <div class="form-group">
                <label for="password1">New Password</label>
                <div class="input-group">
                    <input class="form-control" placeholder="New password" name='password1' value="" type="password">
                </div>
            </div>

            <div class="form-group">
                <label for="password2"> New Password Repeat</label>
                <div class="input-group">
                    <input class="form-control" placeholder="Repeat password" name="password2" value="" type="password">
                </div>
            </div>


            <div class="form-group">
                <label for="institution">Account State</label>

                <div class="radio-group">
                    <?php foreach (users::employee_states() as  $value) { ?>
                        <div class="form-check">
                            <input class="form-check-input" type="radio" name="state" id="state<?= $value["id"] ?>" value="<?= $value["id"] ?>" <?= $value["id"] == $user["state"] ? "checked" : "" ?> autofocus required>
                            <label class="form-check-label w-100" for="state<?= $value["id"] ?>">
                                <?= $value["name"] ?>
                            </label>
                        </div>

                    <?php }  ?>
                </div>

            </div>
        </div>

        <div class="text-primary text-lg my-3">Assigned Roles</div>

        <?php foreach (userroles::types() as $value) { ?>
            <div class="form-group">
                <div class="row">
                    <div class="col iconbox <?= (isset($user_id) && userroles::has_roleassigned($user_id, $value['id'])) ? "text-primary" : "text-muted" ?>">
                        <?= UI::icon("role") ?>
                    </div>
                    <div class="col">
                        <div class="text-strong"><?= $value['name'] ?> <span class="text-xs text-primary ms-2">#<?= $value['code'] ?></span> </div>
                        <div class="text-xs text-muted"><?= $value['text'] ?></div>
                    </div>
                    <div class="col switchbox">
                        <input type="checkbox" class="switch" id="state<?= $value['id'] ?>" name="state_<?= $value['id'] ?>" <?= (isset($user_id) && userroles::has_roleassigned($user_id, $value['id'])) ? "checked" : "" ?>>
                    </div>
                </div>

            </div>

        <?php } ?>

    </div>

    <div class="card-bottom">

        <div class="row">

            <div class="col-6">
                <button type="submit" class="btn btn-primary btn-block"> <?= isset($_GET["id"]) ? "Update" : "Create user account" ?> </button>
            </div>
            <div class="col-6">
                <a href="../../" class="btn btn-secondary btn-block"> Cancel </a>
            </div>
        </div>

    </div>

</form>

<script>
    $('form').submit(function() {
        $(".card-bottom").html(UI_loading);
    });

    $("#institution").chosen({
        no_results_text: "ගැලපෙන ආයතනයක් නොමැත ...."
    });

    function update_image(input) {

        if (input.files && input.files[0]) {
            var reader = new FileReader();
            reader.onload = function(e) {
                $('#profile_img').attr('src', e.target.result);
            }
            reader.readAsDataURL(input.files[0]);
        }
    }
</script>

<?php page::footer(); ?>