require("luamods/db")
require("luamods/cgi")
require("luamods/layout")

userLevel = db.getPriv(layout.username) or 1

if (userLevel == 1) then
    buttonControl = " disabled"
    inputControl = " readonly"
else
    buttonControl = ""
    inputControl = ""
end

validUser = 0

if cgi.post.username ~= nil then
    username = cgi.post.username
else    
    username = cgi.get.username or ""
end

if (username ~= "") then
    user = db.getUserDetails(username)
    if (user ~= nil) then
        validUser = 1
    end
end

header = layout.getHeader()
footer = layout.getFooter()

userstb = db.getusers()

content = [[
                    <div id="info">
                        <div style="background:url(images/users.png); background-size:32px; background-repeat:no-repeat; background-position: 20px center;">
                            <center><h1>Users - Edit Account</h1></center>
                        </div>
                    </div>
]]

if (validUser == 0) then
    -- Bail on error
    content = content .. [[
                    <div id="info">
                        <center>
                            <h2><img src="images/warning.png"/> Unknown user</h2>
                            The specified user does not exist in the database.
                            <br><br>
                            <a href="users_manage.lua">Back to user accounts</a>
                        </center>
                    </div>
]]
    print(header..content..footer)
    return 
end

function getAdminCount()
    adminCount = 0
    users = db.getusers()
    if (users ~= nil) then
        for idx, usr in pairs(users) do
            if (usr.priv == 0) then
                adminCount = adminCount + 1
            end
        end
    end
    return adminCount
end

if (cgi.post.saveButton == "Save Changes") and (userLevel ~= 1) then
    pass1 = cgi.post.newPass1 or ""
    pass2 = cgi.post.newPass2 or ""
    if (pass1 ~= "") or (pass2 ~= "") then
        if (pass1 == pass2) then
            db.changePassword(username, pass1)
            saved = 1
        else
            -- Do fuckall? We received invalid form submission
        end
    end
    newPriv = tonumber(cgi.post.newPriv)
    if (newPriv == 0) or (newPriv == 1) or (newPriv == 2) then
        if (db.getPriv(username) == 0) and (newPriv == 1) and (getAdminCount() == 1) then
            message = [[<img src="images/warning.png"/> You cannot demote the last administrator account to a guest account.]]
        elseif (db.getPriv(username) == 0) and (newPriv == 2) and (getAdminCount() == 1) then
            message = [[<img src="images/warning.png"/> You cannot change the last administrator account to a developer account.]]
        else
            db.changePriv(username, newPriv)
            user.priv = newPriv
            message = [[<img src="images/ok.png"/> Changes saved.]]
        end
    else
        -- Do fuckall? We received invalid form submission
    end
end

if (cgi.post.deleteButton == "Delete User") and (userLevel ~= 1) then
    if (db.getPriv(username) == 0) and (getAdminCount() == 1) then
        message = [[<img src="images/warning.png"/> You cannot delete the last administrator account.]]
    else
        db.removeUser(username)
        -- Did you delete yourself?
        if (username == layout.username) then
            headerpath = "Set-Cookie: userID=deleted;Expires=Thu, 01-Jan-1970 00:00:01 GMT;\n"
            headerpath = headerpath.."Set-Cookie: sessionID=0;Expires=Thu, 01-Jan-1970 00:00:01 GMT;\n"
            headerpath = headerpath.."Location: index.lua\n\n"
            print(headerpath)
            exit(0)
        end
        content = content .. [[
                    <div id="info">
                        <center>
                            <h2>User deleted</h2>
                            <b>The user "]]..username..[[" has been deleted.</b><br><br>
                            <a href="users_manage.lua">Back to user accounts</a>
                        </center>
                    </div>
]]
        print(header..content..footer)
        exit(0)
    end
end

if (userLevel == 1) then
    content = content .. [[
                    <center><b>Note:</b> Editing this section requires administrator privileges.</center><br>
]]
end
content = content .. [[
                    <script>
                        function validateForm(f)
                        {
                            if (f.getAttribute('submitted')) return false;

                            errorstring = "";

                            if ((document.form1.newPass1.value != "") || (document.form1.newPass2.value != ""))
                            {
                                if (document.form1.newPass1.value != document.form1.newPass2.value)
                                {
                                    errorstring += "* Passwords do not match\n";
                                }
                                else if (document.form1.newPass1.value == "")
                                {
                                    errorstring += "* Password cannot be blank\n";
                                }
                                else if (document.form1.newPass1.value.length < 5)
                                {
                                    errorstring += "* Password needs to be at least 5 characters\n";
                                }
                            }

                            if (errorstring != "")
                            {
                                errorstring = "The following errors were detected: \n\n" + errorstring;alert(errorstring);
                                return false;
                            }

                            f.setAttribute('submitted','true');
                        }
                    </script>
                    
                    <h3>Editing user "]]..username..[["</h3>
                    <div class="formLayoutfull">
                        <form action="users_edit.lua" method="post" onsubmit="return validateForm(this)" name="form1">
                            <h3>Password settings</h3>
                            Leave these fields blank to keep the password unchanged.
                            <ul>
                                <li>
                                    <label style="display: inline-block; width: 250px;">New password: </label>
                                    <input type="password" name="newPass1" value=""]]..inputControl..[[/>
                                </li>
                                <li>
                                    <label style="display: inline-block; width: 250px;">Confirm new password: </label>
                                    <input type="password" name="newPass2" value=""]]..inputControl..[[/>
                                </li>
                            </ul>
                            <hr>
                            <h3>User privileges</h3>
                            Administrator accounts have full access to all configurable options.<br>
                            Guest accounts can view the current configuration but cannot change anything.<br>
                            Developer accounts are the same as administrators, but also see debugging information.
                            <ul>
                                <li>
                                    <label style="display: inline-block; width: 250px;">User type: </label>
                                    <select ]]..buttonControl..[[ name="newPriv">
]]
if user.priv == 1 then 
    content = content .. [[
                                        <option value="0">Administrator</option>
                                        <option value="1" selected>Guest</option>
                                        <option value="2">Developer</option>
]]
elseif user.priv == 0 then
    content = content .. [[
                                        <option value="0" selected>Administrator</option>
                                        <option value="1">Guest</option>
                                        <option value="2">Developer</option>
]]
else
    content = content .. [[
                                        <option value="0">Administrator</option>
                                        <option value="1">Guest</option>
                                        <option value="2" selected>Developer</option>
]]
end

content = content ..[[
                                    </select>
                                </li>
                            </ul>
                            <hr>
                            <br>
]]
if (message ~= nil) then
    content = content .. [[
                            <b>]]..message..[[</b><br><br>
]]                            
end
content = content .. [[
                            <input type="button" value="Back to Users" onclick="window.location.assign('users_manage.lua');"/> 
                            <input type="submit" name="saveButton" value="Save Changes"]]..buttonControl..[[/> 
                            <input type="submit" name="deleteButton" value="Delete User"]]..buttonControl..[[ onclick="return confirm('Are you sure you want to delete this user\'s account?')";/>
                            <input type="hidden" name="username" value="]]..username..[["/>
                        </form>
                    </div>
]]    

print (header..content..footer)
