<%-include("../partials/header.ejs") %>
<%-include("../partials/sidebar.ejs") %>
<div class="app-content">
    <%-include("../partials/navbar.ejs") %>

    <main>
        <div class="container-fluid">
            <div class="row m-1">
                <div class="col-12">
                    <h4 class="main-title">Öğrenci Skorları Geçmişi</h4>
                    <p>
                        Öğrencilere yeni değerler ekleyebilir ve silebilirsiniz 
                    </p>
                </div>
            </div>
            <div class="row">
                <div class="col-12">
                    <div class="card ">
                        <div class="card-header ">
                            <div class="d-flex flex-row flex-1">
                                <h5 class="flex-fill">
                                    Skor Geçmişi
                                </h5>
                                <div class="flex-min">
                                    <button class="btn btn-success" data-bs-target="#add_event" data-bs-toggle="modal" type="button">
                                        <i class="fa fa-plus"></i>
                                        Skor Ekle
                                    </button>
                                </div>
                            </div>
                        </div>
                        <div class="card-body p-0">
                            <div class="app-datatable-default overflow-auto">
                                <table class="table display app-data-table default-data-table" id="eventslist"></table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </main>
</div>
<div aria-hidden="true" class="modal fade" id="add_event" tabindex="-1">
    <div class="modal-dialog modal-dialog-centered modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Yeni Skor Ekle</h5>
                <button aria-label="Close" class="btn-close m-0 fs-5" data-bs-dismiss="modal" type="button"></button>
            </div>
            <form class="modal-body" id="eventsaveform" onsubmit="saveEvent(this);return false;">
                <div class="row app-form">
                    <div class="col-md-6 mt-3">
                        <label class="form-label">Öğrenci</label>
                        <select name="student" class="form-control student" required></select>
                    </div>
                    <div class="col-md-6 mt-3">
                        <label class="form-label">Puan Kataloğu</label>
                        <select name="catalog" class="form-control catalog" required></select>
                    </div>
                </div>
            </form>
            <div class="modal-footer">
                <button class="btn btn-outline-success" type="submit" form="eventsaveform">Kaydet</button>
                <button class="btn btn-light-secondary" data-bs-dismiss="modal" type="button">Kapat</button>
            </div>
        </div>
    </div>
</div>
<script>
    $(function(){
        $('.catalog').select2({
            placeholder: 'Puan kataloğunda ara',
            minimumInputLength: 0,
            allowClear: true,
            dropdownParent: $('#add_event'),
            ajax: {
                url: '/catalog/list',
                method: "post",
                dataType: 'json',
                delay: 250,
                data: function (params) {
                    return {
                        start: 0,
                        length: 50,
                        search:{
                            value: params.term
                        }
                    };
                },
                processResults: function (data) {
                    return {
                        results: data.data.map(e => {
                            return {
                                id: e.id,
                                text: e.name + ` (${e.score < 0 ? e.score : "+" + e.score})`
                            }
                        })
                    };
                }
            }
        });
        $('.student').select2({
            placeholder: 'Öğrencilerde ara',
            minimumInputLength: 0,
            allowClear: true,
            dropdownParent: $('#add_event'),
            ajax: {
                url: '/students/list',
                method: "post",
                dataType: 'json',
                delay: 250,
                data: function (params) {
                    return {
                        start: 0,
                        length: 50,
                        search:{
                            value: params.term
                        }
                    };
                },
                processResults: function (data) {
                    return {
                        results: data.data.map(e => {
                            return {
                                id: e.id,
                                text: `${e.name} ${e.surname}`
                            }
                        })
                    };
                }
            }
        });
    })
</script>
<style>
    .select2-container{
        z-index: 10000;
    }
</style>

<script>
    let dataTable;
    $(function(){
        dataTable = $("#eventslist").DataTable({
            serverSide: true,
            processing: true,
            responsive: true,
            ajax: {
                url: "/events/list",
                method:"post"
            },
            columns: [
                {
                    width: "1%",
                    title: "#",
                    data: null,
                    render: function (data, type, row, meta) {
                        return meta.row + 1;
                    }
                },
                {
                    title: "Öğrenci",
                    data: null,
                    name: "fullname",
                    render: function (data, row) {
                        return `${data.studentname} ${data.studentsurname || ''}`;
                    }
                },
                {
                    title: "Puan Kataloğu",
                    data: "catalog",
                    name: "catalog"
                },
                {
                    title: "Puan",
                    data: "score",
                    name: "score",
                    render:e => {
                        return e < 0 ? `<span class="text-danger">${e.toString()}</span>` : `<span class="text-success">+${e}</span>`
                    }
                },
                {
                    title: "Tarih",
                    data: "created_at",
                    name: "created_at",
                    render: value => moment(value).format("DD.MM.YYYY HH:mm")
                },
                {
                    width: "1%",
                    title: "İşlemler",
                    data: null,
                    orderable: false, // İşlemlere göre sıralama yapılamasın
                    render: function (data) {
                        return `
                            <div class="btn-group d-flex flex-row flex-nowrap" role="group">
                                <button class="btn btn-sm btn-outline-danger text-nowrap" onclick="deleteEvent(${data.id})" title="Sil">
                                    <i class="fa fa-trash"></i>
                                    Sil
                                </button>
                            </div>`;
                    }
                }
            ],
            "language": {
                "url": "https://cdn.datatables.net/plug-ins/1.13.6/i18n/tr.json"
            }
        });
    });
    async function saveEvent(form)
    {
        blockui("#add_event .modal-content");
        $.ajax({
            url: "/event/store",
            type: "post",
            data: new FormData(form),
            processData: false,
            contentType: false,
            success: function(response) {
                dataTable.ajax.reload(null, false);
                $("#add_event").modal("hide");
                ublockui();
            },
            error: function(err) {
                ublockui();
            },
        });
    }
    async function deleteEvent(id)
    {
        if(confirm("Kaydı silmek istediğinize emin misiniz?"))
        {
            $.ajax({
                url: "/events/destroy",
                type: "post",
                data: {
                    id
                },
                success: function(response) {
                    dataTable.ajax.reload(null, false);
                    ublockui();
                },
                error: function(err) {
                    ublockui();
                },
            });
        }
    }
    async function updateStudent(form)
    {
        blockui("#update_student .modal-content");
        $.ajax({
            url: "/students/update",
            type: "post",
            data: new FormData(form),
            processData: false,
            contentType: false,
            success: function(response) {
                dataTable.ajax.reload(null, false);
                $("#update_student").modal("hide");
                ublockui();
            },
            error: function(err) {
                ublockui();
            },
        });
    }
    
    async function updateModal(tr)
    {
        let data = dataTable.row($(tr).closest('tr')).data();

        $("#update_student form").get(0).reset();
        $("#update_student [name='id']").val(data.id);

        $("#update_student form input,#update_student form textarea").each(function(){
            let name = this.name;
            $(this).val(data[name]);
        });
        $("#update_student form select").each(function(){
            let name = this.name;
            $(this).find("option:selected").removeAttr("selected");
            $(this).find(`option[value="${data[name]}"]`).attr("selected","selected");
        });
        $("#update_student").modal("show");
    }
    function blockui(ui)
    {
        $(blockui.id = ui).block({
            message: '<div class="loader-container-box"><div class="loader"></div></div>',
            //timeout: 13000,
            overlayCSS: {
                backgroundColor: 'rgba(var(--dark), 0.8)',
                opacity: 0.8,
                borderRadius: 'var(--app-border-radius)',
                cursor: 'wait'
            },
            css: {
                border: 0,
                padding: 0,
                backgroundColor: 'transparent'
            }
        });
    }
    function ublockui()
    {
        $(blockui.id).unblock()
    }
</script>
<%-include("../partials/footer.ejs") %>