@extends('layouts/base_view')
@section('title')
{!! $variables['header_routes'] !!}
@endsection
@section('content')
<section class="content">
    <div class="container-fluid">
        <div class="row">
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-users-cog"></i> Manajemen Session User
                        </h3>
                        <div class="card-tools">
                            <button type="button" class="btn btn-sm btn-info" id="refreshTable">
                                <i class="fas fa-sync-alt"></i> Refresh
                            </button>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="alert alert-info">
                            <i class="fas fa-info-circle"></i>
                            <strong>Informasi:</strong> Halaman ini menampilkan status session semua user. 
                            Admin dapat meng-kill session user yang sedang online untuk memaksa logout.
                            <br>
                            <strong>Session Lifetime:</strong> {{ \App\Models\ParameterGlobal::getSessionLifetime() }} menit 
                            (dapat diubah di <a href="{{ route('parameter_globals.index') }}" class="alert-link">Parameter Global</a>).
                            Session expired otomatis akan dibersihkan setiap 30 menit oleh sistem.
                        </div>
                        
                        <table id="sessionTable" class="table table-hover table-sm">
                            <thead class="bg-warning">
                                <tr>
                                    <th width="5%">No</th>
                                    <th>Username</th>
                                    <th>Nama Lengkap</th>
                                    <th>Status User</th>
                                    <th>Status Session</th>
                                    <th>Last Login</th>
                                    <th>IP Address</th>
                                    <th width="12%" class="text-center">Aksi</th>
                                </tr>
                            </thead>
                            <tbody>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<script>
$(function() {
    var table = $('#sessionTable').DataTable({
        processing: true,
        serverSide: true,
        ajax: '{{ route("users.session_management") }}',
        columns: [
            {
                data: 0,
                name: 'no',
                orderable: false,
                searchable: false
            },
            {
                data: 1,
                name: 'username'
            },
            {
                data: 2,
                name: 'fullname'
            },
            {
                data: 3,
                name: 'status'
            },
            {
                data: 4,
                name: 'session_status',
                orderable: false
            },
            {
                data: 5,
                name: 'last_login_at'
            },
            {
                data: 6,
                name: 'last_login_ip'
            },
            {
                data: 7,
                name: 'action',
                orderable: false,
                searchable: false,
                className: 'text-center'
            }
        ],
        "responsive": false,
        "lengthChange": true,
        "autoWidth": false,
        "order": [[5, 'desc']], // Sort by last login
        drawCallback: function(settings) {
            $('[data-toggle="tooltip"]').tooltip();
        }
    });

    // Refresh button
    $('#refreshTable').on('click', function() {
        table.ajax.reload(null, false);
        Swal.fire({
            icon: 'success',
            title: 'Refreshed',
            text: 'Data berhasil di-refresh',
            timer: 1500,
            showConfirmButton: false
        });
    });

    // Kill session button
    $(document).on('click', '.kill-session', function() {
        var userId = $(this).data('id');
        var username = $(this).data('username');
        
        Swal.fire({
            title: 'Kill Session?',
            html: `Apakah Anda yakin ingin meng-kill session user <strong>${username}</strong>?<br><br>
                   <small class="text-danger">User akan dipaksa logout dari semua device.</small>`,
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#dc3545',
            cancelButtonColor: '#6c757d',
            confirmButtonText: '<i class="fas fa-power-off"></i> Ya, Kill Session',
            cancelButtonText: 'Batal'
        }).then((result) => {
            if (result.isConfirmed) {
                $.ajax({
                    url: `/users/${userId}/kill-session`,
                    type: 'POST',
                    data: {
                        _token: '{{ csrf_token() }}'
                    },
                    success: function(response) {
                        if (response.success) {
                            Swal.fire({
                                icon: 'success',
                                title: 'Berhasil!',
                                text: response.message,
                                timer: 2000,
                                showConfirmButton: false
                            });
                            table.ajax.reload(null, false);
                        } else {
                            Swal.fire({
                                icon: 'error',
                                title: 'Gagal',
                                text: response.message
                            });
                        }
                    },
                    error: function(xhr) {
                        var errorMessage = 'Terjadi kesalahan';
                        if (xhr.responseJSON && xhr.responseJSON.message) {
                            errorMessage = xhr.responseJSON.message;
                        }
                        Swal.fire({
                            icon: 'error',
                            title: 'Error',
                            text: errorMessage
                        });
                    }
                });
            }
        });
    });

    // Auto refresh every 30 seconds
    setInterval(function() {
        table.ajax.reload(null, false);
    }, 30000);
});
</script>
@endsection
