<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper bg-light">
    <section class="content-header p-0 d-flex align-items-end"
             style="height: 400px; background: url('<?= base_url('assets/img/wall2.png') ?>')">
        <div class="container-fluid pl-0 pr-0 pb-0 pt-4" style="background-color: rgba(255,255,255,0.7)">
            <div class="row m-0">
                <?php foreach ($info_box as $info) : ?>
                    <div class="col-md-2 col-3">
                        <div class="shadow small-box bg-<?= $info->box ?>">
                            <div class="inner">
                                <h5 class="mb-0"><b><?= $info->total; ?></b></h5>
                                <span><?= $info->title; ?></span>
                            </div>
                            <div class="icon">
                                <i class="fa fa-<?= $info->icon ?>" style="top: 5px"></i>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>
    </section>

    <section class="content mt-4">
        <div class="container-fluid">
            <div class="row">
                <div class="col-12">
                    <div class="card card-danger my-shadow">
                        <div class="card-header">
                            <h4 class="card-title">Penilaian</h4>
                        </div>
                        <div class="card-body">
                            <div class="row">
                                <?php foreach ($ujian_box as $info) : ?>
                                    <div class="col-6 col-md-3 col-lg-2" style="min-height: 60px">
                                        <div class="info-box border p-1" style="min-height: 60px">
                                            <div class="info-box-content p-1 text-danger">
                                                <span class="info-box-text text-sm"><?= $info->title; ?></span>
                                                <h5 class="info-box-number m-0"><?= $info->total; ?></h5>
                                            </div>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                                <div class="col-6 col-md-3 col-lg-2" style="min-height: 60px">
                                    <div class="info-box border p-1" style="min-height: 60px">
                                        <div class="info-box-content p-1 text-danger">
                                            <span class="info-box-text">Token
                                                <small class="float-right d-none" id="interval">-- : -- : --</small></span>
                                            <div>
                                                <h5 class="info-box-number m-0"
                                                    id="token-view"><?= $token->token != null ? $token->token : '- - - - - -' ?></h5>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <hr>
                            <div class="row">
                                <div class="col-12">
                                    <h6 class="text-center"><b>JADWAL PENILAIAN HARI INI</b></h6>
                                    <div class="col-12 table-responsive" id="table-container"></div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="col-md-4">
                    <div class="card card-primary my-shadow">
                        <div class="card-header">
                            <div class="card-title">
                                ELEARNING HARI INI
                            </div>
                            <div class="card-tools">
                                <a href="<?= base_url('elearning/jadwal') ?>" type="button" onclick="" class="btn btn-sm">
                                    <i class="fa fa-arrow-circle-right"></i>
                                </a>
                            </div>
                        </div>
                        <?php if (count($jadwal_kbm) > 0):?>
                            <div class="card-body p-2">
                                <div class="row">
                                    <span class="ml-3 text-bold">Kelas</span>
                                </div>
                                <hr class="m-0" />
                                <div class="row">
                                    <div class="col-5 col-sm-3">
                                        <div class="nav flex-column nav-tabs h-100">
                                            <?php
                                            $no = 1;
                                            foreach ($kelases as $ky => $kelas) :
                                                $active = $no == 1 ? 'active' : '';
                                                ?>
                                                <a class="nav-link <?= $active ?>"
                                                   href="#tab_<?= $ky ?>"
                                                   data-toggle="tab"><?= $kelas ?></a>
                                                <?php $no++; endforeach; ?>
                                        </div>
                                    </div>
                                    <div class="col-7 col-sm-9">
                                        <div class="tab-content">
                                            <div class="tab-content">
                                                <?php
                                                $no = 1;
                                                foreach ($kelases as $ky => $kelas) :
                                                    $active = $no == 1 ? 'active' : '';
                                                    ?>
                                                    <div class="tab-pane fade show <?= $active ?>" id="tab_<?= $ky ?>">
                                                        <div class="table-responsive">
                                                            <?php
                                                            $jadwalKbm = $jadwal_kbm[$ky] ?? [];
                                                            $table = "<table class='my-timetable w-100 border-bottom' id='tbl'>";
                                                            $tbody = "";
                                                            $idRow = 0;
                                                            $jadwalRows = 0;
                                                            $arrStart = [];

                                                            foreach ($times as $jam) {
                                                                $startTime = isset($jam['start']) ? $jam['start'] : '';
                                                                $arrStart[] = $startTime;
                                                                $rowSpanJam = isset($jam['span']) ? $jam['span'] : 12;

                                                                if ($idRow === 0) {
                                                                    $firstRow = "<tr class='row$idRow'>";

                                                                    $td0 = "<td class='column-time text-center align-top text-xs text-bold times p-0 frozen-column' rowspan='$rowSpanJam'>$startTime</td>";
                                                                    $td1 = "<td class='frozen-column-2' style='width: 30px; height: 10px;'></td>";
                                                                    $td2 = "<td class='row0'></td>";

                                                                    $firstRow .= $td0 . $td1 . $td2;
                                                                    $firstRow .= "</tr>";
                                                                    $tbody .= $firstRow;
                                                                } else {
                                                                    $minute = explode(':', $startTime)[1];
                                                                    $row = "<tr class='row$idRow'>";

                                                                    if ($idRow % 2 !== 0) {
                                                                        $row = "<tr class='row$idRow' data-time='$startTime'>";
                                                                    }

                                                                    if ($minute % 30 === 0) {
                                                                        $td0 = "<td class='column-time text-center align-top text-xs text-bold times p-0 frozen-column' rowspan='$rowSpanJam'>$startTime</td>";
                                                                        $row .= $td0;
                                                                    }

                                                                    $td1 = "<td class='frozen-column-2' style='width: 30px; height: 6px;'></td>";
                                                                    $row .= $td1;

                                                                    $tbody .= $row . "</tr>";
                                                                }

                                                                $scheduleRow = "<tr class='row" . ($idRow + 1) . "'>";

                                                                if ($idRow % 2 !== 0) {
                                                                    $scheduleRow = "<tr class='row" . ($idRow + 1) . "' data-time='$startTime'>";
                                                                }

                                                                $td1 = "<td class='frozen-column-3' style='width: 30px; height: 6px;'></td>";
                                                                $scheduleRow .= $td1;

                                                                $arr = isset($jadwalKbm->detail[$startTime]) ? $jadwalKbm->detail[$startTime] : null;
                                                                $rowSpan = $arr ? $arr['rows'] * 2 : 2;
                                                                $jadwalRows = $rowSpan;

                                                                $td = "<td class='align-middle row" . ($idRow + 1) . " text-xs' rowspan='$rowSpan'>";

                                                                $div = "<div class='h-100 pb-1' style='padding: 0 .1rem;'>";

                                                                if ($arr) {
                                                                    $flex = $rowSpan > 6 ? 'flex-column justify-content-center' : 'flex-row justify-content-between';
                                                                    $alertDivClass = 'alert alert-default-' . (isset($arr['id_mapel']) && $arr['id_mapel'] === '-1'
                                                                            ? 'warning' : (isset($arr['id_mapel']) && $arr['id_mapel'] === '-2' ? 'success'
                                                                                : (isset($arr['kode']) && $arr['kode'] ? 'info' : 'secondary'))) . " p-1 h-100 m-0 d-flex $flex";
                                                                    $alertDiv = "<div class='$alertDivClass'>";

                                                                    if (isset($arr['id_mapel']) && $arr['id_mapel'] === '-1') {
                                                                        $alertDiv .= "<div class='text-xs ml-1'>Istirahat</div>";
                                                                        $alertDiv .= "<div class='d-inline-block mx-1 text-nowrap'>{$arr['dari']} - {$arr['sampai']}</div>";
                                                                    } elseif (isset($arr['id_mapel']) && $arr['id_mapel'] === '-2') {
                                                                        $alertDiv .= "<div class='text-xs ml-1'>Upacara Bendera</div>";
                                                                        $alertDiv .= "<div class='d-inline-block mx-1 text-nowrap'>{$arr['dari']} - {$arr['sampai']}</div>";
                                                                    } else {
                                                                        if (isset($arr['kode']) && $arr['kode']) {
                                                                            $alertDiv .= "<div class='text-bold ml-1'>{$arr['kode']}</div>";
                                                                            $alertDiv .= "<div class='d-inline-block mx-1 text-nowrap'>{$arr['dari']} - {$arr['sampai']}</div>";
                                                                        }
                                                                    }
                                                                    $alertDiv .= "</div>";
                                                                    $div .= $alertDiv;
                                                                    $div .= "</div>";
                                                                    $td .= $div;
                                                                }
                                                                $scheduleRow .= $td;
                                                                $scheduleRow .= "</tr>";
                                                                $tbody .= $scheduleRow;
                                                                $jadwalRows -= 2;
                                                                $idRow += 2;
                                                            }
                                                            $table .= $tbody . "</table>";
                                                            echo $table;
                                                            ?>
                                                        </div>
                                                    </div>
                                                    <?php $no++; endforeach; ?>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        <?php else:?>
                            <div class="card-body">
                                Tidak ada jadwal hari ini
                            </div>
                        <?php endif; ?>
                    </div>
                    <div class="card card-success my-shadow">
                        <div class="card-header">
                            <div class="card-title">Aktifitas</div>
                        </div>
                        <div class="card-body">
                            <div id="log-list">
                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-8">
                    <div class="card card-light my-shadow mb-3">
                        <div class="card-header"><b>INFO/PENGUMUMAN</b></div>
                        <div class="card-body">
                            <div class="konten-pengumuman">
                                <div id="pengumuman">
                                </div>
                                <p id="loading-post" class="text-center d-none">
                                    <br/><i class="fa fa-spin fa-circle-o-notch"></i> Loading....
                                </p>
                                <div id="loadmore-post"
                                     onclick="getPosts()"
                                     class="text-center mt-4 loadmore d-none">
                                    <div class="btn btn-default">Muat Pengumuman lainnya ...</div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
    </section>
</div>

<div class="modal fade" id="komentarModal" tabindex="-1" role="dialog" aria-labelledby="komentarLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="komentarLabel">Tulis Komentar</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <img class="img-fluid img-circle img-sm" src="<?= base_url('assets/img/siswa.png') ?>" alt="Alt Text">
                <div class="img-push">
                    <?= form_open('create', array('id' => 'komentar')) ?>
                    <input type="hidden" id="id-post" name="id_post" value="">
                    <div class="input-group">
                        <input type="text" name="text" placeholder="Tulis komentar ..."
                               class="form-control form-control-sm" required>
                        <span class="input-group-append">
                                <button type="submit" class="btn btn-success btn-sm">Komentari</button>
                            </span>
                    </div>
                    <?= form_close() ?>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Batal</button>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="balasanModal" tabindex="-1" role="dialog" aria-labelledby="balasanLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="balasanLabel">Tulis Balasan</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <img class="img-fluid img-circle img-sm" src="<?= base_url('assets/img/siswa.png') ?>" alt="Alt Text">
                <div class="img-push">
                    <?= form_open('create', array('id' => 'balasan')) ?>
                    <input type="hidden" id="id-comment" name="id_comment" value="">
                    <div class="input-group">
                        <input type="text" name="text" placeholder="Tulis balasan ...."
                               class="form-control form-control-sm" required>
                        <span class="input-group-append">
                                <button type="submit" class="btn btn-success btn-sm">Balas</button>
                            </span>
                    </div>
                    <?= form_close() ?>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Batal</button>
            </div>
        </div>
    </div>
</div>

<script src="<?=base_url()?>/assets/app/js/ajax_request.js" type="text/javascript"></script>
<script src="<?= base_url() ?>/assets/app/js/rowspanizer.js"></script>
<script>
    let timerTokenView;
    var halaman = 0;
    var idGuru = "<?=$guru->id_guru?>";

    function createTime(d) {
        var date = new Date(d);

        var jam = date.getHours();
        var menit = date.getMinutes();
        var sJam;
        var sMenit;

        if (jam < 10) sJam = '0' + jam;
        else sJam = '' + jam;

        if (menit < 10) sMenit = '0' + menit;
        else sMenit = '' + menit;

        var hari = daysdifference(d);
        var time;

        if (hari === 0) {
            time = sJam + ':' + sMenit;
        } else if (hari === 1) {
            time = 'kemarin ' + sJam + ':' + sMenit;
        } else {
            time = jQuery.timeago(d) + ', ' + sJam + ':' + sMenit;
        }
        return time;
    }

    function daysdifference(last) {
        var startDay = new Date(last);
        var endDay = new Date();

        var millisBetween = startDay.getTime() - endDay.getTime();
        var days = millisBetween / (1000 * 3600 * 24);

        return Math.round(Math.abs(days));
    }

    function addComments(id, comments, append) {
        var comm = '';
        $.each(comments, function (i, v) {
            var dari, foto, avatar;
            if (v.dari == '0') {
                dari = 'Admin';
                avatar = v.foto != null ? '<img class="img-circle border" src="' + v.foto + '" alt="Img" width="40px" height="40px">' :
                    '<div class="btn-circle-sm btn-success media-left pt-1" style="width: 43px; height: 40px">A</div>'
            } else {
                if (v.dari_group == '2') {
                    dari = v.nama_guru;
                    foto = v.foto != null ? base_url + v.foto : base_url + 'assets/img/siswa.png';
                    avatar = '<img class="img-circle border" src="' + foto + '" alt="Img" width="40px" height="40px">';
                } else {
                    dari = v.nama_siswa;
                    foto = v.foto_siswa != null ? base_url + v.foto_siswa : base_url + 'assets/img/siswa.png';
                    avatar = '<img class="img-circle border" src="' + foto + '" alt="Img" width="40px" height="40px">';
                }
            }

            comm += '<div class="media mt-1" id="parent-reply' + v.id_comment + '">'
                + avatar +
                '    <div class="w-100 ml-2">' +
                '        <div class="media-body border pl-3 bg-light" style="border-radius: 20px">' +
                '            <span class="text-xs text-muted"><b>' + dari + '</b></span>' +
                '            <div class="comment-text pb-1">' + v.text + '</div>' +
                '        </div>' +
                '        <div class="ml-2">' +
                '            <span class="btn-sm mr-2 text-muted">' + createTime(v.tanggal) + '</span>' +
                '            <span id="trigger-reply' + v.id_comment + '" class="btn btn-sm mr-2 text-muted action-collapse" data-toggle="collapse" aria-expanded="true"' +
                '                              aria-controls="collapse-reply' + v.id_comment + '"' +
                '                              href="#collapse-reply' + v.id_comment + '"><b>' + v.jml + ' balasan</b></span>' +
                '            <span class="btn btn-sm mr-2 text-muted btn-toggle-reply"' +
                '                  data-id="' + v.id_comment + '" data-toggle="modal" data-target="#balasanModal">' +
                '                <i class="fas fa-reply"></i> <b>Balas</b></span>';
            if (v.dari_group === '2' && v.dari === idGuru) {
                comm += '            <span class="btn btn-sm text-muted" data-id="' + v.id_comment + '">' +
                    '                <i class="fa fa-trash mr-1"></i> Hapus' +
                    '            </span>';
            }
            comm += '        </div>' +
                '<div id="collapse-reply' + v.id_comment + '" class="p-2 collapse toggle-reply" data-id="' + v.id_comment + '" data-parent="#parent-reply' + v.id_comment + '">';
            if (v.jml != '0') {
                comm += '<div id="konten-reply' + v.id_comment + '"></div>' +
                    '<div id="loadmore-reply' + v.id_comment + '" onclick="getReplies(' + v.id_comment + ')" class="text-center mb-3 loadmore-reply">' +
                    '       <div class="btn btn-default">Muat balasan lainnya ...</div>' +
                    '</div>';
            }
            comm += '    <div id="loading-reply' + v.id_comment + '" class="text-center d-none">' +
                '        <div class="spinner-grow"></div>' +
                '    </div>' +
                '</div>' +
                '    </div>' +
                '</div>';
        });

        if (append) {
            $(`#konten${id}`).append(comm);
        } else {
            $(`#konten${id}`).prepend(comm);
        }

        $('.toggle-reply').on('shown.bs.collapse', function (e) {
            var konten = $(this);
            var id = konten.data('id');
            var list = $(this).find('.media').length;
            if (list === 0) $(`#loadmore-reply${id}`).click();
        });
    }

    function addReplies(id, replies, append) {
        //console.log('replies', replies);
        var repl = '';
        $.each(replies, function (i, v) {
            var sudahAda = $(`.media${v.id_reply}`).length;
            if (!sudahAda) {
                var dari, foto, avatar;
                if (v.dari == '0') {
                    dari = 'Admin';
                    avatar = v.foto != null ? '<img class="img-circle border" src="' + v.foto + '" alt="Img" width="35px" height="35px">' :
                        '<div class="btn-circle-sm btn-success media-left pt-1 mr-2" style="width: 37px">A</div>';
                } else {
                    if (v.dari_group == '2') {
                        dari = v.nama_guru;
                        foto = v.foto != null ? base_url + v.foto : base_url + 'assets/img/siswa.png';
                        avatar = '<img class="img-circle border" src="' + foto + '" alt="Img" width="35px" height="35px">';
                    } else {
                        dari = v.nama_siswa;
                        foto = v.foto_siswa != null ? base_url + v.foto_siswa : base_url + 'assets/img/siswa.png';
                        avatar = '<img class="img-circle border" src="' + foto + '" alt="Img" width="35px" height="35px">';
                    }
                }

                repl +=
                    '<div class="media mt-1 media' + v.id_reply + '">'
                    + avatar +
                    '    <div class="w-100">' +
                    '        <div class="media-body border pl-3" style="border-radius: 17px; background-color: #dee2e6">' +
                    '            <span class="text-xs text-muted"><b>' + dari + '</b></span>' +
                    '            <div class="comment-text">' + v.text +
                    '            </div>' +
                    '        </div>' +
                    '        <div class="ml-2">' +
                    '            <small class="btn-sm mr-2 text-muted">' + createTime(v.tanggal) + '</small>';
                if (v.dari_group === '2' && v.dari === idGuru) {
                    repl += '            <span class="btn btn-sm text-muted" data-id="' + v.id_reply + '">' +
                        '                <i class="fa fa-trash mr-1"></i> Hapus' +
                        '            </span>';
                }
                repl += '        </div>' +
                    '    </div>' +
                    '</div>';
            }
        });

        if (append) {
            $(`#konten-reply${id}`).append(repl);
        } else {
            $(`#konten-reply${id}`).prepend(repl);
        }
        //console.log('added', 'reply' + id);
    }

    function getComments(id) {
        $(`#loading${id}`).removeClass('d-none');
        $(`#loadmore${id}`).addClass('d-none');
        var $count = $(`#loadmore${id}`), page = $count.data('count');
        if (!page) page = 0;

        setTimeout(function () {
            $.ajax({
                url: base_url + "pengumuman/getcomment/" + id + "/" + page,
                type: "GET",
                success: function (response) {
                    //console.log('page', page);
                    //console.log("result", response);
                    page += 1;
                    currentPage = page;
                    $count.data('count', page);

                    if (response.length === 5) {
                        $(`#loadmore${id}`).removeClass('d-none');
                    }
                    $(`#loading${id}`).addClass('d-none');
                    addComments(id, response, true)
                }, error: function (xhr, status, error) {
                    console.log("error", xhr.responseText);
                }
            });
        }, 500);
    }

    function getReplies(id) {
        $(`#loading-reply${id}`).removeClass('d-none');
        $(`#loadmore-reply${id}`).addClass('d-none');
        var $count = $(`#loadmore-reply${id}`), page = $count.data('count');
        if (!page) page = 0;

        setTimeout(function () {
            $.ajax({
                url: base_url + "pengumuman/getreplies/" + id + "/" + page,
                type: "GET",
                success: function (response) {
                    //console.log('page', page);
                    //console.log("result", response);
                    page += 1;
                    currentPage = page;
                    $count.data('count', page);

                    //n >= start && n <= end
                    if (response.length === 5) {
                        $(`#loadmore-reply${id}`).removeClass('d-none');
                    }
                    $(`#loading-reply${id}`).addClass('d-none');
                    addReplies(id, response, true)
                }, error: function (xhr, status, error) {
                    console.log("error", xhr.responseText);
                }
            });
        }, 500);
    }

    function addPosts(response) {
        var card = '';

        if (response.length > 0) {
            $.each(response, function (i, v) {
                var dari, foto, avatar;
                if (v.dari == '0') {
                    dari = 'Admin';
                    avatar = v.foto != null ? '<img class="img-circle border" src="' + v.foto + '" alt="Img" width="50px" height="50px">' :
                        '<div class="btn-circle btn-success media-left pt-1">A</div>';
                } else {
                    if (v.dari_group == '2') {
                        dari = v.nama_guru;
                        foto = v.foto != null ? base_url + v.foto : base_url + 'assets/img/siswa.png';
                        avatar = '<img class="img-circle border" src="' + foto + '" alt="Img" width="50px" height="50px">';
                    } else {
                        dari = v.nama_siswa;
                        foto = v.foto_siswa != null ? base_url + v.foto_siswa : base_url + 'assets/img/siswa.png';
                        avatar = '<img class="img-circle border" src="' + foto + '" alt="Img" width="50px" height="50px">';
                    }
                }

                card += '<div class="card">' +
                    '    <div class="card-body" id="parent' + v.id_post + '">' +
                    '        <div class="media">' +
                    avatar +
                    '                <div class="media-body ml-3">' +
                    '                    <span class="font-weight-bold"><b>' + dari + '</b></span>' +
                    '                    <br/>' +
                    '                    <span class="text-gray">' + createTime(v.tanggal) + '</span>' +
                    '                </div>' +
                    '        </div>' +
                    '        <div class="mt-2">' + v.text + '</div>' +
                    '        <div class="text-muted">' +
                    '            <button type="button" class="btn btn-default btn-sm mr-2 btn-toggle"' +
                    '                    data-id="' + v.id_post + '" data-toggle="modal"' +
                    '                    data-target="#komentarModal"><i class="fas fa-reply mr-1"></i> Tulis komentar' +
                    '            </button>' +
                    '            <button type="button" id="trigger' + v.id_post + '" class="btn btn-default btn-sm mr-2 action-collapse"' +
                    '                    data-toggle="collapse" aria-expanded="true"' +
                    '                    aria-controls="collapse-' + v.id_post + '"' +
                    '                    href="#collapse-' + v.id_post + '">' +
                    '                <i class="fa fa-commenting-o mr-1"></i>' + v.jml + ' komentar' +
                    '            </button>';
                if (v.dari_group === '2' && v.dari === idGuru) {
                    card += '            <button type="button" class="btn btn-default btn-sm" data-id="' + v.id_post + '">' +
                        '                <i class="fa fa-trash mr-1"></i> Hapus' +
                        '            </button>';
                }
                card += '        </div>' +
                    '    </div>' +
                    '    <div id="collapse-' + v.id_post + '" class="p-2 collapse toggle-comment"' +
                    '         data-id="' + v.id_post + '" data-parent="#parent' + v.id_post + '">' +
                    '        <hr class="m-0">' +
                    '        <div id="konten' + v.id_post + '" class="p-4">' +
                    '        </div>' +
                    '        <div id="loading' + v.id_post + '" class="text-center d-none">' +
                    '            <div class="spinner-grow"></div>' +
                    '        </div>';
                if (v.jml == '0') {
                    card += '<div class="text-center">Tidak ada komentar</div>';
                } else {
                    card += '<div id="loadmore' + v.id_post + '"' +
                        '     onclick="getComments(' + v.id_post + ')"' +
                        '     class="text-center mt-4 loadmore">' +
                        '    <div class="btn btn-default">Muat komentar lainnya ...</div>' +
                        '</div>';
                }
                card += '</div>' +
                    '</div>';
            })
        } else {
            card = '<div class="card card-default">' +
                '<div class="card-body">' +
                ' <p>Tidak ada pengumuman</p>' +
                '</div></div>';
        }

        $('#pengumuman').html(card);

        $('.toggle-comment').on('shown.bs.collapse', function (e) {
            var konten = $(this);
            var id = konten.data('id');
            var list = $(this).find('.media').length;
            if (list === 0) $(`#loadmore${id}`).click();
        });

        $('#komentarModal').on('show.bs.modal', function (e) {
            var id = $(e.relatedTarget).data('id');
            $("#id-post").val(id);

            var isVisible = $(`#collapse-${id}`).hasClass('show');
            if (!isVisible) {
                $(`#trigger${id}`).click();
            }
        });

        $('#balasanModal').on('show.bs.modal', function (e) {
            var id = $(e.relatedTarget).data('id');
            $("#id-comment").val(id);

            var isVisible = $(`#collapse-reply${id}`).hasClass('show');
            if (!isVisible) {
                $(`#trigger-reply${id}`).click();
            }
        });

        $('#komentar').on('submit', function (e) {
            e.preventDefault();
            e.stopImmediatePropagation();

            //console.log("data", $(this).serialize());
            var id = $(this).find('input[name=id_post]').val();

            $.ajax({
                url: base_url + "pengumuman/savekomentar",
                data: $(this).serialize(),
                method: 'POST',
                dataType: "JSON",
                success: function (response) {
                    //console.log("result", response);
                    $('#komentarModal').modal('hide').data('bs.modal', null);
                    $('#komentarModal').on('hidden', function () {
                        $(this).data('modal', null);
                    });
                    addComments(id, response, false)
                    //window.location.href = base_url + 'pengumuman';
                },
                error: function (xhr, status, error) {
                    $('#komentarModal').modal('hide').data('bs.modal', null);
                    $('#komentarModal').on('hidden', function () {
                        $(this).data('modal', null);
                    });
                    showDangerToast('Error, komentar tidak terkirim');
                }
            });
        });

        $('#balasan').on('submit', function (e) {
            e.preventDefault();
            e.stopImmediatePropagation();

            //console.log("data", $(this).serialize());
            var id = $(this).find('input[name=id_comment]').val();

            $.ajax({
                url: base_url + "pengumuman/savebalasan",
                data: $(this).serialize(),
                method: 'POST',
                dataType: "JSON",
                success: function (response) {
                    //console.log("result", response);
                    $('#balasanModal').modal('hide').data('bs.modal', null);
                    $('#balasanModal').on('hidden', function () {
                        $(this).data('modal', null);
                    });
                    //window.location.href = base_url + 'pengumuman';
                    addReplies(id, response, false)
                },
                error: function (xhr, status, error) {
                    $('#balasanModal').modal('hide').data('bs.modal', null);
                    $('#balasanModal').on('hidden', function () {
                        $(this).data('modal', null);
                    });
                    showDangerToast('Error, balasan tidak terkirim');
                }
            });
        });

    }

    function getPosts() {
        $(`#loading-post`).removeClass('d-none');
        $(`#loadmore-post`).addClass('d-none');

        setTimeout(function () {
            $.ajax({
                url: base_url + "pengumuman/getpost/" + halaman,
                type: "GET",
                success: function (response) {
                    //console.log("result", response);
                    halaman += 1;

                    if (response.length === 5) {
                        $(`#loadmore-post`).removeClass('d-none');
                    }
                    $(`#loading-post`).addClass('d-none');
                    addPosts(response)
                }, error: function (xhr, status, error) {
                    console.log("error", xhr.responseText);
                }
            });
        }, 500);
    }

    function getGlobalToken() {
        if (globalToken != null) {
            const viewToken = $('#token-view');
            if (viewToken.length) viewToken.text(globalToken.token);
            if (globalToken.auto == '1' && adaJadwalUjian > 0) {
                $('#refresh-token').removeClass('d-none')
            }
        }
    }

    $(document).ready(function () {
        var colorBg = ['success', 'success', 'secondary', 'primary', 'warning', 'danger',
            'primary', "warning", "primary", "success", "primary", "success", "warning"
        ];

        function load_log() {
            $.ajax({
                url: base_url + "dashboard/getlog",
                data: {page: 1, limit: 10, filter: ['2','3']},
                method: "GET",
                success: function (data) {
                    //console.log(data);
                    if (data.logs.length > 0) {
                        var ul = '<ul class="products-list product-list-in-card pl-2 pr-2">';
                        $.each(data.logs, function (key, value) {
                            const nama_lengkap = value?.first_name === value?.last_name ? value?.first_name : value?.first_name +' '+ value?.last_name
                            var nama = value.id_group === '1' ? value.first_name : nama_lengkap;
                            var clr = colorBg[value.log_type];
                            var tgl = formatTanggal(value.log_time);//new Date('02/12/2018');
                            const guru = data.guru.find(g => g.id === value.id_user);
                            const siswa = data.siswa.find(s => s.id === value.id_user);
                            const admin = data.admins.find(a => a.id === value.id_user);
                            const fotoUser = guru ? guru.foto :
                                siswa ? siswa.foto :
                                    admin ? admin.foto : null;
                            const foto = base_url + (fotoUser ? fotoUser : '');
                            const initial = nama.charAt(0).toUpperCase();
                            ul += '  <li class="item">' +
                                '    <div class="media" style="line-height: 1.3">' +
                                '      <div data-siswa="'+initial+'" class="d-flex justify-content-center align-items-center bg-'+clr+' rounded-circle" style="width: 50px; height: 50px">' +
                                '        <img class="avatar-log img-circle" src="'+foto+'" width="44" height="44"  alt=""/></div>' +
                                //'<button class="btn btn-circle-sm btn-'+clr+' media-left">' + nama.charAt(0).toUpperCase()+'</button>' +
                                '      <div class="media-body ml-2">' +
                                '        <span>'+nama+'</span>' +
                                '        <br />' +
                                '        <span class="text-'+clr+' text-sm">'+value.log_desc+'</span>' +
                                '        <br />' +
                                '        <span class="text-xs text-muted">'+tgl+'</span>' +
                                '      </div>' +
                                '    </div>' +
                                '  </li>';

                        });
                        ul += '</ul>';
                        $('#log-list').html(ul);

                        $(".avatar-log").each(async function (i, v) {
                            const loaded = () => {
                                return new Promise((resolve) => {
                                    let obj = { pos: i };

                                    $(v)
                                        .on("error", function () {
                                            obj.error = true;
                                            const div = $(this).parent();
                                            const initial = div.data('siswa')
                                            $(this).remove()
                                            div.html(`<span class="text-lg">${initial}</span>`);
                                            resolve(obj);
                                        })
                                        .on("load", function () {
                                            obj.error = false;

                                            // ==== Resize gambar dengan rasio asli ====
                                            const canvas = document.createElement("canvas");
                                            const ctx = canvas.getContext("2d");

                                            const targetW = 100; // lebar tetap
                                            const ratio = v.naturalHeight / v.naturalWidth;
                                            const targetH = Math.round(targetW * ratio);

                                            canvas.width = targetW;
                                            canvas.height = targetH;

                                            ctx.drawImage(v, 0, 0, targetW, targetH);

                                            // Convert ke PNG
                                            v.src = canvas.toDataURL("image/png");

                                            resolve(obj);
                                        });
                                });
                            };

                            await loaded();
                        });
                    }
                }
            });
        }

        load_log();

        getPosts();


        getToken(function (result) {
            getGlobalToken();
        });


        $('#refresh-token').click(function () {
            getToken(function (result) {
                getGlobalToken();
            });
        });

        setTimeout(function () {
            ajaxGet(base_url + 'dashboard/get_status_siswa', function(error, response) {
                if (error) {
                    console.log('error', error.message);
                } else {
                    createTableFromJSON(response);
                }
            })
        }, 500)

    });

    async function createTableFromJSON(data) {
        const tableContainer = document.getElementById('table-container');
        const allSesi = data.ruangs || [];
        const jsonData = data.jadwals_ujian || [];

        // 1. Validate and handle empty data
        if (!validateData(allSesi, jsonData, tableContainer)) {
            return;
        }

        // 2. Process and group the data
        const groupedSchedules = processAndGroupData(data);

        // 3. Sort the final list for correct rowspans
        groupedSchedules.sort((a, b) => {
            if (a.ruang_sesi.ruang_id !== b.ruang_sesi.ruang_id) return a.ruang_sesi.ruang_id - b.ruang_sesi.ruang_id;
            if (a.ruang_sesi.sesi_id !== b.ruang_sesi.sesi_id) return a.ruang_sesi.sesi_id - b.ruang_sesi.sesi_id;
            return a.jam_ke - b.jam_ke;
        });

        // 4. Calculate rowspans for 'ruang' and 'sesi' columns
        const rowCounts = calculateRowCounts(groupedSchedules, 'ruang_sesi.ruang_id');
        const sesiRowCounts = calculateRowCounts(groupedSchedules, 'ruang_sesi.ruang_id', 'ruang_sesi.sesi_id');

        // 5. Build and render the HTML table
        const tableHtml = buildTable(groupedSchedules, data, rowCounts, sesiRowCounts);
        tableContainer.innerHTML = tableHtml;
    }

    function validateData(allSesi, jsonData, container) {
        if (allSesi.length === 0 || jsonData.length === 0) {
            container.innerHTML = `<table class="w-100 table-bordered"><tr><td class="text-center">Tidak ada jadwal penilaian hari ini</td></tr></table>`;
            return false;
        }
        return true;
    }

    function processAndGroupData(data) {
        const allSesi = data.ruangs || [];
        const jsonData = data.jadwals_ujian || [];
        const grouped = {};

        jsonData.forEach(jadwal => {
            jadwal.bank.bank_kelas = jadwal.bank.bank_kelas.map(String)
            const ruangFiltered = allSesi?.filter(r =>
                r.kelas_id.some(id => jadwal.bank.bank_kelas.includes(id?.toString()))
            );

            ruangFiltered.forEach(ruang => {
                // siswa dalam sesi/ruang ini
                const siswaRuang = data.sesisiswa.filter(s =>
                    s.ruang_id === ruang.ruang_id &&
                    s.sesi_id === ruang.sesi_id &&
                    jadwal.bank.bank_kelas.includes(s.kelas_id) &&
                    !(jadwal?.bank?.soal_agama != '-' && jadwal?.bank?.soal_agama != '0' && jadwal?.bank?.soal_agama != s.siswa.agama)
                );
                const jumlahSiswa = siswaRuang.length;

                let belumLogin = 0, sedangLogin = 0, selesai = 0;
                siswaRuang.forEach(s => {
                    // cari cbtsiswa untuk siswa ini
                    const cbt = data.cbtsiswa.find(c =>
                        c.id_siswa === s.siswa_id &&
                        c.jadwal.id_jadwal === jadwal.id_jadwal
                    );

                    if (!cbt || cbt.mulai === null) {
                        belumLogin++;
                    } else if (cbt.selesai === null) {
                        sedangLogin++;
                    } else {
                        selesai++;
                    }
                });
                const pengawasJadwal = data.pengawas[jadwal.id_jadwal]?.[ruang.ruang_id]?.[ruang.sesi_id] || {};
                const key = `${ruang.ruang_id}-${ruang.sesi_id}-${pengawasJadwal.jam_ke || '1'}`;
                if (!grouped[key]) {
                    grouped[key] = {
                        key: key,
                        ruang_sesi: ruang,
                        jam_ke: pengawasJadwal.jam_ke || '1',
                        jadwal: [],
                        pengawas: [],
                        peserta: 0,
                        blm_login: 0,
                        sdg_login: 0,
                        selesai: 0
                    };
                }
                grouped[key].jadwal.push(jadwal);
                const pengawasList = (pengawasJadwal.id_guru || '').split(',').filter(Boolean);
                //if (!grouped[key].jam_ke.includes(pengawasJadwal.jam_ke)) {
                //    grouped[key].jam_ke.push(pengawasJadwal.jam_ke)
                //}
                for (const string of pengawasList) {
                    if (!grouped[key].pengawas.includes(data.gurus[string] || '')) {
                        grouped[key].pengawas.push(data.gurus[string] || '');
                    }
                }
                grouped[key].peserta += jumlahSiswa;
                grouped[key].blm_login += belumLogin;
                grouped[key].sdg_login += sedangLogin;
                grouped[key].selesai += selesai;
            });
        });

        return Object.values(grouped);
    }

    function calculateRowCounts(items, ...keys) {
        const counts = new Map();
        let prevValues = null;
        let currentCount = 0;

        // Use a deep equality check for dynamic keys
        const getValues = (item) => keys.map(key => {
            return key.split('.').reduce((obj, prop) => obj?.[prop], item);
        });

        [...items, null].forEach(item => {
            const currentValues = item ? getValues(item) : null;

            const isSameGroup = prevValues && currentValues &&
                prevValues.every((val, i) => val === currentValues[i]);

            if (!isSameGroup) {
                if (prevValues !== null) {
                    const key = prevValues.join('-');
                    counts.set(key, currentCount);
                }
                currentCount = 0;
            }

            if (item !== null) {
                currentCount++;
            }
            prevValues = currentValues;
        });

        return counts;
    }

    function buildTable(groupedSchedules, data, rowCounts, sesiRowCounts) {
        const headerHtml = `
        <thead>
            <tr class="bg-light">
                <th class="text-center align-middle" rowspan="2">RUANG</th>
                <th class="text-center align-middle" rowspan="2">SESI</th>
                <th class="text-center align-middle" rowspan="2">JAM KE</th>
                <th class="text-center align-middle" rowspan="2">MAPEL<br>( BANK SOAL )</th>
                <th class="text-center align-middle" rowspan="2">KELAS</th>
                <th class="text-center align-middle" rowspan="2">PENGAWAS</th>
                <th class="text-center align-middle" rowspan="2">JML SISWA</th>
                <th class="text-center align-middle" colspan="3">STATUS SISWA</th>
            </tr>
            <tr class="bg-light">
                <th class="text-center align-middle">BLM<br/>LOGIN</th>
                <th class="text-center align-middle">SDG<br/>LOGIN</th>
                <th class="text-center align-middle">SELESAI</th></tr></thead>
            </tr>
        </thead>`;

        let bodyHtml = '<tbody>';
        const usedRuangIds = new Set();
        const usedSesiKeys = new Set();
        let currentRow = 0;
        let curSesi = 0;
        let bgRow = '';
        let bold = false;

        groupedSchedules.forEach(group => {
            const { ruang_sesi, jam_ke, jadwal, pengawas, peserta, blm_login, sdg_login, selesai } = group;
            let infoMapel = ``;
            for (const jad of jadwal) {
                infoMapel += `${jad.bank.mapel.kode} (<span class="badge badge-light">${jad.bank.bank_kode}</span>)<br/>`;
            }
            const bank_kelas = getUniqueClassNames(ruang_sesi, jadwal).join(', ');
            //const bank_kode = jadwal.map(j => `<span class="badge badge-light">${j.bank.bank_kode}</span>`).join('<br>');
            const idsGuru = jadwal.map(j => j.bank.bank_guru_id).join(',');

            bodyHtml += `<tr>`;
            // Ruang column with rowspan
            const ruangId = ruang_sesi.ruang_id;
            if (!usedRuangIds.has(ruangId)) {
                const rowspanValue = rowCounts.get(String(ruangId)) || 1;
                bodyHtml += `<td rowspan="${rowspanValue}" class="text-center align-middle border-bottom-bold">${ruang_sesi.nama_ruang}</td>`;
                usedRuangIds.add(ruangId);
                bold = true
            } else {
                bold = false
            }

            var genap = curSesi % 2 === 0;
            const bBold = bold ? 'border-top-bold' : '';
            // Sesi column with rowspan
            const sesiKey = `${ruang_sesi.ruang_id}-${ruang_sesi.sesi_id}`;
            if (!usedSesiKeys.has(sesiKey)) {
                bgRow = genap ? 'bg-gray-light' : '';
                const rowspanValue = sesiRowCounts.get(sesiKey) || 1;
                bodyHtml += `<td rowspan="${rowspanValue}" class="text-center align-middle td-sesi ${bgRow} ${bBold}">${ruang_sesi.nama_sesi}</td>`;
                usedSesiKeys.add(sesiKey);
                curSesi++;
            }

            bodyHtml += `
            <td class="text-center align-middle td-jam ${bgRow} ${bBold}">${jam_ke}</td>
            <td class="align-middle td-mapel jadwal ${bgRow} ${bBold}">${infoMapel}</td>
            <td class="text-center align-middle ${bgRow} ${bBold}">${bank_kelas}</td>
            <td class="text-center align-middle td-pengawas ${bgRow} ${bBold}" data-guru="${idsGuru}">${pengawas.join('<br>')}</td>
            <td class="text-center align-middle text-bold ${bgRow} ${bBold}">${peserta}</td>
            <td class="text-center align-middle ${bBold} ${bgRow}"><span class="text-bold text-danger">${blm_login}</span></td>
            <td class="text-center align-middle ${bBold} ${bgRow}"><span class="text-bold text-info">${sdg_login}</span></td>
            <td class="text-center align-middle ${bBold} ${bgRow}"><span class="text-bold text-success">${selesai}</span></td>
        </tr>`;

            currentRow++;
        });

        bodyHtml += '</tbody>';
        return `<table class="table table-bordered table-sm w-100">${headerHtml}${bodyHtml}</table>`;
    }

    function getUniqueClassNames(ruang_sesi, jadwal) {
        const banks_kelas = [];
        const classIds = ruang_sesi.kelas_id;

        for (const j of jadwal) {
            for (const klsId of classIds) {
                if (j.bank?.bank_kelas?.includes(klsId)) {
                    banks_kelas.push(ruang_sesi.nama_kelas[klsId] || '');
                }
            }
        }

        return [...new Set(banks_kelas)];
    }

    function formatTanggal(dateString) {
        const date = new Date(dateString);
        const options = { weekday: 'short', day: 'numeric', month: 'short', year: 'numeric' };
        return date.toLocaleDateString('id-ID', options);
    }

</script>
