@extends('backoffice.layouts.app')

@section('title', 'Kara Liste')

@section('content')
<div class="container-fluid">
    <div class="row mb-4">
        <div class="col-12">
            <div class="d-flex justify-content-between align-items-center">
                <div>
                    <h2 class="mb-1"><i class="bi bi-slash-circle me-2"></i>Kara Liste</h2>
                    <p class="text-muted">Engellenen oyuncular listesi</p>
                </div>
                @if(can_access('blacklist', 'create'))
                <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#createBlacklistModal">
                    <i class="bi bi-plus-circle me-2"></i>Kayit Ekle
                </button>
                @endif
            </div>
        </div>
    </div>

    <div class="card border-0 shadow-sm">
        <div class="card-body p-0">
            <div class="table-responsive">
                <table id="blacklistTable" class="table table-hover mb-0">
                    <thead class="table-light">
                        <tr>
                            <th>ID</th>
                            <th>Oyuncu ID</th>
                            <th>Oyuncu Adi</th>
                            <th>Aciklama</th>
                            <th>Ekleyen</th>
                            <th>Olusturma Tarihi</th>
                            <th width="140" class="text-center">Islemler</th>
                        </tr>
                    </thead>
                    <tbody></tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- Create Modal -->
<div class="modal fade" id="createBlacklistModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="bi bi-plus-circle me-2"></i>Kara Liste Kaydi</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="createBlacklistForm">
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">Oyuncu ID <span class="text-danger">*</span></label>
                        <input type="text" name="player_id" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Oyuncu Adi</label>
                        <input type="text" name="player_name" class="form-control">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Aciklama</label>
                        <textarea name="description" class="form-control" rows="3"></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Iptal</button>
                    <button type="submit" class="btn btn-primary"><i class="bi bi-check-circle me-2"></i>Olustur</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Edit Modal -->
<div class="modal fade" id="editBlacklistModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="bi bi-pencil me-2"></i>Kara Listeyi Duzenle</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="editBlacklistForm">
                <input type="hidden" id="editBlacklistId">
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">Oyuncu ID <span class="text-danger">*</span></label>
                        <input type="text" name="player_id" id="editPlayerId" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Oyuncu Adi</label>
                        <input type="text" name="player_name" id="editPlayerName" class="form-control">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Aciklama</label>
                        <textarea name="description" id="editDescription" class="form-control" rows="3"></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Iptal</button>
                    <button type="submit" class="btn btn-primary"><i class="bi bi-check-circle me-2"></i>Guncelle</button>
                </div>
            </form>
        </div>
    </div>
</div>

@endsection

@push('scripts')
<script>
$(document).ready(function() {
    const canUpdate = {!! can_access('blacklist', 'update') ? 'true' : 'false' !!};
    const canDelete = {!! can_access('blacklist', 'delete') ? 'true' : 'false' !!};
    let table;

    function initTable() {
        if (table) table.destroy();
        table = $('#blacklistTable').DataTable({
            processing: true,
            serverSide: false,
            ajax: {
                url: '{{ route("backoffice.blacklist.index") }}',
                data: { ajax: 1 },
                dataSrc: 'data',
                error: function(xhr) {
                    Swal.fire('Hata!', xhr.responseJSON?.message || 'Liste yuklenemedi', 'error');
                }
            },
            columns: [
                { data: 'id' },
                { data: 'player_id' },
                { data: 'player_name' },
                { data: 'description' },
                { data: 'created_by_name' },
                { data: 'created_at' },
                {
                    data: null,
                    orderable: false,
                    render: function(data) {
                        let btns = '<div class="btn-group btn-group-sm">';
                        if (canUpdate) {
                            btns += '<button class="btn btn-outline-primary btn-edit" data-id="' + data.id + '"><i class="bi bi-pencil"></i></button>';
                        }
                        if (canDelete) {
                            btns += '<button class="btn btn-outline-danger btn-delete" data-id="' + data.id + '"><i class="bi bi-trash"></i></button>';
                        }
                        return btns + '</div>';
                    }
                }
            ],
            order: [[0, 'desc']],
            pageLength: 25,
            language: { url: '//cdn.datatables.net/plug-ins/1.13.6/i18n/tr.json' }
        });
    }

    initTable();

    $('#createBlacklistForm').on('submit', function(e) {
        e.preventDefault();
        let formData = $(this).serialize();
        formData += '&_token={{ csrf_token() }}';

        $.ajax({
            url: '{{ route("backoffice.blacklist.store") }}',
            method: 'POST',
            data: formData,
            success: function(response) {
                $('#createBlacklistModal').modal('hide');
                $('#createBlacklistForm')[0].reset();
                Swal.fire('Basarili!', response.message, 'success');
                table.ajax.reload();
            },
            error: function(xhr) {
                if (xhr.status === 422 && xhr.responseJSON.errors) {
                    let errorMsg = '<ul class="text-start">';
                    Object.keys(xhr.responseJSON.errors).forEach(function(key) {
                        errorMsg += '<li>' + xhr.responseJSON.errors[key][0] + '</li>';
                    });
                    errorMsg += '</ul>';
                    Swal.fire('Dogrulama Hatasi!', errorMsg, 'error');
                } else {
                    Swal.fire('Hata!', xhr.responseJSON?.message || 'Istegi islerken hata olustu', 'error');
                }
            }
        });
    });

    $(document).on('click', '.btn-edit', function() {
        const id = $(this).data('id');
        $.ajax({
            url: '{{ route("backoffice.blacklist.show", ":id") }}'.replace(':id', id),
            success: function(response) {
                const item = response.item;
                $('#editBlacklistId').val(item.id);
                $('#editPlayerId').val(item.player_id);
                $('#editPlayerName').val(item.player_name || '');
                $('#editDescription').val(item.description || '');
                $('#editBlacklistModal').modal('show');
            }
        });
    });

    $('#editBlacklistForm').on('submit', function(e) {
        e.preventDefault();
        const id = $('#editBlacklistId').val();
        let formData = $(this).serialize();
        formData += '&_token={{ csrf_token() }}&_method=PUT';

        $.ajax({
            url: '{{ route("backoffice.blacklist.update", ":id") }}'.replace(':id', id),
            method: 'POST',
            data: formData,
            success: function(response) {
                $('#editBlacklistModal').modal('hide');
                Swal.fire('Basarili!', response.message, 'success');
                table.ajax.reload();
            },
            error: function(xhr) {
                if (xhr.status === 422 && xhr.responseJSON.errors) {
                    let errorMsg = '<ul class="text-start">';
                    Object.keys(xhr.responseJSON.errors).forEach(function(key) {
                        errorMsg += '<li>' + xhr.responseJSON.errors[key][0] + '</li>';
                    });
                    errorMsg += '</ul>';
                    Swal.fire('Dogrulama Hatasi!', errorMsg, 'error');
                } else {
                    Swal.fire('Hata!', xhr.responseJSON?.message || 'Istegi islerken hata olustu', 'error');
                }
            }
        });
    });

    $(document).on('click', '.btn-delete', function() {
        const id = $(this).data('id');
        Swal.fire({
            title: 'Emin misiniz?',
            text: 'Bu kayit silinecek.',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: 'Evet, sil',
            cancelButtonText: 'Iptal',
            confirmButtonColor: '#dc3545'
        }).then((result) => {
            if (result.isConfirmed) {
                $.ajax({
                    url: '{{ route("backoffice.blacklist.destroy", ":id") }}'.replace(':id', id),
                    method: 'POST',
                    data: { _token: '{{ csrf_token() }}', _method: 'DELETE' },
                    success: function(response) {
                        Swal.fire('Basarili!', response.message, 'success');
                        table.ajax.reload();
                    },
                    error: function(xhr) {
                        Swal.fire('Hata!', xhr.responseJSON?.message || 'Istegi islerken hata olustu', 'error');
                    }
                });
            }
        });
    });
});
</script>
@endpush
