<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>
        Admin || <%= config.name %>
    </title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.4.0/font/bootstrap-icons.css">
    <link rel="stylesheet" href="https://unpkg.com/bootstrap-table@1.18.3/dist/bootstrap-table.min.css">
    <style>
        .fixed-table-body{
            height: auto !important;
        }
        *::-webkit-scrollbar {
        display: none;
        }

        /* Hide scrollbar for IE, Edge and Firefox */
        * {
        -ms-overflow-style: none;  /* IE and Edge */
        scrollbar-width: none;  /* Firefox */
        }
        .positionLabelTop{
            display: none;
        }
        .positionLabelLeft{
            display: inline;
        }
        .checkHeight{
            height: 75%;
        }
        @media only screen and (max-width: 576px) {
            .checkHeight{
                height: auto;
            }
            .positionLabelTop{
                display: inline;
            }
            .positionLabelLeft{
                display: none;
            }
        }
    </style>
    <%- include("./../components/head.ejs")%>
</head>

<body class="w-100 bg-light-light h-auto">
    <%- include("./../components/nav.ejs")%>
        <div class="w-100 content bg-light-light px-2 px-md-5 py-3" id="content">
            <h2 class="d-inline-block">Users</h2>
            <button class="btn btn-<%= config.other.navColor[2] %> d-inline-block ms-4 align-middle mb-2" type="button" data-bs-toggle="modal" data-bs-target="#exampleModal">New User</button>
            <div class="row w-100 mx-0 gy-2 gx-0 g-md-3 row-cols-md-2 row-cols-sm-1 checkHeight">
                <div class="col">
                    <div class="w-100 h-100 shadow p-2 rounded border border-secondary border-1">
                        
                        <table data-toggle="table" data-search="true" data-show-columns="true" id="mainTable">
                            <thead>
                                <tr class="tr-class-2">
                                    <th data-field="username">Username</th>
                                    <th data-field="rank">Rank</th>
                                    <th data-field="hours">Flight Hours</th>
                                    <th data-field="admin">Admin</th>
                                </tr>
                            </thead>
                            <tbody>
                                <% users.forEach(pilot=>{%>
                                    <tr id="tr-id-<%=pilot.username%>" class="tr-class-<%=pilot.username%> pirepClickable" data-title="<%=pilot.username%>"
                                        title="<%= pilot.username%>" data-object='{"key": "value"}' style="cursor: pointer;"
                                        onclick="openUser('<%=pilot.username%>')">
                                        <td id="td-id-<%=pilot.username %>" class="td-class-<%=pilot.username %>" data-title="<%= pilot.username%>">
                                            <strong>
                                                <%= config.code%><%= pilot.username%>
                                            </strong>
                                        </td>
                                        <td data-text="<%= pilot.rank %>">
                                            <%= pilot.rank %>
                                        </td>
                                        <td data-text="<%= pilot.hours %>">
                                            <%= pilot.hours %>
                                        </td>
                                        <td data-text="<%= (pilot.admin == 1 ? true : false)  ? "True" : "False" %>">
                                            <% if(pilot.admin) { %>
                                                <span class="badge bg-success">Yes</span>
                                            <%}else{%>
                                                <span class="badge bg-danger">No</span>
                                            <%}%>
                                        </td>
                                    </tr>
                                <%})%>
                            </tbody>
                        </table>
                    </div>
                </div>
                <div class="col">
                    <div class="w-100 h-100 shadow rounded border border-dark border-2 text-center" id="collectedUsers" style="overflow-y: scroll;">
                        <div id="userViewNUS" class="w-100 py-5">
                            <h1>Select a user on the <span class="positionLabelLeft">left</span><span class="positionLabelTop">top</span></h1>
                        </div>
                        <% users.forEach(pilot =>{%>
                            <div class="w-100 p-3 text-start d-none" id="pilot_display_<%=pilot.username%>">
                                <div class="w-100 text-center">
                                    <img src="<%= pilot.profileURL %>" class="w-100 mx-auto rounded" style="max-width: 50px;">
                                </div>
                                
                                <br>
                                <% if(pilot.admin==1){%>
                                    <span class="bg-success badge">Admin</span>
                                <%}%>
                                <% if(pilot.manualRank == 1){%>
                                    <span class="bg-primary badge">Manually Ranked</span>    
                                <%}%>
                                <% if(pilot.revoked == 1){%>
                                    <span class="bg-danger badge">Revoked</span>
                                <%}%>
                                <span class="bg-secondary badge"><%= pilot.rank%></span>
                                <br>
                                <h3 class="d-inline-block mt-2"><%=config.code + pilot.username%></h3>
                                <h6 class="ms-2 d-inline-block"><%= pilot.display%></h6>
                                <br>
                                <%if(pilot.revoked==1){%>
                                    <button type="button" class="btn btn-outline-primary" onclick="unrevokeUser('<%=pilot.username%>')">Unrevoke
                                        user</button>
                                        <br>
                                    <%}else if(user.username != pilot.username){%>
                                        <button type="button" class="btn btn-outline-danger" onclick="revokeUser('<%=pilot.username%>')">Revoke
                                            user</button>
                                        <button type="button" class="btn btn-outline-danger" onclick="resetPWD('<%=pilot.username%>')">Reset Password</button>
                                        <br>
                                    <%}%>
                                <br>
                                <h2>Data</h2>
                                <hr>
                                <div class="row gx-3 gy-2 row-cols-1 row-cols-md-2 row-cols-lg-3">
                                    <div class="col">
                                        <div class="shadow form-control p-3 text-center">
                                            <h4><%= pilot.hours%>hr</h4>
                                            <p class="mb-0"><i class="bi bi-clock"></i> Flight Hours</p>
                                        </div>
                                    </div>
                                    <div class="col">
                                        <div class="shadow form-control p-3 text-center">
                                            <h4>
                                                <%= pilot.rank%>
                                            </h4>
                                            <p class="mb-0"><i class="bi bi-person"></i> Rank</p>
                                        </div>
                                    </div>
                                    <div class="col">
                                        <div class="shadow form-control p-3 text-center">
                                            <h4>
                                                <%= new Date(pilot.llogin).toDateString() %>
                                            </h4>
                                            <p class="mb-0"><i class="bi bi-calendar"></i> Last Seen</p>
                                        </div>
                                    </div>
                                    <div class="col">
                                        <div class="shadow form-control p-3 text-center">
                                            <%if(pilot.revoked == 1){%>
                                                <h4 class="text-danger">User Revoked</h4>
                                            <%}else if(pilot.admin == 0){%>
                                                <h4>Normal User</h4>
                                            <%}else{%>
                                                <h4>Admin User</h4>
                                            <%}%>
                                            <p class="mb-0"><i class="bi bi-key"></i> Access</p>
                                        </div>
                                    </div>
                                </div>
                                <br><br>
                                <h2>Ranks</h2>
                                <hr>
                                <form class="form-control p-3" action="/admin/users/rankChange" method="POST">
                                    <input type="hidden" name="uid" value="<%= pilot.username%>">
                                    <div class="form-check mb-3 mt-1 text-start">
                                        <input class="form-check-input" type="checkbox" <% if(pilot.manualRank){%>checked=""<%}%> value="yespls" name="manual" id="manual">
                                        <label class="form-check-label" for="manual">
                                            Manual Rank Only
                                        </label>
                                    </div>
                                    <div class="mb-3 text-start">
                                        <label class="form-label">
                                            Set Rank
                                            <select class="form-select" name="rank">
                                                <% ranks.forEach(rank=>{%>
                                                    <option value="<%= rank.label%>">
                                                        <%= rank.label%>
                                                    </option>
                                                    <%})%>
                                            </select>
                                        </label>
                                        <p class="text-muted">This only has an effect if Manual Rank Only is turned on.</p>
                                    </div>
                                    <button class="btn btn-<%= config.other.navColor[2] %>">Create</button>
                                </form>
                                <h2>PIREPs</h2>
                                <hr>
                                <div class="table-responsive">
                                    <table data-toggle="table" data-search="true" data-show-columns="true" id="pirepTable_<%=pilot.username%>" class="table table-responsive table-striped">
                                        <thead>
                                            <tr class="tr-class-2">
                                                <th data-field="route">Route</th>
                                                <th data-field="Departure-Airport">Departure Airport</th>
                                                <th data-field="Arrival-Airport">Arrival Airport</th>
                                                <th data-field="aircraft">Aircraft</th>
                                                <th data-field="airline">Airline</th>
                                                <th data-field="state">State</th>
                                            </tr>
                                        </thead>
                                        <tbody id="tablefor_<%=pilot.username%>">
                                            <% pireps.forEach(pirep=>{%>
                                                <%if(pirep.author==pilot.username){%>
                                                    <tr id="pilot_<%=pilot.username%>_pirep_<%=pirep.id%>"
                                                        data-title="pilot_<%=pilot.username%>_pirep_<%=pirep.id%>"
                                                        title="pilot_<%=pilot.username%>_pirep_<%=pirep.id%>" data-object='{"key": "value"}'>
                                                        <td data-field="route">
                                                            <%=config.code%>
                                                                <%= pirep.route%>
                                                        </td>
                                                        <td data-field="Departure-Airport">
                                                            <%= pirep.depICAO%>
                                                        </td>
                                                        <td data-field="Arrival-Airport">
                                                            <%= pirep.arrICAO%>
                                                        </td>
                                                        <td data-field="aircraft">
                                                            <%= pirep.vehiclePublic%>
                                                        </td>
                                                        <td data-field="airline">
                                                            <%= pirep.airline%>
                                                        </td>
                                                        <td data-field="state">
                                                            <% if (pirep.status=='a' ){%>
                                                                <span class="badge bg-success">Accepted</span>
                                                                <%}else if(pirep.status=="d" ){%>
                                                                    <span class="badge bg-danger">Rejected</span></p>
                                                                    <%}else{%>
                                                                        <span class="badge bg-secondary">Awaiting</span>
                                                                        <%}%>
                                                        </td>
                                                    </tr>
                                                    <%}%>
                                                        <%})%>
                                        </tbody>
                                    </table>
                                </div>
                                
                            </div>
                        <%})%>
                    </div>
                </div>
            </div>
        </div>
        <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="exampleModalLabel">Add User</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <form method="POST" action="/admin/users/new" novalidate class="needs-validation">
                            <h2>Create new account</h2>
                            <br>
                            <div class="input-group mb-3">
                                <span class="input-group-text" id="basic-addon1">
                                    <%= config.code%>
                                </span>
                                <input type="text" class="form-control" placeholder="Username" aria-label="Username" required=""
                                    aria-describedby="basic-addon1" name="username">
                                <div class="valid-feedback">Good work!</div>
                                <div class="invalid-feedback">Needs a valid username!</div>
                            </div>
                            <div class="mb-3">
                                <label>Name:</label>
                                <input type="text" class="mt-1 form-control" placeholder="Name" required="" aria-label="Name"
                                    name="Name">
                                <div class="valid-feedback">Good work!</div>
                                <div class="invalid-feedback">Needs a valid name!</div>
                            </div>
                            <div class="mb-3">
                                <label>IFC Username:</label>
                                <input type="text" class="mt-1 form-control" placeholder="IFC Username" required=""
                                    aria-label="IFC" name="IFC">
                                <div class="valid-feedback">Good work!</div>
                                <div class="invalid-feedback">Needs a valid username!</div>
                                <p class="mt-2"><span class="text-danger fw-bold">CAUTION</span>: Please make sure the IFC Name
                                    is correct. It must be case correct!</p>
                            </div>
                            <div class="mb-3">
                                <label>Starting Hours:</label>
                                <input type="number" class="form-control mt-1" min="0" placeholder="Starting Hours" required=""
                                    aria-label="hours" name="hours">
                                <div class="valid-feedback">Good work!</div>
                                <div class="invalid-feedback">Needs a valid number!</div>
                            </div>
                            <div class="mb-3">
                                <label>Starting Password:</label>
                                <input type="password" class="form-control mt-1" placeholder="Password" required=""
                                    aria-label="Password" aria-describedby="basic-addon1" name="password">
                                <div class="valid-feedback">Good work!</div>
                                <div class="invalid-feedback">Needs a valid password!</div>
                            </div>
                            <div class="form-check mt-1 text-start">
                                <input class="form-check-input" type="checkbox" value="yespls" name="manual" id="manual">
                                <label class="form-check-label" for="manual">
                                    Manual Rank Only
                                </label>
                            </div>
                            <p class="text-muted">This means that the user can only have their rank change by it being manually updated via the users page.</p>
                            <div class="form-check mt-1 text-start">
                                <input class="form-check-input" type="checkbox" value="yespls" checked="" disabled="" name="CPW"
                                    id="CPWCheck">
                                <label class="form-check-label" for="flexCheckDefault">
                                    Require Password Change on login
                                </label>
                            </div>
                            <div class="form-check mt-3 text-start">
                                <input class="form-check-input" type="checkbox" value="true" name="admin" id="flexCheckDefault">
                                <label class="form-check-label" for="flexCheckDefault">
                                    Admin
                                </label>
                                <p><strong>CAREFUL:</strong> This is a dangerous permission to grant.</p>
                            </div>
                            <button class="btn btn-<%= config.other.navColor[2] %>">Create</button>
                        </form>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    </div>
                </div>
            </div>
        </div>
        <%- include('./../components/footer.ejs') %>
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/js/bootstrap.bundle.min.js"
            integrity="sha384-JEW9xMcG8R+pH31jmWH6WWP0WintQrMb4s7ZOdauHnUtxwoG2vI5DkLtS3qm9Ekf"
            crossorigin="anonymous"></script>
        <script src="https://code.jquery.com/jquery-3.6.0.min.js"
            integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
        <script src="https://unpkg.com/bootstrap-table@1.18.3/dist/bootstrap-table.min.js"></script>
        <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
        <script>
            $('#mainTable').on('click-row.bs.table', function (row, el, field){
                openUser(el._id.split("-")[2])
            })
            function openUser(username){
                const collection = document.getElementById("collectedUsers").children;
                collection.forEach(item =>{
                    item.classList.add('d-none');
                })
                //document.getElementById(`countfor_${username}`).innerHTML = document.getElementById(`tablefor_${username}`).childElementCount;
                document.getElementById(`pilot_display_${username}`).classList.remove('d-none');
                document.getElementById(`pilot_display_${username}`).scrollIntoView();
            }
            function revokeUser(user) {
                    const data = `uid=${encodeURIComponent(user)}`;
                    const xhr = new XMLHttpRequest();
                    xhr.withCredentials = true;
                    xhr.open("POST", "/admin/users/revoke");
                    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                    xhr.send(data);
                    setTimeout(() => {
                        window.location.reload();
                    }, 1500);
                }
            function unrevokeUser(user) {
                    const data = `uid=${encodeURIComponent(user)}`;
                    const xhr = new XMLHttpRequest();
                    xhr.withCredentials = true;
                    xhr.open("POST", "/admin/users/unrevoke");
                    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                    xhr.send(data);
                    setTimeout(() => {
                        window.location.reload();
                    }, 1500);
                }
            function makeid(length) {
                    var text = "";
                    var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

                    for (var i = 0; i < length; i++) {
                        text += possible.charAt(Math.floor(Math.random() * possible.length));
                    }

                    return text;
                }
            function resetPWD(user){
                const newPWD = makeid(10);
                swal("Are you sure?", `Are you sure you want to reset <%=config.code%>${user}'s password?`, 'info').then(result =>{
                    if(result){
                        const data = `uid=${encodeURIComponent(user)}&newpwd=${encodeURIComponent(newPWD)}`;
                        const xhr = new XMLHttpRequest();
                        xhr.withCredentials = true;
                        xhr.open("POST", "/admin/users/resetPWD");
                        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                        xhr.send(data);
                        xhr.addEventListener("readystatechange", function () {
                            if (this.readyState === this.DONE) {
                                if(this.status == 200){
                                    swal("Password reset", `<%=config.code%>${user}'s password has been reset to ${newPWD}`, 'info').then(() => {
                                        window.location.reload();
                                    });
                                }else{
                                    swal("Error", `There was an error resetting the password (${this.status})`, 'error')
                                }
                            }
                        });
                        
                        
                    }   
                })
            }
        </script>
        
        
</body>

</html>