@extends('backoffice.layouts.app')

@section('title', 'Hazir Cevaplar')

@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-chat-left-text me-2"></i>Hazir Cevaplar</h2>
                    <p class="text-muted">Reddetme icin kullanilacak hazir cevaplari yonetin</p>
                </div>
                @if(can_access('canned_responses', 'create'))
                <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#createResponseModal">
                    <i class="bi bi-plus-circle me-2"></i>Yeni Hazir Cevap
                </button>
                @endif
            </div>
        </div>
    </div>

    <div class="card border-0 shadow-sm">
        <div class="card-body p-0">
            <div class="table-responsive">
                <table id="responsesTable" class="table table-hover mb-0">
                    <thead class="table-light">
                        <tr>
                            <th>Cevap</th>
                            <th>Olusturan</th>
                            <th width="160">Tarih</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="createResponseModal" 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>Yeni Hazir Cevap</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="createResponseForm">
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">Cevap <span class="text-danger">*</span></label>
                        <input type="text" name="content" class="form-control" required maxlength="255">
                        <div class="invalid-feedback"></div>
                    </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="editResponseModal" 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>Hazir Cevabi Duzenle</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="editResponseForm">
                <input type="hidden" id="editResponseId">
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">Cevap <span class="text-danger">*</span></label>
                        <input type="text" name="content" id="editContent" class="form-control" required maxlength="255">
                        <div class="invalid-feedback"></div>
                    </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('canned_responses', 'update') ? 'true' : 'false' !!};
    const canDelete = {!! can_access('canned_responses', 'delete') ? 'true' : 'false' !!};

    const table = $('#responsesTable').DataTable({
        processing: true,
        serverSide: false,
        ajax: '{{ route("backoffice.canned-responses.index") }}',
        columns: [
            { data: 'content' },
            { 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: [[2, 'desc']],
        pageLength: 25,
        language: { url: '//cdn.datatables.net/plug-ins/1.13.6/i18n/tr.json' }
    });

    $('#createResponseForm').on('submit', function(e) {
        e.preventDefault();
        const $form = $(this);
        $form.find('.is-invalid').removeClass('is-invalid');
        $form.find('.invalid-feedback').text('');

        $.ajax({
            url: '{{ route("backoffice.canned-responses.store") }}',
            method: 'POST',
            data: {
                content: $form.find('[name="content"]').val(),
                _token: '{{ csrf_token() }}'
            },
            success: function(response) {
                $('#createResponseModal').modal('hide');
                $form[0].reset();
                Swal.fire('Basarili!', response.message, 'success');
                table.ajax.reload();
            },
            error: function(xhr) {
                if (xhr.status === 422 && xhr.responseJSON.errors) {
                    const errors = xhr.responseJSON.errors;
                    Object.keys(errors).forEach(function(key) {
                        const input = $form.find('[name="' + key + '"]');
                        input.addClass('is-invalid');
                        input.siblings('.invalid-feedback').text(errors[key][0]);
                    });
                } else {
                    Swal.fire('Hata!', xhr.responseJSON?.message || 'Bir hata olustu', 'error');
                }
            }
        });
    });

    $(document).on('click', '.btn-edit', function() {
        const id = $(this).data('id');
        $.ajax({
            url: '{{ route("backoffice.canned-responses.show", ":id") }}'.replace(':id', id),
            success: function(response) {
                $('#editResponseId').val(response.response.id);
                $('#editContent').val(response.response.content);
                $('#editResponseModal').modal('show');
            }
        });
    });

    $('#editResponseForm').on('submit', function(e) {
        e.preventDefault();
        const id = $('#editResponseId').val();
        const $form = $(this);
        $form.find('.is-invalid').removeClass('is-invalid');
        $form.find('.invalid-feedback').text('');

        $.ajax({
            url: '{{ route("backoffice.canned-responses.update", ":id") }}'.replace(':id', id),
            method: 'POST',
            data: {
                content: $('#editContent').val(),
                _token: '{{ csrf_token() }}',
                _method: 'PUT'
            },
            success: function(response) {
                $('#editResponseModal').modal('hide');
                Swal.fire('Basarili!', response.message, 'success');
                table.ajax.reload();
            },
            error: function(xhr) {
                if (xhr.status === 422 && xhr.responseJSON.errors) {
                    const errors = xhr.responseJSON.errors;
                    Object.keys(errors).forEach(function(key) {
                        const input = $form.find('[name="' + key + '"]');
                        input.addClass('is-invalid');
                        input.siblings('.invalid-feedback').text(errors[key][0]);
                    });
                } else {
                    Swal.fire('Hata!', xhr.responseJSON?.message || 'Bir hata olustu', 'error');
                }
            }
        });
    });

    $(document).on('click', '.btn-delete', function() {
        const id = $(this).data('id');
        Swal.fire({
            title: 'Emin misiniz?',
            text: 'Bu hazir cevabi silmek istediginizden emin misiniz?',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: 'Evet, Sil',
            cancelButtonText: 'Iptal',
            confirmButtonColor: '#dc3545'
        }).then((result) => {
            if (result.isConfirmed) {
                $.ajax({
                    url: '{{ route("backoffice.canned-responses.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 || 'Bir hata olustu', 'error');
                    }
                });
            }
        });
    });
});
</script>
@endpush
