<?php
// Tambahkan pengecekan admin di awal
if (!isset($data_admin['agent_level']) || $data_admin['agent_level'] !== "admin") {
    header("Location: ./");
    exit();
}

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action'])) {
    $agent_identifier = trim((string)($_POST['agent_identifier'] ?? ''));
    $targetAgent = agent_find_by_identifier($call, $agent_identifier);
    $action = $_POST['action'];

    // Tentukan status berdasarkan aksi
    if ($action == 'block') {
        $status = 'blocked';
    } elseif ($action == 'unblock') {
        $status = 'active';
    } else {
        $status = '';
    }

    if ($status && $targetAgent !== null) {
        $targetAgentName = mysqli_real_escape_string($call, agent_public_name($targetAgent));
        $query = "UPDATE tb_agent SET agent_status = '$status' WHERE agent_name = '$targetAgentName'";
        $result = mysqli_query($call, $query);

        if ($result) {
            $message = 'Agent berhasil di blokir';
        } else {
            $message = 'Failed to update agent status';
        }
    }
}

$agentRows = [];
$agentTotal = 0;
$activeTotal = 0;
$blockedTotal = 0;
$cek_perpanjang = mysqli_query($call, "SELECT * FROM tb_agent ORDER BY id DESC");
if ($cek_perpanjang) {
    while ($data_perpanjang = mysqli_fetch_array($cek_perpanjang)) {
        $agentTotal++;
        if (($data_perpanjang['agent_status'] ?? '') === 'blocked') {
            $blockedTotal++;
        } else {
            $activeTotal++;
        }
        $agentRows[] = $data_perpanjang;
    }
}
?>

<div class="app-page-shell">
    <div class="row g-4">
    <div class="col-12">
        <div class="card">
            <div class="card-header">
                <h4 class="card-title mb-1">Blocked Agent</h4>
                <p class="text-muted mb-0">Kelola status aktif dan blocked agent.</p>
            </div>
        <?php if (!empty($message)) : ?>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Konfigurasi SweetAlert2 Toast
            const Toast = Swal.mixin({
                toast: true,
                position: 'top-end',
                showConfirmButton: false,
                timer: 3000,
                timerProgressBar: true,
                didOpen: (toast) => {
                    toast.onmouseenter = Swal.stopTimer;
                    toast.onmouseleave = Swal.resumeTimer;
                }
            });

            // Menampilkan Toast dengan SweetAlert2
            Toast.fire({
                icon: '<?php echo strpos($message, 'berhasil') !== false ? 'success' : 'error'; ?>',
                title: '<?php echo htmlspecialchars($message); ?>'
            });
        });
    </script>
<?php endif; ?>
            <div class="card-body">
                <div class="table-responsive">
                    <table id="table-perpanjangan-token" class="table table-striped table-hover align-middle">
                        <thead class="table-light">
                            <tr>
                                <th>Agent Name</th>
                                <th>Date Created</th>
                                <th>Status</th>
                                <th>Action</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php
                            foreach ($agentRows as $data_perpanjang) {
                                // Tentukan status agen, misalnya "Active", "Blocked"
                                $status = ($data_perpanjang['agent_status'] == 'blocked') ? 'Blocked' : 'Active';
                                $statusClass = ($data_perpanjang['agent_status'] == 'blocked') ? 'bg-light-danger text-danger' : 'bg-light-success text-success';
                            ?>
                            <tr>
                                <td><?= htmlspecialchars($data_perpanjang['agent_name'], ENT_QUOTES, 'UTF-8') ?></td>
                                <td class="text-nowrap"><?= htmlspecialchars($data_perpanjang['agent_created'], ENT_QUOTES, 'UTF-8') ?></td>
                                <td><span class="badge <?= $statusClass ?>"><?= htmlspecialchars($status, ENT_QUOTES, 'UTF-8') ?></span></td>
                                <td>
                                    <!-- Form untuk memblokir atau membuka blokir agen -->
                                    <form method="post" action="">
                                        <input type="hidden" name="agent_identifier" value="<?= htmlspecialchars(agent_public_name((array)$data_perpanjang), ENT_QUOTES, 'UTF-8') ?>">
                                        <?php if ($data_perpanjang['agent_status'] != 'blocked') { ?>
                                            <button type="submit" name="action" value="block" class="btn btn-outline-danger btn-sm">Block</button>
                                        <?php } else { ?>
                                            <button type="submit" name="action" value="unblock" class="btn btn-outline-success btn-sm">Unblock</button>
                                        <?php } ?>
                                    </form>
                                </td>
                            </tr>
                            <?php
                            }
                            ?>
                        </tbody>
                        <tfoot>
                            <tr>
                                <th>Agent Name</th>
                                <th>Date Created</th>
                                <th>Status</th>
                                <th>Action</th>
                            </tr>
                        </tfoot>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>
</div>
