<?php
    $warnedUsers = isset($warnedUsers) && is_array($warnedUsers) ? $warnedUsers : [];
    $warnedCount = isset($warnedCount) ? (int)$warnedCount : count($warnedUsers);
    $highRiskUsers = array_filter($warnedUsers, static function ($user) {
        return isset($user['warningCount']) && (int)$user['warningCount'] >= 2;
    });
    $totalWarningsIssued = array_sum(array_map(static function ($user) {
        return isset($user['warningCount']) ? (int)$user['warningCount'] : 0;
    }, $warnedUsers));
?>

<style>
    .warnings-hero {
        background: linear-gradient(135deg, #f97316, #fb7185);
        border-radius: 20px;
        color: #fff;
        padding: 32px 36px;
        box-shadow: 0 20px 40px rgba(251, 113, 133, 0.25);
        margin-bottom: 28px;
        position: relative;
        overflow: hidden;
    }
    .warnings-hero::after {
        content: "";
        position: absolute;
        inset: 0;
        background: radial-gradient(circle at top right, rgba(255,255,255,0.45), transparent 55%);
        opacity: 0.6;
    }
    .warnings-hero h1 {
        font-size: 1.875rem;
        font-weight: 700;
        margin-bottom: 6px;
    }
    .warnings-hero p {
        margin: 0;
        font-size: 1rem;
        opacity: 0.9;
    }
    .warnings-hero .badge {
        background: rgba(255,255,255,0.2);
        color: #fff;
        padding: 6px 12px;
        border-radius: 999px;
        font-weight: 600;
        letter-spacing: 0.08em;
    }
    .warnings-metrics .card {
        border: none;
        border-radius: 18px;
        box-shadow: 0 12px 30px rgba(15, 23, 42, 0.08);
        transition: transform 0.25s ease, box-shadow 0.25s ease;
    }
    .warnings-metrics .card:hover {
        transform: translateY(-4px);
        box-shadow: 0 16px 36px rgba(15, 23, 42, 0.12);
    }
    .warnings-metrics .metric-label {
        font-size: 0.85rem;
        text-transform: uppercase;
        letter-spacing: 0.08em;
        color: #64748b;
        margin-bottom: 6px;
    }
    .warnings-metrics .metric-value {
        font-size: 1.8rem;
        font-weight: 700;
        color: #0f172a;
    }
    .warnings-metrics .metric-subtext {
        font-size: 0.85rem;
        color: #94a3b8;
        margin-top: 4px;
    }
    .filter-card {
        border: none;
        border-radius: 16px;
        box-shadow: 0 14px 28px rgba(15, 23, 42, 0.08);
        margin-bottom: 28px;
    }
    .filter-card .form-control {
        border-radius: 14px;
        border-color: #e2e8f0;
        padding: 10px 14px;
        box-shadow: none;
    }
    .filter-card .form-control:focus {
        border-color: #fb7185;
        box-shadow: 0 0 0 0.25rem rgba(251, 113, 133, 0.15);
    }
    .table-card {
        border: none;
        border-radius: 18px;
        box-shadow: 0 18px 36px rgba(15, 23, 42, 0.1);
    }
    .table thead th {
        text-transform: uppercase;
        letter-spacing: 0.05em;
        font-size: 0.75rem;
        border-bottom: 1px solid #e2e8f0;
        color: #475569;
        background-color: #f8fafc;
    }
    .table tbody td {
        vertical-align: middle;
        color: #1e293b;
    }
    .status-pill {
        display: inline-flex;
        align-items: center;
        gap: 6px;
        padding: 6px 14px;
        border-radius: 999px;
        font-weight: 600;
        font-size: 0.82rem;
    }
    .status-pill.warned {
        background: rgba(249, 115, 22, 0.12);
        color: #ea580c;
    }
    .status-pill.suspend {
        background: rgba(220, 38, 38, 0.12);
        color: #b91c1c;
    }
    .btn-action {
        border-radius: 12px;
        padding: 8px 16px;
        font-weight: 600;
        transition: all 0.2s ease;
    }
    .btn-action:hover {
        transform: translateY(-1px);
    }
    .empty-state {
        padding: 48px 0;
        text-align: center;
        color: #64748b;
        font-size: 1rem;
    }
    @media (max-width: 767.98px) {
        .warnings-hero {
            padding: 24px;
        }
        .warnings-hero h1 {
            font-size: 1.5rem;
        }
        .warnings-metrics .metric-value {
            font-size: 1.5rem;
        }
    }
</style>

<!--start main wrapper-->
<main class="main-wrapper">
    <div class="main-content">
        <section class="warnings-hero d-none">
            <div class="d-flex flex-column flex-lg-row align-items-lg-center justify-content-between position-relative">
                <div>
                    <h1>Warned Users</h1>
                    <p>Review accounts that recently received policy warnings and decide the next action.</p>
                </div>
                <div class="mt-3 mt-lg-0">
                    <span class="badge"><?= $warnedCount; ?> in review</span>
                </div>
            </div>
        </section>

        <section class="warnings-metrics mb-4">
            <div class="row g-3">
                <div class="col-md-4">
                    <div class="card h-100">
                        <div class="card-body">
                            <div class="metric-label">Warned Users</div>
                            <div class="metric-value"><?= number_format($warnedCount); ?></div>
                            <div class="metric-subtext">Active warnings in the last review cycle</div>
                        </div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="card h-100">
                        <div class="card-body">
                            <div class="metric-label">Warnings Issued</div>
                            <div class="metric-value"><?= number_format($totalWarningsIssued); ?></div>
                            <div class="metric-subtext">Total warnings earned by these accounts</div>
                        </div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="card h-100">
                        <div class="card-body">
                            <div class="metric-label">High-Risk Accounts</div>
                            <div class="metric-value text-danger"><?= number_format(count($highRiskUsers)); ?></div>
                            <div class="metric-subtext">Users with 2+ warnings</div>
                        </div>
                    </div>
                </div>
            </div>
        </section>

        <div class="card filter-card">
            <div class="card-body">
                <label for="warnedSearch" class="form-label fw-semibold">Search warned users</label>
                <div class="input-group">
                    <span class="input-group-text bg-white border-end-0">
                        <i class="bi bi-search text-muted"></i>
                    </span>
                    <input type="text" id="warnedSearch" class="form-control border-start-0" placeholder="Search by name or email...">
                </div>
            </div>
        </div>

        <div class="card table-card">
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-hover mb-0" id="warnedUsersTable">
                        <thead>
                            <tr>
                                <th scope="col">User</th>
                                <th scope="col">Email</th>
                                <th scope="col">Warnings</th>
                                <th scope="col">Last Warning</th>
                                <th scope="col">Status</th>
                                <th scope="col" class="text-end">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (!empty($warnedUsers)): ?>
                                <?php foreach ($warnedUsers as $user): ?>
                                    <?php
                                        $warnings = isset($user['warningCount']) ? (int)$user['warningCount'] : 0;
                                        $lastWarningAt = isset($user['lastWarningAt']) ? (int)$user['lastWarningAt'] : null;
                                        $status = isset($user['status']) ? strtolower($user['status']) : 'warning';
                                        $statusClass = $status === 'suspend' ? 'suspend' : 'warning';
                                    ?>
                                    <tr data-search="<?= htmlspecialchars(strtolower(($user['fullName'] ?? '') . ' ' . ($user['email'] ?? '')), ENT_QUOTES, 'UTF-8'); ?>">
                                        <td>
                                            <div class="d-flex align-items-center gap-2">
                                                <div class="avatar avatar-sm rounded-circle bg-warning text-white fw-semibold">
                                                    <?= strtoupper(substr($user['fullName'], 0, 1)); ?>
                                                </div>
                                                <div>
                                                    <span class="fw-semibold d-block"><?= htmlspecialchars($user['fullName'], ENT_QUOTES, 'UTF-8'); ?></span>
                                                    <small class="text-muted">ID: <?= htmlspecialchars($user['id'], ENT_QUOTES, 'UTF-8'); ?></small>
                                                </div>
                                            </div>
                                        </td>
                                        <td><?= $user['email'] !== '' ? htmlspecialchars($user['email'], ENT_QUOTES, 'UTF-8') : '<span class="text-muted">Not provided</span>'; ?></td>
                                        <td>
                                            <span class="badge rounded-pill bg-warning text-dark px-3 py-2">
                                                <?= $warnings; ?> warning<?= $warnings === 1 ? '' : 's'; ?>
                                            </span>
                                        </td>
                                        <td>
                                            <?php if ($lastWarningAt): ?>
                                                <?= date('d M Y, h:i A', $lastWarningAt / 1000); ?>
                                            <?php else: ?>
                                                <span class="text-muted">No record</span>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <span class="status-pill <?= $statusClass; ?>">
                                                <i class="bi bi-exclamation-triangle-fill"></i>
                                                <?= ucfirst($statusClass); ?>
                                            </span>
                                        </td>
                                        <td class="text-end">
                                            <button
                                                class="btn-action btn btn-outline-danger text-danger suspend-user-btn"
                                                data-user-id="<?= htmlspecialchars($user['id'], ENT_QUOTES, 'UTF-8'); ?>"
                                                data-user-name="<?= htmlspecialchars($user['fullName'], ENT_QUOTES, 'UTF-8'); ?>"
                                            >
                                                <i class="bi bi-slash-circle me-1"></i>Suspend User
                                            </button>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="6">
                                        <div class="empty-state">
                                            <i class="bi bi-emoji-smile fs-1 text-success d-block mb-3"></i>
                                            Great news! No users are currently in a warned state.
                                        </div>
                                    </td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</main>
<!--end main wrapper-->

<script>
    (function () {
        const searchInput = document.getElementById('warnedSearch');
        const tableRows = document.querySelectorAll('#warnedUsersTable tbody tr');

        if (!searchInput || !tableRows.length) {
            return;
        }

        searchInput.addEventListener('input', function (event) {
            const query = event.target.value.trim().toLowerCase();

            tableRows.forEach(function (row) {
                const haystack = row.getAttribute('data-search') || '';
                if (haystack.indexOf(query) !== -1) {
                    row.classList.remove('d-none');
                } else {
                    row.classList.add('d-none');
                }
            });
        });
    })();

    (function () {
        const suspendButtons = document.querySelectorAll('.suspend-user-btn');
        if (!suspendButtons.length) {
            return;
        }

        suspendButtons.forEach(function (button) {
            button.addEventListener('click', function () {
                const userId = this.getAttribute('data-user-id');
                const userName = this.getAttribute('data-user-name') || 'this user';
                const row = this.closest('tr');
                const statusPill = row ? row.querySelector('.status-pill') : null;

                if (!userId) {
                    Swal.fire({
                        icon: 'error',
                        title: 'Missing user',
                        text: 'We could not determine which user to suspend.',
                        confirmButtonColor: '#dc2626',
                    });
                    return;
                }

                Swal.fire({
                    title: 'Suspend user?',
                    text: `This will permanently suspend ${userName}.`,
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonColor: '#dc2626',
                    cancelButtonColor: '#64748b',
                    confirmButtonText: 'Yes, suspend',
                }).then((result) => {
                    if (!result.isConfirmed) {
                        return;
                    }

                    Swal.fire({
                        title: 'Processing suspension',
                        html: '<p class="mb-0 text-muted">Updating account status…</p>',
                        allowOutsideClick: false,
                        allowEscapeKey: false,
                        showConfirmButton: false,
                        didOpen: () => Swal.showLoading(),
                    });

                    fetch('<?= base_url('site/suspendWarnedUser'); ?>', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
                            'X-Requested-With': 'XMLHttpRequest',
                        },
                        body: new URLSearchParams({ userId: userId }),
                    })
                        .then((response) => response.json())
                        .then((data) => {
                            Swal.close();

                            if (!data.success) {
                                Swal.fire({
                                    icon: 'error',
                                    title: 'Suspension failed',
                                    text: data.message || 'Unable to suspend this user.',
                                    confirmButtonColor: '#dc2626',
                                });
                                return;
                            }

                            Swal.fire({
                                icon: 'success',
                                title: 'User suspended',
                                text: `${userName} has been moved to the suspended list.`,
                                confirmButtonColor: '#16a34a',
                            });

                            if (statusPill) {
                                statusPill.classList.remove('warning');
                                statusPill.classList.add('suspend');
                                statusPill.innerHTML = '<i class="bi bi-slash-circle-fill"></i> Suspend';
                            }

                            if (row) {
                                row.setAttribute('data-search', `${row.getAttribute('data-search') || ''} suspend`);
                                this.setAttribute('disabled', 'disabled');
                                this.classList.remove('btn-outline-danger', 'text-danger');
                                this.classList.add('btn-light', 'text-muted');
                                this.innerHTML = '<i class="bi bi-lock-fill me-1"></i>Suspended';
                            }
                        })
                        .catch(() => {
                            Swal.close();
                            Swal.fire({
                                icon: 'error',
                                title: 'Network error',
                                text: 'Please try again in a moment.',
                                confirmButtonColor: '#dc2626',
                            });
                        });
                });
            });
        });
    })();
</script>
