<?= $this->extend('Layout/Starter') ?>
<?= $this->section('content') ?>
<div class="row justify-content-center">
    <div class="col-12"><?= $this->include('Layout/msgStatus') ?></div>
    <div class="col-12">
        <div class="card shadow-sm">
            <div class="card-header bg-primary text-white">
                <div class="d-flex justify-content-between align-items-center">
                    <div class="btn-group">
                        <button class="btn btn-light btn-sm" id="blur-out"><i class="bi bi-eye-slash"></i></button>
                        <a class="btn btn-outline-light btn-sm" href="<?= site_url('keys/generate') ?>"><i class="bi bi-person-plus"></i></a>
                    </div>
                    <button class="btn btn-danger btn-sm" id="delete-selected" disabled><i class="bi bi-trash3"></i> Xoá Đã Chọn</button>
                </div>
            </div>
            <div class="card-body p-2">
                <form id="bulk-delete-form">
                    <?= csrf_field() ?>
                    <div class="table-responsive">
                        <table id="datatable" class="table table-bordered table-sm table-hover text-center align-middle w-100">
                            <thead class="table-light">
                                <tr>
                                    <th><input type="checkbox" id="check-all"></th>
                                    <th>#</th>
                                    <th>Game</th>
                                    <th class="text-nowrap">Key</th>
                                    <th>Loại</th>
                                    <th>Máy</th>
                                    <th>Thời Gian</th>
                                    <th>Hết Hạn</th>
                                    <th>Hành Động</th>
                                </tr>
                            </thead>
                        </table>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
<?= $this->endSection() ?>

<?= $this->section('css') ?>
<?= link_tag("https://cdn.datatables.net/1.10.25/css/dataTables.bootstrap5.min.css") ?>
<style>
.key-vip { background-color: #ffc107; color: #000; font-weight: bold; padding: 2px 6px; border-radius: 4px; }
.key-regular { background-color: #0d6efd; color: #fff; padding: 2px 6px; border-radius: 4px; }
.key-sensi { filter: blur(5px); user-select: none; }
</style>
<?= $this->endSection() ?>

<?= $this->section('js') ?>
<?= script_tag("https://cdn.datatables.net/1.10.25/js/jquery.dataTables.min.js") ?>
<?= script_tag("https://cdn.datatables.net/1.10.25/js/dataTables.bootstrap5.min.js") ?>
<script>
$(function () {
    const table = $('#datatable').DataTable({
        processing: true,
        serverSide: true,
        order: [[1, "desc"]],
        ajax: "<?= site_url('keys/api') ?>",
        columns: [
            {
                data: 'user_key',
                orderable: false,
                render: data => `<input type="checkbox" class="form-check-input key-checkbox" name="keys[]" value="${data}">`
            },
            { data: 'id' },
            { data: 'game' },
            {
                data: 'user_key',
                render: function (data, type, row) {
                    const status = row.status === 'Active' ? 'text-success' : 'text-danger';
                    return `<span class="${status} keyBlur key-sensi">${data}</span>`;
                }
            },
            {
                data: 'key_type',
                render: data => data.toUpperCase() === 'VIP'
                    ? '<span class="key-vip">VIP</span>'
                    : '<span class="key-regular">THƯỜNG</span>'
            },
            {
                data: 'devices',
                render: (data, type, row) => `<span id="devMax-${row.user_key}">${data || 0}/${row.max_devices}</span>`
            },
            { data: 'duration' },
            {
                data: 'expired',
                render: data => data ? `<span class="badge bg-primary">${data}</span>` : '(Chưa kích hoạt)'
            },
            {
                data: null,
                render: (data, type, row) => `
                    <div class="btn-group btn-group-sm">
                        <button class="btn btn-outline-danger" onclick="resetUserKey('${row.user_key}')"><i class="bi bi-bootstrap-reboot"></i></button>
                        <a href="<?= site_url('keys') ?>/${row.id}" class="btn btn-outline-primary"><i class="bi bi-pencil"></i></a>
                    </div>`
            }
        ],
        drawCallback: function () {
            $('#delete-selected').prop('disabled', $('.key-checkbox:checked').length === 0);
        }
    });

    $('#blur-out').click(function () {
        $('.keyBlur').toggleClass('key-sensi');
        $(this).html($('.keyBlur').hasClass('key-sensi') ? `<i class="bi bi-eye-slash"></i>` : `<i class="bi bi-eye"></i>`);
    });

    $('#check-all').on('change', function () {
        $('.key-checkbox').prop('checked', this.checked);
        $('#delete-selected').prop('disabled', $('.key-checkbox:checked').length === 0);
    });

    $('#datatable').on('change', '.key-checkbox', function () {
        $('#delete-selected').prop('disabled', $('.key-checkbox:checked').length === 0);
    });

    $('#delete-selected').click(function (e) {
        e.preventDefault();
        const selected = $('.key-checkbox:checked');
        if (!selected.length || !confirm(`Bạn có chắc muốn xoá ${selected.length} key?`)) return;
        const formData = new FormData($('#bulk-delete-form')[0]);
        selected.each(function () {
            formData.append('keys[]', $(this).val());
        });
        $.ajax({
            url: "<?= site_url('keys/delete_bulk') ?>",
            method: "POST",
            data: formData,
            processData: false,
            contentType: false,
            success: res => {
                alert(res.message || "Đã xoá!");
                table.ajax.reload();
                $('#check-all').prop('checked', false);
                $('#delete-selected').prop('disabled', true);
            },
            error: xhr => {
                alert("Lỗi xoá: " + xhr.status + " - " + xhr.responseText);
            }
        });
    });
});

function resetUserKey(key) {
    if (!confirm("Reset thiết bị cho key này?")) return;
    $.get("<?= site_url('keys/reset') ?>", { userkey: key, reset: 1 }, function (res) {
        if (res.reset) {
            alert("Đã reset thành công!");
            $('#datatable').DataTable().ajax.reload();
        } else {
            alert(res.registered ? "Key đã reset trước đó." : "Không tồn tại key!");
        }
    });
}
</script>
<?= $this->endSection() ?>