<x-app-layout>

<div class="container-fluid">
    <div class="card">
        <div class="card-header d-flex justify-content-between align-items-center">
            <h5 class="mb-0">Backups</h5>
            <div>
                @can('backup.manage')
                    <button id="create-backup" class="btn btn-primary btn-sm">Create Backup</button>
                @endcan
            </div>
        </div>
        <div class="card-body">
            <table id="backups-table" class="table table-striped table-bordered" style="width:100%">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Filename</th>
                        <th>Status</th>
                        <th>Size</th>
                        <th>Created At</th>
                        <th>Actions</th>
                    </tr>
                </thead>
            </table>
        </div>
    </div>
</div>

@push('scripts')
<script>
$(function() {
    var table = $('#backups-table').DataTable({
        processing: true,
        serverSide: true,
        ajax: {
            url: '{{ route("admin.backups.data") }}',
            type: 'GET'
        },
        columns: [
            { data: 'id', name: 'id' },
            { data: 'filename', name: 'filename' },
            { data: 'status', name: 'status' },
            { data: 'size', name: 'size' },
            { data: 'created_at', name: 'created_at' },
            { data: 'operations', name: 'operations', orderable: false, searchable: false },
        ]
    });

    $('#create-backup').on('click', function() {
        $.ajax({
            url: '{{ route("admin.backups.store") }}',
            method: 'POST',
            headers: { 'X-CSRF-TOKEN': '{{ csrf_token() }}' },
            success: function(res) {
                alert('Backup job queued');
                table.ajax.reload();
            },
            error: function() { alert('Failed to start backup'); }
        });
    });

    $('#backups-table').on('click', '.js-download-backup', function() {
        var id = $(this).data('id');
        window.location = '{{ url('admin/backups') }}/' + id + '/download';
    });

    $('#backups-table').on('click', '.js-delete-backup', function() {
        var id = $(this).data('id');
        if (!confirm('Delete backup?')) return;
        $.ajax({
            url: '{{ url('admin/backups') }}/' + id,
            method: 'DELETE',
            headers: { 'X-CSRF-TOKEN': '{{ csrf_token() }}' },
            success: function() { table.ajax.reload(); },
            error: function() { alert('Failed to delete'); }
        });
    });
});
</script>
@endpush
</x-app-layout>