<?php
// Account Suspensions admin page.
// Root-only. Manage account-level suspend/resume with cascade to all sites.
// Registered in $allowed_pages, $root_only_pages, and permission_manager.php.

require_once('/docker/whp/web/libs/permission_checker.php');
require_once('/docker/whp/web/libs/account_disable.php');

if (!is_root_user()) {
    http_response_code(403);
    echo '<div class="alert alert-danger"><i class="fa fa-lock me-2"></i>Access denied: root only.</div>';
    return;
}

$csrf_token = $_SESSION['csrf_token'] ?? '';
$disabled_accounts = list_disabled_accounts();
?>

<div class="row">
    <!-- Card 1: Currently suspended accounts -->
    <div class="col-12 mb-4">
        <div class="card">
            <div class="card-header d-flex align-items-center justify-content-between">
                <span><i class="fa fa-ban me-2"></i>Currently Suspended Accounts</span>
                <span class="badge bg-<?php echo empty($disabled_accounts) ? 'secondary' : 'danger'; ?>">
                    <?php echo count($disabled_accounts); ?> suspended
                </span>
            </div>
            <div class="card-body p-0">
                <?php if (empty($disabled_accounts)): ?>
                <div class="p-3 text-muted">(none)</div>
                <?php else: ?>
                <div class="table-responsive">
                    <table class="table table-sm table-hover mb-0" id="suspended-accounts-table">
                        <thead>
                            <tr>
                                <th>Username</th>
                                <th>Reason</th>
                                <th>Disabled At</th>
                                <th>Disabled By</th>
                                <th>Note</th>
                                <th></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($disabled_accounts as $row): ?>
                            <tr data-username="<?php echo htmlspecialchars($row['username']); ?>">
                                <td><strong><?php echo htmlspecialchars($row['username']); ?></strong></td>
                                <td><span class="badge bg-warning text-dark"><?php echo htmlspecialchars($row['reason']); ?></span></td>
                                <td><?php echo htmlspecialchars($row['disabled_at']); ?></td>
                                <td><?php echo htmlspecialchars($row['disabled_by']); ?></td>
                                <td><?php echo htmlspecialchars((string)($row['note'] ?? '')); ?></td>
                                <td>
                                    <button type="button"
                                            class="btn btn-sm btn-success btn-enable-account"
                                            data-username="<?php echo htmlspecialchars($row['username']); ?>">
                                        <i class="fa fa-check-circle me-1"></i>Enable
                                    </button>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- Card 2: Search accounts -->
    <div class="col-12">
        <div class="card">
            <div class="card-header">
                <i class="fa fa-search me-2"></i>Search Accounts
            </div>
            <div class="card-body">
                <div class="mb-3">
                    <input type="text"
                           id="account-search-input"
                           class="form-control"
                           placeholder="Search by username or domain..."
                           autocomplete="off">
                </div>
                <div id="account-search-results"></div>
            </div>
        </div>
    </div>
</div>

<!-- Disable Account Modal -->
<div class="modal fade" id="disableAccountModal" tabindex="-1" aria-labelledby="disableAccountModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="disableAccountModalLabel">
                    <i class="fa fa-ban me-2"></i>Disable Account
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <p>Disabling account <strong id="disable-modal-username"></strong> will stop all of its sites and route them to the suspended page.</p>
                <div class="mb-3">
                    <label class="form-label" for="disable-reason">Reason <span class="text-danger">*</span></label>
                    <select class="form-select" id="disable-reason" required>
                        <option value="">-- select --</option>
                        <option value="unpaid">Unpaid</option>
                        <option value="tos_violation">TOS Violation</option>
                        <option value="maintenance">Maintenance</option>
                        <option value="admin_other">Admin Other</option>
                    </select>
                </div>
                <div class="mb-3">
                    <label class="form-label" for="disable-note">Note (optional)</label>
                    <textarea class="form-control" id="disable-note" rows="2" placeholder="Internal note..."></textarea>
                </div>
                <div id="disable-account-error" class="alert alert-danger d-none"></div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-danger" id="disable-account-confirm">
                    <i class="fa fa-ban me-1"></i>Disable Account
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Confirm Enable Modal -->
<div class="modal fade" id="enableAccountModal" tabindex="-1" aria-labelledby="enableAccountModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="enableAccountModalLabel">
                    <i class="fa fa-check-circle me-2"></i>Enable Account
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <p>Re-enable account <strong id="enable-modal-username"></strong> and restart all its sites?</p>
                <div id="enable-account-error" class="alert alert-danger d-none"></div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-success" id="enable-account-confirm">
                    <i class="fa fa-check-circle me-1"></i>Enable Account
                </button>
            </div>
        </div>
    </div>
</div>

<script>
// Wrap in DOMContentLoaded: this inline script runs before bootstrap.bundle.js
// (loaded in the footer), so referencing `bootstrap.Modal` at parse time threw
// "bootstrap is not defined" and aborted the whole script — leaving every button
// (disable/enable/search) unwired. DOMContentLoaded fires after the footer scripts.
document.addEventListener('DOMContentLoaded', function () {
    var csrfToken = <?php echo json_encode($csrf_token); ?>;

    // ------------------------------------------------------------------ //
    // Utility: escape HTML for safe DOM insertion                         //
    // ------------------------------------------------------------------ //
    function escHtml(s) {
        return String(s)
            .replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#39;');
    }

    // ------------------------------------------------------------------ //
    // Search (debounced 300 ms)                                           //
    // ------------------------------------------------------------------ //
    var searchTimer  = null;
    var searchInput  = document.getElementById('account-search-input');
    var searchResult = document.getElementById('account-search-results');

    function renderSearchResults(results) {
        if (!results || results.length === 0) {
            searchResult.textContent = 'No accounts found.';
            return;
        }

        var table = document.createElement('table');
        table.className = 'table table-sm table-hover mb-0';

        var thead = document.createElement('thead');
        thead.innerHTML = '<tr><th>Username</th><th>Domains</th><th>Sites</th><th>Status</th><th></th></tr>';
        table.appendChild(thead);

        var tbody = document.createElement('tbody');
        results.forEach(function (r) {
            var tr = document.createElement('tr');

            // Username cell
            var tdUser = document.createElement('td');
            var strong = document.createElement('strong');
            strong.textContent = r.username || '';
            tdUser.appendChild(strong);
            tr.appendChild(tdUser);

            // Domains cell
            var tdDomains = document.createElement('td');
            tdDomains.style.cssText = 'max-width:320px;word-break:break-all;';
            if (r.domains) {
                tdDomains.textContent = r.domains;
            } else {
                var em = document.createElement('em');
                em.className = 'text-muted';
                em.textContent = '—';
                tdDomains.appendChild(em);
            }
            tr.appendChild(tdDomains);

            // Site count cell
            var tdCount = document.createElement('td');
            tdCount.textContent = parseInt(r.site_count, 10) || 0;
            tr.appendChild(tdCount);

            // Status cell
            var tdStatus = document.createElement('td');
            var badge = document.createElement('span');
            if (r.disabled_reason) {
                badge.className = 'badge bg-danger';
                badge.textContent = 'Suspended: ' + r.disabled_reason;
            } else {
                badge.className = 'badge bg-success';
                badge.textContent = 'Active';
            }
            tdStatus.appendChild(badge);
            tr.appendChild(tdStatus);

            // Action cell
            var tdAction = document.createElement('td');
            if (!r.disabled_reason) {
                var btn = document.createElement('button');
                btn.type = 'button';
                btn.className = 'btn btn-sm btn-danger btn-open-disable';
                btn.dataset.username = r.username || '';
                btn.innerHTML = '<i class="fa fa-ban me-1"></i>Disable';
                btn.addEventListener('click', function () {
                    openDisableModal(this.dataset.username);
                });
                tdAction.appendChild(btn);
            }
            tr.appendChild(tdAction);

            tbody.appendChild(tr);
        });
        table.appendChild(tbody);

        var wrapper = document.createElement('div');
        wrapper.className = 'table-responsive';
        wrapper.appendChild(table);

        searchResult.innerHTML = '';
        searchResult.appendChild(wrapper);
    }

    function doSearch(q) {
        if (q.trim() === '') {
            searchResult.textContent = '';
            return;
        }
        fetch('api/accounts-search.php?q=' + encodeURIComponent(q), {
            headers: { 'X-CSRF-Token': csrfToken }
        })
        .then(function (r) { return r.json(); })
        .then(function (data) { renderSearchResults(data.results || []); })
        .catch(function (e) {
            searchResult.textContent = 'Search failed: ' + String(e);
        });
    }

    searchInput.addEventListener('input', function () {
        clearTimeout(searchTimer);
        var q = searchInput.value;
        searchTimer = setTimeout(function () { doSearch(q); }, 300);
    });

    // ------------------------------------------------------------------ //
    // Disable modal                                                        //
    // ------------------------------------------------------------------ //
    var disableModalEl  = document.getElementById('disableAccountModal');
    var disableModal    = new bootstrap.Modal(disableModalEl);
    var disableUsername = document.getElementById('disable-modal-username');
    var disableReason   = document.getElementById('disable-reason');
    var disableNote     = document.getElementById('disable-note');
    var disableError    = document.getElementById('disable-account-error');
    var disableConfirm  = document.getElementById('disable-account-confirm');

    var pendingDisableUsername = '';

    function openDisableModal(username) {
        pendingDisableUsername = username;
        disableUsername.textContent = username;
        disableReason.value = '';
        disableNote.value   = '';
        disableError.classList.add('d-none');
        disableModal.show();
    }

    disableConfirm.addEventListener('click', function () {
        var reason = disableReason.value;
        if (!reason) {
            disableError.textContent = 'Please select a reason.';
            disableError.classList.remove('d-none');
            return;
        }
        disableError.classList.add('d-none');
        disableConfirm.disabled = true;

        var body = new URLSearchParams({
            username:   pendingDisableUsername,
            reason:     reason,
            note:       disableNote.value,
            csrf_token: csrfToken
        });
        fetch('api/account-disable.php', { method: 'POST', body: body })
        .then(function (r) { return r.json(); })
        .then(function (data) {
            disableConfirm.disabled = false;
            if (data.ok) {
                disableModal.hide();
                location.reload();
            } else {
                disableError.textContent = 'Error: ' + (data.error || 'unknown');
                disableError.classList.remove('d-none');
            }
        })
        .catch(function (e) {
            disableConfirm.disabled = false;
            disableError.textContent = 'Request failed: ' + String(e);
            disableError.classList.remove('d-none');
        });
    });

    // ------------------------------------------------------------------ //
    // Enable modal                                                         //
    // ------------------------------------------------------------------ //
    var enableModalEl  = document.getElementById('enableAccountModal');
    var enableModal    = new bootstrap.Modal(enableModalEl);
    var enableUsername = document.getElementById('enable-modal-username');
    var enableError    = document.getElementById('enable-account-error');
    var enableConfirm  = document.getElementById('enable-account-confirm');

    var pendingEnableUsername = '';

    function openEnableModal(username) {
        pendingEnableUsername = username;
        enableUsername.textContent = username;
        enableError.classList.add('d-none');
        enableModal.show();
    }

    enableConfirm.addEventListener('click', function () {
        enableError.classList.add('d-none');
        enableConfirm.disabled = true;

        var body = new URLSearchParams({
            username:   pendingEnableUsername,
            csrf_token: csrfToken
        });
        fetch('api/account-enable.php', { method: 'POST', body: body })
        .then(function (r) { return r.json(); })
        .then(function (data) {
            enableConfirm.disabled = false;
            if (data.ok) {
                enableModal.hide();
                location.reload();
            } else {
                enableError.textContent = 'Error: ' + (data.error || 'unknown');
                enableError.classList.remove('d-none');
            }
        })
        .catch(function (e) {
            enableConfirm.disabled = false;
            enableError.textContent = 'Request failed: ' + String(e);
            enableError.classList.remove('d-none');
        });
    });

    // ------------------------------------------------------------------ //
    // Wire enable buttons in the suspended-accounts table                 //
    // ------------------------------------------------------------------ //
    document.querySelectorAll('.btn-enable-account').forEach(function (btn) {
        btn.addEventListener('click', function () {
            openEnableModal(this.getAttribute('data-username'));
        });
    });

});
</script>
