@extends('layouts.app')

@section('style')
<link href="https://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.18/summernote.min.css" rel="stylesheet">
@endsection

@section('content')
<main class="py-4" style="flex: 1;">
    <div class="container">
        <div class="d-grid gap-2 d-md-flex justify-content-md-end mb-4">
            <button class="btn btn-success" data-bs-toggle="modal" data-bs-target="#addModal">
                <i class="fa-solid fa-plus"></i> เพิ่มข้อมูล
            </button>
        </div>
        <div class="row justify-content-center">
            <div class="col-md-12">
                <div class="card">
                    <div class="card-header">{{ __('เทมเพลต') }}</div>
                    <div class="card-body bg-white">
                        <div style="overflow-x: auto;">
                            <table id="templateTable" class="table table-striped table-bordered" style="width:100%">
                                <thead>
                                    <tr>
                                        <th style="width: 5%;">ลำดับ</th>
                                        <th style="width: 20%;">รูปภาพ</th>
                                        <th style="width: 20%;">ชื่อเกม</th>
                                        <th style="width: 40%;">รายละเอียดเกม</th>
                                        <th style="width: 15%;">จัดการ</th>
                                    </tr>
                                </thead>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</main>

@include('modals.add_template')
@include('modals.edit_template')
@include('modals.map_template_questions')

@endsection

@section('script')
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/2.9.1/umd/popper.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.18/summernote.min.js"></script>
<script src="{{ asset('vendor/laravel-filemanager/js/stand-alone-button.js') }}"></script>
<script>
    const routePrefix = "{{ url('filemanager') }}";

    document.addEventListener('DOMContentLoaded', function() {
        setupSummernote();
        initializeFileManagers();
        initializeDataTable();
        setupFormSubmissions();
        setupModalReset();
    });

    function setupSummernote() {
        $('#summernote').summernote({
            height: 300,
            callbacks: {
                onChange: function(contents) {
                    $(this).siblings('textarea').val(contents);
                }
            }
        });

        $('#edit_summernote').summernote({
            height: 300,
            callbacks: {
                onChange: function(contents) {
                    $(this).siblings('textarea').val(contents);
                }
            }
        });
    }

    function initializeFileManagers() {
        $('#lfm').filemanager('image', {
            prefix: routePrefix
        });
        $('#edit_lfm').filemanager('image', {
            prefix: routePrefix
        });
    }

    function initializeDataTable() {
        $('#templateTable').DataTable({
            ajax: {
                url: '{{ route("template_get_data") }}',
                method: 'GET',
                dataSrc: '',
                error: function(xhr, status, error) {
                    console.error('AJAX Error:', status, error);
                }
            },
            columns: [{
                    data: null,
                    render: (data, type, row, meta) => meta.row + 1
                },
                {
                    data: 'image_url',
                    render: (data) => `<img src="${data}" style="height: 5rem; width: auto;">`
                },
                {
                    data: 'template_name'
                },
                {
                    data: 'description'
                },
                {
                    data: 'id',
                    render: (data) => generateActionButtons(data)
                }
            ]
        });
    }

    function setupFormSubmissions() {
        $('#addForm').submit(handleAddFormSubmit);
        $('#editForm').submit(handleEditFormSubmit);
        $('#mapForm').submit(handleMapFormSubmit);
    }

    function handleAddFormSubmit(event) {
        event.preventDefault();
        $.ajax({
            url: '{{ route("template_store") }}',
            method: 'POST',
            data: $(this).serialize(),
            success: function() {
                $('#addModal').modal('hide');
                reloadDataTable();
                showSuccessAlert('เพิ่มเทมเพลตสำเร็จแล้ว');
                resetAddForm();
            },
            error: function() {
                showErrorAlert('เกิดข้อผิดพลาดขณะเพิ่มเทมเพลต');
            }
        });
    }

    function handleEditFormSubmit(event) {
        event.preventDefault();
        $.ajax({
            url: '{{ route("template_update") }}',
            method: 'POST',
            data: $(this).serialize(),
            success: function() {
                $('#editModal').modal('hide');
                reloadDataTable();
                showSuccessAlert('อัปเดตเทมเพลตสำเร็จแล้ว');
                resetEditForm();
            },
            error: function() {
                showErrorAlert('เกิดข้อผิดพลาดขณะอัพเดตเทมเพลต');
            }
        });
    }

    function handleMapFormSubmit(event) {
        event.preventDefault();
        $.ajax({
            url: '{{ route("map_template_store") }}',
            method: 'POST',
            data: $(this).serialize(),
            success: function() {
                $('#mapModal').modal('hide');
                reloadDataTable();
                showSuccessAlert('แมพปิ้งคำตอบถูกบันทึกสำเร็จ');
                resetEditForm();
            },
            error: function() {
                showErrorAlert('เกิดข้อผิดพลาดขณะบันทึกแมพปิ้งคำตอบ');
            }
        });
    }

    function resetAddForm() {
        $('#addForm').trigger('reset');
        $('#summernote').summernote('code', '');
        $('#holder').empty();
    }

    function resetEditForm() {
        $('#editForm').trigger('reset');
        $('#edit_summernote').summernote('code', '');
        $('#edit_holder').empty();
    }

    function setupModalReset() {
        $('#addModal').on('hidden.bs.modal', resetAddForm);
        $('#editModal').on('hidden.bs.modal', resetEditForm);
    }

    function editTemplate(id) {
        $.ajax({
            url: '{{ route("template_get_edit") }}',
            method: 'GET',
            data: {
                id
            },
            success: function(data) {
                populateEditModal(data);
                $('#editModal').modal('show');
            },
            error: function() {
                showErrorAlert('เกิดข้อผิดพลาดขณะดึงข้อมูลเทมเพลต');
            }
        });
    }

    function mapTemplate(id) {
        $.ajax({
            url: '{{ route("template_get_map") }}',
            method: 'GET',
            data: {
                id
            },
            success: function(data) {
                populateMapModal(data);
                $('#mapModal').modal('show');
            },
            error: function() {
                showErrorAlert('เกิดข้อผิดพลาดขณะดึงข้อมูลแมพปิ้ง');
            }
        });
    }

    function deleteTemplate(id) {
        Swal.fire({
            title: 'คุณแน่ใจว่าต้องการลบเทมเพลตนี้หรือไม่',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            confirmButtonText: 'ยืนยัน',
            cancelButtonText: 'ยกเลิก'
        }).then((result) => {
            if (result.isConfirmed) {
                $.ajax({
                    url: '{{ route("template_delete") }}',
                    method: 'POST',
                    data: {
                        _token: '{{ csrf_token() }}',
                        id
                    },
                    success: function() {
                        Swal.fire('ลบเทมเพลตสำเร็จแล้ว', '', 'success').then(reloadDataTable);
                    },
                    error: function() {
                        showErrorAlert('เกิดข้อผิดพลาดขณะลบเทมเพลต');
                    }
                });
            }
        });
    }

    function populateEditModal(data) {
        $('#edit_template_name').val(data.template_name);
        $('#edit_summernote').summernote('code', data.description);
        $('#edit_image_url').val(data.image_url);
        $('#edit_id').val(data.id);
        const image = $('<img>')
            .attr('src', data.image_url)
            .attr('alt', 'Template Image')
            .css('height', '5rem');
        $('#edit_holder').empty().append(image);
    }

    function populateMapModal(data) {
        $('#templates-container').empty();

        data.template_questions.forEach((template_question, index) => {
            const options = data.questions_all.map(question => {
                const selected = question.id === template_question.question_id ? 'selected' : '';
                return `<option value="${question.id}" ${selected}>${question.question_text}</option>`;
            }).join('');

            const templateHtml = `
                <div id="template_id_${index}">
                    <input type="hidden" id="template_questions_id_${index}" name="template_questions_id[]" value="${template_question.id}">
                    <div class="template-item mt-3">
                        <label class="form-label">ลำดับคำถาม</label>
                        <input type="number" class="form-control" name="question_order[]" placeholder="ลำดับคำถาม" value="${template_question.question_order}">
                    </div>
                    <div class="template-item mt-3">
                        <label class="form-label">รหัสคำถามถัดไป</label>
                        <select class="form-select" name="question_id[]">
                            <option value="">เลือกรหัสคำถามถัดไป</option>
                            ${options}
                        </select>
                    </div>
                    <div class="template-item mt-3">
                        <button type="button" class="btn btn-danger btn-sm" onclick="deleteTemplate(${index})">
                            <i class="fa-solid fa-trash"></i> ลบ
                        </button>
                    </div>
                </div>
            `;

            $('#templates-container').append(templateHtml);
        });

        $('#template_id').val(data.template.id);
    }

    function deleteTemplate(index) {
        const templateQuestionsId = $(`#template_questions_id_${index}`).val();

        if (!templateQuestionsId) {
            alert('ไม่พบข้อมูลแมพปิ้งที่จะลบ');
            return;
        }

        Swal.fire({
            title: 'คุณแน่ใจว่าต้องการลบแมพปิ้งนี้หรือไม่',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            confirmButtonText: 'ยืนยัน',
            cancelButtonText: 'ยกเลิก'
        }).then((result) => {
            if (result.isConfirmed) {
                $.ajax({
                    url: '{{ route("map_templates_delete") }}',
                    method: 'POST',
                    data: {
                        _token: '{{ csrf_token() }}',
                        id: templateQuestionsId
                    },
                    success: function() {
                        Swal.fire('ลบแมพปิ้งสำเร็จแล้ว', '', 'success');
                        $(`#template_id_${index}`).remove();
                    },
                    error: function() {
                        Swal.fire('เกิดข้อผิดพลาดขณะลบแมพปิ้ง', '', 'error');
                    }
                });
            }
        });
    }

    function generateActionButtons(id) {
        return `
            <button type="button" class="btn btn-secondary btn-sm" onclick="mapTemplate(${id})">
                <i class="fa-solid fa-gear"></i>
            </button>
            <button type="button" class="btn btn-warning btn-sm" onclick="editTemplate(${id})">
                <i class="fa-solid fa-pen-to-square"></i>
            </button>
            <button type="button" class="btn btn-danger btn-sm" onclick="deleteTemplate(${id})">
                <i class="fa-solid fa-trash"></i>
            </button>
        `;
    }

    function reloadDataTable() {
        $('#templateTable').DataTable().ajax.reload();
    }

    function showSuccessAlert(message) {
        Swal.fire(message, '', 'success');
    }

    function showErrorAlert(message) {
        Swal.fire(message, '', 'error');
    }

    document.getElementById('add-template-btn').addEventListener('click', function() {
        const container = document.getElementById('templates-container');
        const templateCount = container.querySelectorAll('input[name="question_order[]"]').length;

        $.ajax({
            url: '{{ route("questions_get_data") }}',
            method: 'GET',
            success: function(data) {
                const options = data.map(question => {
                    return `<option value="${question.id}">${question.question_text}</option>`;
                }).join('');

                const templateHtml = `
                    <div id="container_id_${templateCount}">
                        <div class="template-item mt-3">
                            <label class="form-label">ลำดับคำถาม</label>
                            <input type="number" class="form-control" name="question_order[]" placeholder="ลำดับคำถาม">
                        </div>
                        <div class="template-item mt-3">
                            <label class="form-label">รหัสคำถามถัดไป</label>
                            <select class="form-select" name="question_id[]">
                                <option value="">เลือกรหัสคำถามถัดไป</option>
                                ${options}
                            </select>
                        </div>
                        <div class="template-item mt-3">
                            <button type="button" class="btn btn-danger btn-sm" onclick="removeTemplate(${templateCount})">
                                <i class="fa-solid fa-trash"></i> ลบ
                            </button>
                        </div>
                    </div>
                `;

                const div = document.createElement('div');
                div.innerHTML = templateHtml;
                container.appendChild(div);
            },
            error: function() {
                showErrorAlert('เกิดข้อผิดพลาดขณะดึงข้อมูลคำถาม');
            }
        });
    });

    function removeTemplate(templateCount) {
        const itemToRemove = document.getElementById(`container_id_${templateCount}`);
        if (itemToRemove) {
            itemToRemove.remove();
        }
    }
</script>
@endsection