<%- await include('parts/header.ejs', locals) %>

<style>
    .pInfoCallout{
        min-width: 180px !important;
        margin-bottom: .5rem;
    }
    .pInfoCallout .c-callout{
        padding-bottom: 2px;
    }
    .pInfoCallout small{
        letter-spacing: .04em;
    }

    .searchTab{
        min-height: 64px;
    }

    .c-callout{
        margin: 0;
    }
</style>


<!-- Callouts -->
<div class="row justify-content-center">
    <div class="row col-xl-10 p-0 pb-3 justify-content-center">
        <div class="col-2 pInfoCallout">
            <div class="c-callout c-callout-info">
                <small class="text-muted">Total Players</small><br>
                <strong class="h4"><%= stats.players %></strong>
            </div>
        </div>
        <div class="col-2 pInfoCallout">
            <div class="c-callout c-callout-info">
                <small class="text-muted">Total Playtime</small><br>
                <strong class="h4"><%= stats.playTime %></strong>
            </div>
        </div>
        <!-- <div class="col-2 pInfoCallout">
            <div class="c-callout c-callout-success">
                <small class="text-muted">New Players This Week</small><br>
                <strong class="h4">9,123</strong>
            </div>
        </div>
        <div class="col-2 pInfoCallout">
            <div class="c-callout c-callout-success">
                <small class="text-muted">Playtime This Week</small><br>
                <strong class="h4">9,123</strong>
            </div>
        </div> -->
        <div class="col-2 pInfoCallout">
            <div class="c-callout c-callout-success">
                <small class="text-muted">Whitelists</small><br>
                <strong class="h4"><%= stats.whitelists %></strong>
            </div>
        </div>
        <div class="col-2 pInfoCallout">
            <div class="c-callout c-callout-warning">
                <small class="text-muted">Warns</small><br>
                <strong class="h4"><%= stats.warns %></strong>
            </div>
        </div>
        <div class="col-2 pInfoCallout">
            <div class="c-callout c-callout-danger">
                <small class="text-muted">Bans</small><br>
                <strong class="h4"><%= stats.bans %></strong>
            </div>
        </div>
    </div>
</div>


<!-- Main info -->
<div class="row justify-content-center">

    <div class="col-md-10 col-lg-8 col-xl-5 mw-col6">

        <!-- Ban ID -->
        <div class="card card-accent-danger">
            <div class="card-header font-weight-bold">Ban Identifiers:</div>
            <div class="card-body">
                <% if (disableBans) { %>
                    <div class="text-center">
                        <h3 class="mx-auto pt-3 text-danger">ban checking disabled</h3>
                    </div>
                <% } else { %>
                    <% if (permsDisable.ban) { %>
                        <div class="text-center">
                            <h3 class="mx-auto pt-3 text-secondary">you can't ban people</h3>
                        </div>
                    <% } else { %>
                        <div class="form-group row">
                            <label for="frmAddBan-identifiers" class="col-sm-3 col-form-label">
                                Identifier(s) <br>
                                <small class="text-danger">(required)</small>
                            </label>
                            <div class="col-sm-9">
                                <input type="text" class="form-control" id="frmAddBan-identifiers"
                                    placeholder="steam:101010101010101, license:d3832ddc9f845bf...">
                                <span class="form-text text-muted">
                                    Valid identifiers: <code>steam, license, xbl, live, discord, fivem</code>.
                                    You can insert multiple IDs separated by comma.
                                </span>
                            </div>
                        </div>

                        <div class="form-group row">
                            <label for="frmAddBan-reason" class="col-sm-3 col-form-label">
                                Reason <br>
                                <small class="text-danger">(required)</small>
                            </label>
                            <div class="col-sm-9">
                                <input type="text" class="form-control" id="frmAddBan-reason" maxlength="256"
                                    placeholder="doing bad things :(">
                            </div>
                        </div>

                        <div class="form-group row">
                            <label for="frmAddBan-durationSelect" class="col-sm-3 col-form-label">
                                Duration
                            </label>
                            <div class="col-sm-9">
                                <select class="form-control" id="frmAddBan-durationSelect">
                                    <option value="2 hours">2 hours</option>
                                    <option value="8 hours">8 hours</option>
                                    <option value="1 day">1 day</option>
                                    <option value="2 days">2 days</option>
                                    <option value="1 week">1 week</option>
                                    <option value="2 weeks">2 weeks</option>
                                    <option value="permanent" class="font-weight-bold text-danger" selected>permanent</option>
                                    <option value="custom" class="font-weight-bold">custom</option>
                                </select>
                                <div class="row mt-2">
                                    <div class="col-sm-3 pr-0">
                                        <input type="number" class="form-control" id="frmAddBan-durationMultiplier" 
                                            maxlength="3" placeholder="7" disabled>
                                    </div>
                                    <div class="col-sm-9 pl-2">
                                        <select class="form-control" id="frmAddBan-durationUnit" disabled>
                                            <option value="hours">hours</option>
                                            <option value="days">days</option>
                                            <option value="weeks" selected>weeks</option>
                                            <option value="months">months</option>
                                        </select>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="text-center mt-4">
                            <button class="btn btn-sm btn-danger" type="submit" id="frmAddBan-button">
                                <i class="icons cui-check"></i> Ban Identifiers
                            </button>
                        </div>
                    <% } %>
                <% } %>
            </div>
        </div>
        <!-- /Ban ID -->

        <div class="text-center">
            <small class="text-muted"><%- message %></small>
        </div>

    </div>



    <div class="col-md-10 col-lg-8 col-xl-5 mw-col8">
        
        <!-- Search + List Card -->
        <div class="card">
            <div class="card-header card-accent-info">
                <ul class="nav nav-pills card-header-pills">
                    <div class="form-group row mb-0 mr-auto">
                        <div class="col-md-12">
                            <div class="input-group">
                                <input class="form-control" id="dbSearch-input" type="text"
                                    placeholder="name, license, IDs">
                                <span class="input-group-append">
                                    <button class="btn btn-sm btn-secondary" type="button" id="dbSearch-button">
                                        <svg class="c-icon">
                                            <use href="img/coreui_icons.svg#cil-magnifying-glass"></use>
                                        </svg> Search
                                    </button>
                                </span>
                            </div>
                        </div>
                    </div>
                    <li class="nav-item">
                        <a class="nav-link" id="dbPlayers-tab" data-toggle="pill" href="#dbPlayers-content" role="tab" 
                            aria-controls="dbPlayers-content" aria-selected="false"><i class="icon-user"></i> Players</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link active" id="dbActions-tab" data-toggle="pill" href="#dbActions-content" role="tab" 
                            aria-controls="dbActions-content" aria-selected="true"><i class="icon-notebook"></i> Actions</a>
                    </li>
                </ul>
            </div>
            <div class="card-body">
                <div class="tab-content">
                    <h5 class="text-center text-primary mb-2" id="dbSearch-message"></h5>
                    <div class="tab-pane fade" id="dbPlayers-content" role="tabpanel" aria-labelledby="dbPlayers-tab">
                        <div id="dbPlayers-tabSearch" class="searchTab d-none"></div>
                        <div id="dbPlayers-tabDefault">
                            <h5 class="card-title">Last <%= queryLimits.players %> joined players</h5>
                            <% if (!lastPlayers.length) { %>
                                <div class="text-center">
                                    <h3 class="mx-auto pt-3 text-secondary">no players yet...</h3>
                                </div>
                            <% } else { %>
                                <div class="list-group list-group-accent">
                                    <% for (const player of lastPlayers) { %>
                                        <!-- FIXME: fix logEntryClickableX and onclickX-->
                                        <div class="list-group-item list-group-item-accent-<%= player.color %> logEntry logEntryClickable">
                                            <div class="d-flex w-100 justify-content-between" onclick="showPlayerByLicense('<%= player.license %>')">
                                                <strong class="overflow-hidden"><%= player.name %></strong>
                                                <small><%= player.joined %></small>
                                            </div>
                                        </div>
                                    <% } %>
                                </div>
                            <% } %>
                        </div>
                    </div>

                    <div class="tab-pane fade show active" id="dbActions-content" role="tabpanel" aria-labelledby="dbActions-tab">
                        <div id="dbActions-tabSearch" class="searchTab d-none"></div>
                        <div id="dbActions-tabDefault">
                            <h5 class="card-title">Last <%= queryLimits.actions %> actions (bans/warns):</h5> 
                            <% if (!lastActions.length) { %>
                                <div class="text-center">
                                    <h3 class="mx-auto pt-3 text-secondary">no actions yet...</h3>
                                </div>
                            <% } else { %>
                                <div class="list-group list-group-accent">
                                    <% for (const action of lastActions) { %>
                                        <div class="list-group-item list-group-item-accent-<%= action.color %> logEntry">
                                            <div class="d-flex w-100 justify-content-between">
                                                <strong><%- action.message %></strong>
                                                <small class="text-right">
                                                    <span class="text-monospace font-weight-bold">(<%= action.id %>)</span>
                                                    <%= action.date %>
                                                    <% if (!permsDisable.ban) { %>
                                                        <% if (
                                                            action.isRevoked ||
                                                            (action.type === 'warn' && permsDisable.warn) ||
                                                            (action.type === 'ban' && permsDisable.ban)
                                                        ) { %>
                                                            &nbsp;
                                                            <span class="badge badge-outline-light txInlineBtn txActionsBtn">REVOKE</span>
                                                        <% } else { %>
                                                            &nbsp;
                                                            <button onclick="revokeAction('<%= action.id %>')" 
                                                                class="btn btn-secondary txInlineBtn txActionsBtn">REVOKE</button>
                                                        <% } %>
                                                    <% } %>
                                                </small>
                                            </div>
                                            <span><%= action.reason || "" %></span>
                                            <% if (action.footerNote) { %>
                                                <small class="d-block"><%= action.footerNote %></small>
                                            <% } %>
                                        </div>
                                    <% } %>
                                </div>
                            <% } %>
                            <%# End actions list %>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <!-- /Tabbed Card -->


    </div>
</div>


<%- await include('parts/footer.ejs', locals) %>


<script>
    //============================================== SSR Variables
    const permsDisableBan = ('<%= permsDisable.ban %>' === 'true');
    const permsDisableWarn = ('<%= permsDisable.warn %>' === 'true');

    //============================================== Search functionality
    const getSVG = (icon) => {
        return `<svg class="c-icon">
            <use href="img/coreui_icons.svg#cil-${icon}"></use>
        </svg>`;
    }
    const searchInput = document.getElementById('dbSearch-input');
    const searchButton = document.getElementById('dbSearch-button');
    const searchMessage = document.getElementById('dbSearch-message');
    const dbPlayersTab = document.getElementById('dbPlayers-tab');
    const dbPlayersContent = document.getElementById('dbPlayers-content');
    const dbPlayersSearchTab = document.getElementById('dbPlayers-tabSearch');
    const dbPlayersDefaultTab = document.getElementById('dbPlayers-tabDefault');
    const dbActionsTab = document.getElementById('dbActions-tab');
    const dbActionsContent = document.getElementById('dbActions-content');
    const dbActionsSearchTab = document.getElementById('dbActions-tabSearch');
    const dbActionsDefaultTab = document.getElementById('dbActions-tabDefault');

    searchButton.addEventListener('click', (e) => {
        if(searchButton.textContent.includes('Search')){
            performSearch();
        }else{
            clearSearch();
        }
    })
    searchInput.addEventListener('keyup', (e) => {
        if(e.keyCode !== 13){
            if(!searchButton.innerHTML.includes('magnifying-glass')){
                searchButton.innerHTML = getSVG('magnifying-glass') + ` Search`;
            }
        }else{
            if(searchInput.value.length){
                performSearch();
            }else{
                clearSearch();
            }
        }
    })

    //Clear search
    function clearSearch(){
        dbPlayersSearchTab.classList.add('d-none');
        dbPlayersDefaultTab.classList.remove('d-none');
        dbActionsSearchTab.classList.add('d-none');
        dbActionsDefaultTab.classList.remove('d-none');
        searchButton.innerHTML = getSVG('magnifying-glass') + ` Search`;
        searchInput.value = '';
        searchMessage.innerText = '';
        location.hash = '';
    }

    //Perform search
    function performSearch(){
        const searchString = searchInput.value.trim();
        location.hash = encodeURI(searchString);
        if(!searchString.length) return clearSearch();
        dbPlayersSearchTab.innerHTML = SPINNER_HTML;
        dbActionsSearchTab.innerHTML = SPINNER_HTML;
        dbPlayersSearchTab.classList.remove('d-none');
        dbPlayersDefaultTab.classList.add('d-none');
        dbActionsSearchTab.classList.remove('d-none');
        dbActionsDefaultTab.classList.add('d-none');
        searchButton.innerHTML = getSVG('x') + ` Clear`;
        searchMessage.innerText = '';

        txAdminAPI({
            type: "GET",
            url: '/player/search?query=' + encodeURI(searchString),
            timeout: REQ_TIMEOUT_LONG,
            success: function (data) {
                if(data.error){
                    dbPlayersSearchTab.innerText = error;
                    dbActionsSearchTab.innerText = error;
                    return;
                }
                searchMessage.innerText = data.message;
                dbPlayersSearchTab.innerHTML = dbPlayersToHtmlList(data.resPlayers);
                dbActionsSearchTab.innerHTML = dbActionsToHtmlListOld(data.resActions, permsDisableWarn, permsDisableBan);
                if(data.resPlayers.length && !data.resActions.length){
                    dbActionsTab.classList.remove('active');
                    dbActionsContent.classList.remove('show', 'active');
                    dbPlayersTab.classList.add('active');
                    dbPlayersContent.classList.add('show', 'active');
                }else if(data.resActions.length && !data.resPlayers.length){
                    dbPlayersTab.classList.remove('active');
                    dbPlayersContent.classList.remove('show', 'active');
                    dbActionsTab.classList.add('active');
                    dbActionsContent.classList.add('show', 'active');
                }
            },
            error: function (xmlhttprequest, textstatus, message) {
                dbPlayersSearchTab.innerText = message;
                dbActionsSearchTab.innerText = message;
            }
        });
    }

    //Converts players array to html
    function dbPlayersToHtmlList(players){
        if(!players.length){
            return `<div class="text-center">
                <h3 class="mx-auto pt-3 text-secondary">no players found</h3>
            </div>`;
        }else{
            const processed = players.map(p => `
                <div class="list-group-item list-group-item-accent-${xss(p.color)} logEntry logEntryClickable">
                    <div class="d-flex w-100 justify-content-between" onclick="showPlayerByLicense('${xss(p.license)}')"> 
                        <strong>${xss(p.name)}</strong>
                        <small>${xss(p.joined)}</small>
                    </div>
                </div>`);
            
            return [
                `<div class="list-group list-group-accent">`,
                ...processed,
                `</div>`
            ].join('\n');
        }
    }

    //Converts actions array to html
    function dbActionsToHtmlListOld(actions, _permsDisableWarn, _permsDisableBan){
        if(!actions.length){
            return `<div class="text-center">
                <h3 class="mx-auto pt-3 text-secondary">no actions found</h3>
            </div>`;
        }else{
            const processed = actions.map(a => {
                let revokeButton = '';
                if(!permsDisableBan){
                    if(
                        a.isRevoked ||
                        (a.type == 'warn' && permsDisableWarn) ||
                        (a.type == 'ban' && permsDisableBan)
                    ){
                        revokeButton = `&nbsp;<span class="badge badge-outline-light txInlineBtn txActionsBtn">REVOKE</span>`; 
                    }else{
                        revokeButton = `&nbsp;<button onclick="revokeAction('${xss(a.id)}')" 
                                class="btn btn-secondary txInlineBtn txActionsBtn">REVOKE</button>`; 
                    }
                }
                const reason = (a.reason !== null)? xss(a.reason) : '';
                const footerNote = (a.footerNote)? `<small class="d-block">${xss(a.footerNote)}</small>` : '';
                return `<div class="list-group-item list-group-item-accent-${xss(a.color)} logEntry">
                    <div class="d-flex w-100 justify-content-between">
                        <strong>${a.message}</strong>
                        <small class="text-right">
                            <span class="text-monospace font-weight-bold">(${xss(a.id)})</span>
                            ${xss(a.date)}
                            ${revokeButton}
                        </small>
                    </div>
                    <span>${reason}</span>
                    ${footerNote}
                </div>`;
            });
            
            return [
                `<div class="list-group list-group-accent">`,
                ...processed,
                `</div>`
            ].join('\n');
        }
    }

    //Performs auto-search
    const urlHash = decodeURI(location.hash.substr(1).trim());
    if(urlHash.length){
        searchInput.value = urlHash;
        performSearch();
    }

    

    //============================================== Ban card
    const banCard = {
        identifiers: document.getElementById("frmAddBan-identifiers"),
        reason: document.getElementById("frmAddBan-reason"),
        durationSelect: document.getElementById("frmAddBan-durationSelect"),
        durationMultiplier: document.getElementById("frmAddBan-durationMultiplier"),
        durationUnit: document.getElementById("frmAddBan-durationUnit"),
        button: document.getElementById('frmAddBan-button'),
    }

    banCard.durationSelect.onchange = () => {
        const isDefault = (banCard.durationSelect.value !== 'custom');
        banCard.durationMultiplier.disabled = isDefault;
        banCard.durationUnit.disabled = isDefault;
    }

    banCard.button.onclick = () => {
        const frmIdentifiers = banCard.identifiers.value.trim();
        const reason = banCard.reason.value.trim();
        const data = {
            reason,
            duration: banCard.durationSelect.value === 'custom' ?
                `${banCard.durationMultiplier.value} ${banCard.durationUnit.value}` :
                banCard.durationSelect.value
        };

        if (!frmIdentifiers.length || !data.reason.length) {
            const notify = $.notify({ message: 'The identifiers and reason fields are required.' }, { type: 'warning' });
            return;
        }
        if (data.reason.length < 3) {
            const notify = $.notify({ message: 'The reason must be at least 3 characters.' }, { type: 'warning' });
            return;
        }
        data.identifiers = frmIdentifiers.split(/[,;'"\s]+/).filter(x => x.length);
        const notify = $.notify({ message: '<p class="text-center">Banning...</p>' }, {});

        txAdminAPI({
            type: "POST",
            url: '/database/ban_ids',
            timeout: REQ_TIMEOUT_LONG,
            data,
            success: function (data) {
                if (checkApiLogoutRefresh(data)) return;
                notify.update('progress', 0);
                if (data.success === true) {
                    notify.update('type', 'success');
                    notify.update('message', 'Player banned.');
                    banCard.identifiers.value = '';
                    banCard.reason.value = '';
                } else {
                    notify.update('type', 'danger');
                    notify.update('message', data.error || 'unknown error');
                }
            },
            error: function (xmlhttprequest, textstatus, message) {
                notify.update('progress', 0);
                notify.update('type', 'danger');
                notify.update('message', message);
            }
        });
    }
</script>
