@extends('backoffice.layouts.app')

@section('title', 'Backoffice Kullanıcılar')
@php
    $hiddenUserGroupIdsRaw = json_decode(setting('advanced_hidden_user_group_ids', '[1,9]'), true);
    $hiddenUserGroupIds = is_array($hiddenUserGroupIdsRaw)
        ? array_values(array_unique(array_map('intval', $hiddenUserGroupIdsRaw)))
        : [1, 9];
@endphp

@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-people me-2"></i>Backoffice Kullanıcılar</h2>
                    <p class="text-muted">Sistem kullanıcılarını yönetin</p>
                </div>
                <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#createUserModal">
                    <i class="bi bi-plus-circle me-2"></i>Yeni Kullanıcı Ekle
                </button>
            </div>
        </div>
    </div>

    <!-- Filters -->
    <div class="card border-0 shadow-sm mb-4">
        <div class="card-body">
            <form id="filterForm" class="row g-3">
                <div class="col-md-6">
                    <label class="form-label small">Yetki Grubu</label>
                    <select name="permission_group_id" class="form-select form-select-sm">
                        <option value="">Tümü</option>
                        @foreach($permissionGroups as $group)
                            @if(!in_array((int) $group->id, $hiddenUserGroupIds, true))
                                <option value="{{ $group->id }}">{{ $group->name }}</option>
                            @endif
                        @endforeach
                    </select>
                </div>
                <div class="col-md-6">
                    <label class="form-label small">&nbsp;</label>
                    <button type="submit" class="btn btn-primary btn-sm w-100"><i class="bi bi-funnel"></i> Filtrele</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Table -->
    <div class="card border-0 shadow-sm">
        <div class="card-body p-0">
            <div class="table-responsive">
                <table id="usersTable" class="table table-hover mb-0">
                    <thead class="table-light">
                        <tr>
                            <th>Kullanıcı Adı</th>
                            <th>Ad Soyad</th>
                            <th>E-posta</th>
                            <th>Yetki Grubu</th>
                            <th>Son Giriş</th>
                            <th>Durum</th>
                            <th width="150" class="text-center">İşlemler</th>
                        </tr>
                    </thead>
                    <tbody></tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- Create Modal -->
<div class="modal fade" id="createUserModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="bi bi-plus-circle me-2"></i>Yeni Backoffice Kullanıcısı</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="createUserForm">
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">Yetki Grubu</label>
                        <select name="permission_group_id" class="form-select">
                            <option value="">Seçiniz (Opsiyonel)</option>
                            @foreach($permissionGroups as $group)
                            @if(!in_array((int) $group->id, $hiddenUserGroupIds, true))
                                <option value="{{ $group->id }}">{{ $group->name }}</option>
                            @endif
                        @endforeach
                        </select>
                        <small class="text-muted">Boş bırakılırsa yetki kısıtlaması olmaz</small>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Kullanıcı Adı <span class="text-danger">*</span></label>
                        <input type="text" name="username" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Ad Soyad <span class="text-danger">*</span></label>
                        <input type="text" name="full_name" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">E-posta <span class="text-danger">*</span></label>
                        <input type="email" name="email" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Site EriÅŸimi</label>
                        <select name="site_ids[]" class="form-select" multiple size="6">
                            @foreach($sites as $site)
                                <option value="{{ $site->id }}">{{ $site->name }}{{ $site->is_active ? '' : ' (Pasif)' }}</option>
                            @endforeach
                        </select>
                        <small class="text-muted">BoÅŸ bÄ±rakÄ±lÄ±rsa tÃ¼m sitelere eriÅŸebilir</small>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Şifre <span class="text-danger">*</span></label>
                        <input type="password" name="password" class="form-control" required minlength="6">
                        <small class="text-muted">En az 6 karakter</small>
                    </div>
                    <div class="mb-3">
                        <div class="form-check form-switch">
                            <input class="form-check-input" type="checkbox" name="is_active" checked>
                            <label class="form-check-label">Aktif</label>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">İptal</button>
                    <button type="submit" class="btn btn-primary"><i class="bi bi-check-circle me-2"></i>Oluştur</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Edit Modal -->
<div class="modal fade" id="editUserModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="bi bi-pencil me-2"></i>Kullanıcıyı Düzenle</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="editUserForm">
                <input type="hidden" id="editUserId">
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">Yetki Grubu</label>
                        <select name="permission_group_id" id="editPermissionGroupId" class="form-select">
                            <option value="">Seçiniz (Opsiyonel)</option>
                            @foreach($permissionGroups as $group)
                            @if(!in_array((int) $group->id, $hiddenUserGroupIds, true))
                                <option value="{{ $group->id }}">{{ $group->name }}</option>
                            @endif
                        @endforeach
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Kullanıcı Adı</label>
                        <input type="text" name="username" id="editUsername" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Ad Soyad</label>
                        <input type="text" name="full_name" id="editFullName" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">E-posta</label>
                        <input type="email" name="email" id="editEmail" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Site Erisim</label>
                        <select name="site_ids[]" id="editSiteIds" class="form-select" multiple size="6">
                            @foreach($sites as $site)
                                <option value="{{ $site->id }}">{{ $site->name }}{{ $site->is_active ? '' : ' (Pasif)' }}</option>
                            @endforeach
                        </select>
                        <small class="text-muted">Secilen Siteleri erisebilir</small>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Yeni Şifre</label>
                        <input type="password" name="password" id="editPassword" class="form-control" minlength="6">
                        <small class="text-muted">Boş bırakılırsa şifre değişmez</small>
                    </div>
                    <div class="mb-3">
                        <div class="form-check form-switch">
                            <input class="form-check-input" type="checkbox" name="is_active" id="editIsActive">
                            <label class="form-check-label">Aktif</label>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">İptal</button>
                    <button type="submit" class="btn btn-primary"><i class="bi bi-check-circle me-2"></i>Güncelle</button>
                </div>
            </form>
        </div>
    </div>
</div>

@endsection

@push('scripts')
<script>
$(document).ready(function() {
    const canUpdateUsers = {!! can_access('users', 'update') ? 'true' : 'false' !!};
    const canDeleteUsers = {!! can_access('users', 'delete') ? 'true' : 'false' !!};
    const hiddenPermissionGroupIds = @json($hiddenUserGroupIds);
    let table;

    function setMultiSelectValues(selector, values) {
        const normalizedValues = (values || []).map(function(value) {
            return String(value);
        });

        $(selector).find('option').each(function() {
            $(this).prop('selected', normalizedValues.includes(String($(this).val())));
        });
    }

    function initTable(filters = {}) {
        if (table) table.destroy();
        table = $('#usersTable').DataTable({
            processing: true,
            serverSide: false,
            ajax: {
                url: '{{ route("backoffice.users.index") }}',
                data: filters,
                dataSrc: function(response) {
                    let rows = [];
                    if (Array.isArray(response)) {
                        rows = response;
                    } else if (response && Array.isArray(response.data)) {
                        rows = response.data;
                    }
                    return rows.filter(function(user) {
                        return !hiddenPermissionGroupIds.includes(Number(user.permission_group_id));
                    });
                }
            },
            columns: [
                { data: 'username' },
                { data: 'full_name' },
                { data: 'email' },
                {
                    data: 'permission_group_name',
                    render: function(data) {
                        return data !== '-' ? '<span class="badge bg-primary">' + data + '</span>' : '<span class="text-muted">-</span>';
                    }
                },
                {
                    data: 'last_login_at',
                    render: function(data) {
                        return data !== '-' ? '<small class="text-muted">' + data + '</small>' : '<span class="text-muted">-</span>';
                    }
                },
                {
                    data: 'is_active',
                    render: function(data) {
                        return data ? '<span class="badge bg-success">Aktif</span>' : '<span class="badge bg-danger">Pasif</span>';
                    }
                },
                {
                    data: null,
                    orderable: false,
                    render: function(data) {
                        let btns = '<div class="btn-group btn-group-sm">';
                        if (canUpdateUsers) {
                            btns += '<button class="btn btn-outline-primary btn-edit" data-id="' + data.id + '"><i class="bi bi-pencil"></i></button>';
                            btns += '<button class="btn btn-outline-' + (data.is_active ? 'warning' : 'success') + ' btn-toggle" data-id="' + data.id + '"><i class="bi bi-' + (data.is_active ? 'pause' : 'play') + '-circle"></i></button>';
                        }
                        if (canDeleteUsers) {
                            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, 'asc']],
            pageLength: 25,
            language: { url: '//cdn.datatables.net/plug-ins/1.13.6/i18n/tr.json' }
        });
    }

    initTable();

    $('#filterForm').on('submit', function(e) {
        e.preventDefault();
        const filters = Object.fromEntries(new FormData(this).entries());
        initTable(filters);
    });

    // Create
    $('#createUserForm').on('submit', function(e) {
        e.preventDefault();
        let formData = $(this).serialize();
        formData += '&_token={{ csrf_token() }}';
        formData += '&is_active=' + ($('input[name="is_active"]').is(':checked') ? '1' : '0');

        $.ajax({
            url: '{{ route("backoffice.users.store") }}',
            method: 'POST',
            data: formData,
            success: function(response) {
                $('#createUserModal').modal('hide');
                $('#createUserForm')[0].reset();
                Swal.fire('Başarılı!', 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('Doğrulama Hatası!', errorMsg, 'error');
                } else {
                    Swal.fire('Hata!', xhr.responseJSON?.message || 'Bir hata oluştu', 'error');
                }
            }
        });
    });

    // Edit
    $(document).on('click', '.btn-edit', function() {
        const id = $(this).data('id');
        $.ajax({
            url: '{{ route("backoffice.users.show", ":id") }}'.replace(':id', id),
            success: function(response) {
                const u = response.user;
                $('#editUserId').val(u.id);
                $('#editPermissionGroupId').val(u.permission_group_id || '');
                $('#editUsername').val(u.username);
                $('#editFullName').val(u.full_name);
                $('#editEmail').val(u.email);
                $('#editPassword').val('');
                setMultiSelectValues('#editSiteIds', u.allowed_site_ids || []);
                $('#editIsActive').prop('checked', u.is_active);
                $('#editUserModal').modal('show');
            }
        });
    });

    $('#editUserForm').on('submit', function(e) {
        e.preventDefault();
        const id = $('#editUserId').val();
        let formData = $(this).serialize();
        formData += '&_token={{ csrf_token() }}&_method=PUT';
        formData += '&is_active=' + ($('#editIsActive').is(':checked') ? '1' : '0');

        $.ajax({
            url: '{{ route("backoffice.users.update", ":id") }}'.replace(':id', id),
            method: 'POST',
            data: formData,
            success: function(response) {
                $('#editUserModal').modal('hide');
                Swal.fire('Başarılı!', 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('Doğrulama Hatası!', errorMsg, 'error');
                } else {
                    Swal.fire('Hata!', xhr.responseJSON?.message || 'Bir hata oluştu', 'error');
                }
            }
        });
    });

    // Toggle
    $(document).on('click', '.btn-toggle', function() {
        const id = $(this).data('id');
        $.ajax({
            url: '{{ route("backoffice.users.toggle-status", ":id") }}'.replace(':id', id),
            method: 'POST',
            data: { _token: '{{ csrf_token() }}' },
            success: function(response) {
                Swal.fire('Başarılı!', response.message, 'success');
                table.ajax.reload();
            },
            error: function(xhr) {
                Swal.fire('Hata!', xhr.responseJSON?.message || 'Bir hata oluştu', 'error');
            }
        });
    });

    // Delete
    $(document).on('click', '.btn-delete', function() {
        const id = $(this).data('id');
        Swal.fire({
            title: 'Emin misiniz?',
            text: 'Bu kullanıcıyı silmek istediğinizden emin misiniz?',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: 'Evet, Sil',
            cancelButtonText: 'İptal',
            confirmButtonColor: '#dc3545'
        }).then((result) => {
            if (result.isConfirmed) {
                $.ajax({
                    url: '{{ route("backoffice.users.destroy", ":id") }}'.replace(':id', id),
                    method: 'POST',
                    data: { _token: '{{ csrf_token() }}', _method: 'DELETE' },
                    success: function(response) {
                        Swal.fire('Başarılı!', response.message, 'success');
                        table.ajax.reload();
                    },
                    error: function(xhr) {
                        Swal.fire('Hata!', xhr.responseJSON?.message || 'Bir hata oluştu', 'error');
                    }
                });
            }
        });
    });
});
</script>
@endpush
