<?php
if ($_SESSION['user_role'] == 1) {

    $lessonArr = array();
    $lessonNameArr = array();
    _selectNoParam(
        $gstmt,
        $gcount,
        "SELECT lessonid, classid, sname FROM `att` INNER JOIN class ON att.classid = class.id WHERE att.this_on = '" . $this_on . "' and tid = '" . $_SESSION['user_id'] . "'  GROUP BY classid, lessonid",
        $glessonid,
        $gclassid,
        $sname
    );


    $orson = [];
    $uldsen = [];
    while (_fetch($gstmt)) {
        $gcag = 0;
        _selectRowNoParam(
            "SELECT cag, lessonName FROM `tlesson` WHERE id = '" . $glessonid . "'",
            $gcag,
            $glessonName
        );

        $gtoo = 0;
        _selectRowNoParam(
            "SELECT COUNT(id) from att WHERE att.this_on = '" . $this_on . "' and lessonid = '$glessonid,' and classid = '$gclassid' and tid = " . $_SESSION['user_id'],
            $gtoo
        );
        array_push($orson, $gtoo * 2);
        array_push($uldsen, $gcag - $gtoo * 2);

        array_push($lessonNameArr, $sname . " " . $glessonName);
    }

    $gra = new stdClass;
    $gra->name = "Орсон";
    $gra->data = $orson;
    array_push($lessonArr, $gra);
    $gra = new stdClass;
    $gra->name = "Үлдсэн";
    $gra->data = $uldsen;
    array_push($lessonArr, $gra);
?>
    <link rel="stylesheet" href="https://uicdn.toast.com/tui-calendar/latest/tui-calendar.css">
    <link rel="stylesheet" href="https://uicdn.toast.com/tui.time-picker/latest/tui-time-picker.css">
    <link rel="stylesheet" href="https://uicdn.toast.com/tui.date-picker/latest/tui-date-picker.css">

    <!-- JavaScript -->
    <script src="https://uicdn.toast.com/tui.code-snippet/v1.5.0/tui-code-snippet.js"></script>
    <script src="https://uicdn.toast.com/tui.time-picker/latest/tui-time-picker.js"></script>
    <script src="https://uicdn.toast.com/tui.date-picker/latest/tui-date-picker.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/chance/1.1.7/chance.min.js"></script>
    <script src="https://uicdn.toast.com/tui-calendar/latest/tui-calendar.js"></script>
    <style>
        /* Edit товчлуурыг нуух */
        .tui-full-calendar-section-button {
            display: none !important;
        }

        .tui-full-calendar-popup {
            font-weight: 500 !important;
        }
    </style>
    <div class="page-header">
        <div class="page-header-left d-flex align-items-center">
            <div class="page-header-title">
                <h5 class="m-b-10 text-danger"><?= $this_on ?> ХИЧЭЭЛИЙН ЖИЛ</h5>
            </div>
            <ul class="breadcrumb">
                <li class="breadcrumb-item"><a href="/">Эхлэл</a></li>
            </ul>
        </div>
    </div>
    <div class="main-content">
        <div class="card stretch stretch-full d-none d-md-block">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <h3 id="renderRange">СҮҮЛИЙН ХИЧЭЭЛ ОРОЛТУУД</h3>
                    <div id="menu">
                        <span id="menu-navi" class="d-flex">
                            <button type="button" class="btn btn-light-brand m-1" data-action="move-today">Өнөөдөр</button>
                            <button type="button" class="btn btn-light-brand m-1" data-action="move-prev">
                                <i class="calendar-icon ic-arrow-line-left" data-action="move-prev">←</i>
                            </button>
                            <button type="button" class="btn btn-light-brand m-1" data-action="move-next">
                                <i class="calendar-icon ic-arrow-line-right" data-action="move-next">→</i>
                            </button>
                        </span>
                    </div>
                </div>
                <div class="d-flex flex-column mb-3" id="loadingDiv"></div>
                <div id="calendar"></div>
            </div>
        </div>
        <div class="card stretch stretch-full">
            <div class="card-header">
                <h5 class="card-title">ЦАГИЙН ГҮЙЦЭТГЭЛ</h5>
            </div>
            <div class="card-body">
                <div id="chart"></div>
            </div>
        </div>
    </div>
    <?php require ROOT . "/pages/main-end.php"; ?>
    <div class="modal fade-scale" id="detial" tabindex="-1" aria-labelledby="detial" aria-hidden="true" data-bs-dismiss="ou">
        <div class="modal-dialog modal-xl" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="detialLabel">ИРЦ БҮРТГЭЛ</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body" id="modal-body">

                </div>
            </div>
        </div>
    </div>
    <div class="modal fade-scale" id="deleteModal" tabindex="-1" aria-labelledby="deleteLabel" aria-hidden="true">
        <div class="modal-dialog modal-md">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="deleteLabel">ИРЦ БҮРТГЭЛ УСТГАХ</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body" id="modal-dbody">

                </div>
                <input type="text" style="display: none;" id="deleteId" />
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Болих</button>
                    <button type="button" class="btn btn-danger" onclick="attDelete()">Устгах</button>
                </div>
            </div>
        </div>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/apexcharts"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Монгол 7 хоногийн өдрүүд
            const weekDays = ['Ням', 'Даваа', 'Мягмар', 'Лхагва', 'Пүрэв', 'Баасан', 'Бямба'];

            // Монгол сарууд
            const monthNames = [
                '1-р сар', '2-р сар', '3-р сар', '4-р сар', '5-р сар', '6-р сар',
                '7-р сар', '8-р сар', '9-р сар', '10-р сар', '11-р сар', '12-р сар'
            ];

            const calendar = new tui.Calendar('#calendar', {
                defaultView: 'month',
                month: {
                    dayNames: weekDays,
                    visibleWeeksCount: 6,
                    startDayOfWeek: 1, // Даваа гарагаас эхлэнэ
                    isAlways6Week: false
                },
                week: {
                    dayNames: weekDays,
                    startDayOfWeek: 1 // Даваа гарагаас эхлэнэ
                },
                template: {
                    monthDayname: function(model) {
                        return '<span class="tui-full-calendar-weekday-grid-date">' + weekDays[model.day] + '</span>';
                    },
                    monthGridHeader: function(model) {
                        const date = new Date(model.date);
                        const day = date.getDate();
                        const today = new Date();

                        // Өнөөдрийг тодруулах
                        const isToday = date.getDate() === today.getDate() &&
                            date.getMonth() === today.getMonth() &&
                            date.getFullYear() === today.getFullYear();

                        return '<span class="tui-full-calendar-weekday-grid-date' +
                            (isToday ? ' tui-full-calendar-weekday-grid-date-decorator' : '') +
                            '">' + day + '</span>';
                    },
                    monthGridHeaderExceed: function(hiddenCount) {
                        return '<span class="weekday-grid-more-schedules">+' + hiddenCount + '</span>';
                    },
                    monthMoreTitleDate: function(date) {
                        var d = new Date(date); // string -> Date
                        return monthNames[d.getMonth()] + ' ' + d.getDate() + ' (' + weekDays[d.getDay()] + ')';
                    },
                    popupDetailBody: function(schedule) {
                        const start = new Date(schedule.start);
                        const end = new Date(schedule.end);

                        return `
                            <div class="tui-full-calendar-popup-detail-item">
                                <span id="body${schedule.id}" class="tui-full-calendar-content">${schedule.body || 'Тайлбаргүй'}</span>
                                <div class="custom-popup-buttons d-flex">
                                    <button class="custom-delete-btn btn btn-danger w-100 m-1" role='button' data-bs-toggle='modal' data-bs-target='#deleteModal' data-id="${schedule.id}">Устгах</button>
                                    <button class="custom-detial-btn btn btn-warning w-100 m-1" role='button' data-bs-toggle="modal" data-bs-target="#detial" role="button" data-detial-id="${schedule.id}">Ирц бүртгэл</button>
                                </div>
                            </div>
                        `;
                    },
                    popupDetailDate: function(isAllDay, start, end) {
                        let dateStr = monthNames[start.getMonth()] + 'ын ' + start.getDate() + '-н';

                        if (!isAllDay) {
                            dateStr += ', ' + start.getHours() + ':' + (start.getMinutes() < 10 ? '0' : '') + start.getMinutes();
                            dateStr += ' - ' + end.getHours() + ':' + (end.getMinutes() < 10 ? '0' : '') + end.getMinutes();
                        }

                        return dateStr;
                    }
                },
                useDetailPopup: true,
                useCreationPopup: false,
                useFormPopup: true,
                isReadOnly: false,
            });

            function formatEventTime(schedule) {
                const start = new Date(schedule.start);
                const end = new Date(schedule.end);
                return `${start.getDate()}-р сарын ${start.getHours()}:${start.getMinutes().toString().padStart(2, '0')} - ${end.getHours()}:${end.getMinutes().toString().padStart(2, '0')}`;
            }
            // Жишээ үйл явдлууд (нэг өдөрт 3 үйл явдал)
            const today = new Date();
            const events = [];

            calendar.createSchedules(events);

            // Одоогийн сарыг харуулах
            updateRenderRangeText();

            // Цонхны хэмжээ өөрчлөгдөхөд календарыг дахин тохируулах
            window.addEventListener('resize', function() {
                calendar.render();
            });

            // Цэсний товчнууд
            document.getElementById('menu-navi').addEventListener('click', function(e) {
                const target = e.target;
                const action = target.getAttribute('data-action');

                if (!action) {
                    return;
                }

                if (action === 'move-prev') {
                    calendar.prev();
                } else if (action === 'move-today') {
                    calendar.today();
                } else if (action === 'move-next') {
                    calendar.next();
                }

                updateRenderRangeText();
                loadEvents();
            });

            loadEvents();

            function loadEvents() {
                console.log(calendar.getDate().getMonth() + 1);
                console.log(calendar.getDate().getFullYear());
                $.ajax({
                    url: "/home/teacher-lesson",
                    type: "POST",
                    data: {
                        sar: calendar.getDate().getMonth() + 1,
                        jil: calendar.getDate().getFullYear()
                    },
                    error: function(xhr, textStatus, errorThrown) {
                        $('#loadingDiv').html('<div class="loadText text-danger">Алдаа гарлаа</div>');
                    },
                    beforeSend: function() {
                        $('#loadingDiv').html('<div class="loader"></div>');
                    },
                    success: function(data) {
                        if (isJSON(data)) {
                            $('#loadingDiv').html('');
                            data = JSON.parse(data);
                            calendar.clear();
                            calendar.createSchedules(data);
                        } else {
                            $('#loadingDiv').html(data);
                        }
                    },
                    async: true
                });

            }
            // Сар, жилийг харуулах текст шинэчлэх
            function updateRenderRangeText() {
                const view = calendar.getViewName();
                const calDate = calendar.getDate();
                const year = calDate.getFullYear();
                const month = calDate.getMonth();

                document.getElementById('renderRange').textContent =
                    year + ' оны ' + monthNames[month];
            }
            document.getElementById('calendar').addEventListener('click', function() {
                calendar.render();
            });
            document.addEventListener('click', function(e) {
                if (e.target.classList.contains('custom-delete-btn')) {
                    const eventId = e.target.getAttribute('data-id');
                    console.log('Устгах товч дарсан:', eventId);
                    deleteAtt(eventId);
                }
                if (e.target.classList.contains('custom-detial-btn')) {
                    const eventId = e.target.getAttribute('data-detial-id');
                    console.log('Харах товч дарсан:', eventId);
                    detial(eventId);
                }
            });

            function deleteAtt(id) {
                $('#deleteId').val(id);
                $('#modal-dbody').html($('#body' + id).text() + ' утсгах уу?');
            }

            function detial(id) {
                console.log(id);
                row_click(id)
                $.ajax({
                    url: "../att/detial",
                    type: "POST",
                    data: {
                        mode: 2,
                        id: id
                    },
                    error: function(xhr, textStatus, errorThrown) {
                        $("#modal-body").html("Алдаа гарлаа !");
                    },
                    beforeSend: function() {
                        $('#modal-body').html("Түр хүлээнэ үү ...");
                    },
                    success: function(data) {
                        $('#modal-body').html(data);
                    },
                    async: true
                });
            };

            function isJSON(str) {
                try {
                    const obj = JSON.parse(str);
                    return typeof obj === 'object' && obj !== null;
                } catch (e) {
                    return false;
                }
            }
        });

        function attDelete() {
            $.ajax({
                url: "../att/ajax",
                type: "POST",
                data: {
                    mode: 4,
                    attid: $('#deleteId').val()
                },
                error: function(xhr, textStatus, errorThrown) {
                    $("#modal-dbody").html("Алдаа гарлаа !");
                },
                beforeSend: function() {
                    $('#modal-dbody').html("Түр хүлээнэ үү ...");
                },
                success: function(data) {
                    location.reload();
                },
                async: true
            });

        }
        window.onload = (event) => {
            var options = {
                series: <?php echo json_encode($lessonArr) ?>,
                chart: {
                    type: 'bar',
                    height: <?= (count($lessonNameArr) + 1) * 100 ?>,
                    stacked: true,
                },
                plotOptions: {
                    bar: {
                        horizontal: true,
                        dataLabels: {
                            total: {
                                enabled: true,
                                offsetX: 0,
                                style: {
                                    fontSize: '13px',
                                    fontWeight: 900
                                }
                            }
                        }
                    },
                },
                stroke: {
                    width: 1,
                    colors: ['#fff']
                },
                title: {
                    text: '<?= $user_fname ?> <?= $user_lname ?>'
                },
                xaxis: {
                    categories: <?php echo json_encode($lessonNameArr) ?>,
                    labels: {
                        formatter: function(val) {
                            return val + " цаг"
                        }
                    }
                },
                yaxis: {
                    title: {
                        text: undefined
                    },
                },
                tooltip: {
                    y: {
                        formatter: function(val) {
                            return val + " цаг"
                        }
                    }
                },
                fill: {
                    opacity: 1
                },
                legend: {
                    position: 'top',
                    horizontalAlign: 'left',
                    offsetX: 40
                }
            };

            var chart = new ApexCharts(document.querySelector("#chart"), options);
            chart.render();
        };
    </script>
<?php } else echo "Хандах эрх хүрэлцэхгүй байна"; ?>