<?php
include "pin/header.php";
include "pin/sidenav.php";

$user_name = $_SESSION['user_name'];
$emp_id = $_SESSION['emp_id'];
$user_role = $_SESSION['user_role'];


$month = isset($_GET['month']) ? $_GET['month'] : date("Y-m", strtotime("last month"));
// $eid = isset($_GET['emp_id']) ? $_GET['emp_id'] : $emp_id;

// if ($user_role != 0) {
//     if (isset($_GET['emp_id'])) {
//         $ex = mysqli_num_rows(mysqli_query($db, "select * from users where employee_id='$_GET[emp_id]' and leader='$emp_id'"));
//         if ($ex == 0 && $_GET['emp_id'] != $emp_id) {
//             echo "<script>location.href='404'</script>";
//         }
//     }
// }


?>

<!-- Plugin css -->
<link href="assets/libs/fullcalendar-core/main.min.css" rel="stylesheet" type="text/css" />
<link href="assets/libs/fullcalendar-daygrid/main.min.css" rel="stylesheet" type="text/css" />
<link href="assets/libs/fullcalendar-bootstrap/main.min.css" rel="stylesheet" type="text/css" />
<link href="assets/libs/fullcalendar-timegrid/main.min.css" rel="stylesheet" type="text/css" />
<link href="assets/libs/fullcalendar-list/main.min.css" rel="stylesheet" type="text/css" />

<!-- ============================================================== -->
<!-- Start Page Content here -->
<!-- ============================================================== -->


<style>
    .fc-toolbar {
        flex-wrap: wrap;
    }

    .fc-highlight {
        background: #bce8f1 !important;
        opacity: 1 !important;
    }

    .alert-info {
        color: #000 !important;
        background-color: #7cefd273 !important;
        border-color: #7cefd273 !important;
    }

    .fc-event,
    td {
        cursor: pointer;
    }

    .attendance-wrapper {
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 1rem;
        flex-wrap: wrap;
    }

    .attendance-status {
        width: 160px;
        height: 120px;
        background: #fff;
        padding: 1rem;
    }

    .attendance-status h6::before {
        content: '';
        width: 10px;
        height: 10px;
        background: #fff;
        display: inline-block;
        border-radius: 50%;
        position: relative;
        top: 50%;
        left: -5px;
    }

    .attendance-status:nth-of-type(1) h6::before {
        background: #198754;
    }

    .attendance-status:nth-of-type(2) h6::before {
        background: #ffc107;
    }

    .attendance-status:nth-of-type(3) h6::before {
        background: #0d6efd;
    }

    .attendance-status:nth-of-type(4) h6::before {
        background: #dc3545;
    }

    .attendance-status:nth-of-type(5) h6::before {
        background: #212529;
    }

    .attendance-status:nth-of-type(6) h6::before {
        background: #212529;
    }

    .attendance-change-bg {
        background-color: #285430;
    }
</style>


<div class="content-page" style="position:relative;">
    <style>
        #loader-wrapper {

            width: 100%;
            height: 100vh;
            background: #fff;
            position: absolute;
            top: 0;
            z-index: 99;
            display: none;
        }

        .loader {
            /* border: 1px solid white; */
            width: 100%;
            height: 100%;
            display: flex;
            justify-content: center;
            align-items: center;
            flex-direction: column;
        }

        .loading-container {
            display: flex;
            justify-content: center;
            align-items: center;
            position: relative;
        }

        .spinner {
            height: 8rem;
            width: 8rem;
            border-width: 5px;
            border-style: solid;
            /* border-color: #c5c5c5; */
            border-color: #000;
            /* border-left-color: #00000070; */
            border-left-color: #fff;
            border-radius: 50%;
            display: flex;
            justify-content: center;
            align-items: center;
            animation: spin infinite 1.5s linear;
        }

        .spinner-text {
            position: absolute;
            font-size: 14px;
            color: #000;
            top: 50%;
            transform: translateY(-50%);
            font-weight: 600;
            letter-spacing: 1.5px;
            text-transform: uppercase;
        }

        .load-text {
            color: #000;
            font-size: 14pt;
            margin-top: 1rem;
        }

        .no-scroll {
            overflow: hidden;
        }

        @keyframes spin {
            to {
                transform: rotate(360deg);
            }
        }
    </style>
    <div id="loader-wrapper">
        <div class="loader">
            <div class="loading-container">
                <p class="spinner-text">
                    loading...
                </p>
                <div class="spinner"></div>
            </div>
            <p class="load-text">Please wait ...</p>
        </div>
    </div>

    <div class="content">
        <div class="container-fluid">
            <div class="mt-5"></div>

            <div class="row align-items-start">
                <div class="col-md-9 mb-3">
                    <h4>Punctual Employees of <span class="text-primary">`<?php echo date("F", strtotime($month)); ?>`</span></h4>
                </div>
                <div class="col-md-3 mb-3">
                    <div class="form-group mb-sm-0">
                        <input type="month" class="form-control" id="attendanceMonth" value="<?php echo $month; ?>">
                    </div>
                </div>
            </div>

            <div class="row mt-4" id="top_five">

            </div>



        </div>
    </div> <!-- content -->
</div>


<?php
include "pin/footer.php";
?>
<!-- plugin js -->
<script src="assets/libs/fullcalendar-core/main.min.js"></script>
<script src="assets/libs/fullcalendar-bootstrap/main.min.js"></script>
<script src="assets/libs/fullcalendar-daygrid/main.min.js"></script>
<script src="assets/libs/fullcalendar-timegrid/main.min.js"></script>
<script src="assets/libs/fullcalendar-list/main.min.js"></script>
<script src="assets/libs/fullcalendar-interaction/main.min.js"></script>

<!-- Calendar init -->
<!-- <script src="assets/js/pages/calendar.init.js"></script> -->

<script>
    function loadCalender(index, obj) {
        let name = obj.name;
        let total_hours = obj.total_hours;
        let events = obj.events;
        let calendar = $(`#calendar${index}`)[0];
        // console.log(calendar)
        let calendarObj = {};

        calendarObj[`calendar${index}`] = new FullCalendar.Calendar(calendar, {
            plugins: ["bootstrap", "interaction", "dayGrid", "timeGrid", "list"],
            themeSystem: "bootstrap",
            bootstrapFontAwesome: false,
            defaultView: "dayGridMonth",
            defaultDate: '<?php echo date("Y-m-01", strtotime($month)); ?>',
            header: {
                left: "",
                center: "",
                right: "title",
            },
            handleWindowResize: true,
            height: $(window).height() - 200,
            eventLimit: false,
            droppable: false,
            selectable: false,
            selectHelper: false,
            editable: false,
            events: events,
        });
        calendarObj[`calendar${index}`].render()
        $(`#calendar${index} .fc-header-toolbar .fc-left`).html(`<h2>${name}</h2>`);
        $(`#calendar${index} .fc-header-toolbar .fc-center`).html(`<h2><span class="text-primary">${total_hours}</span> Hours</h2>`);
        // $(".fc-header-toolbar .fc-right").html('<div class="form-group mb-sm-0"><input type="month" class="form-control" id="attendanceMonth" value="<?php echo $month; ?>" style="width:15rem;"></div>');
        // Destroy old calendar object
    }

    async function getData(month) {
        $(window).scrollTop(0);
        $("#loader-wrapper").show();
        $('body').addClass('no-scroll');

        await fetch('fun/getPunctualityResult.php', {
            method: "POST",
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                selectedMonth: month
            })
        }).then((response) => {
            if (!response.ok) {
                const message = `An error has occurred: ${response.status}`;
                throw new Error(message);
            }
            return response.json();
        }).then((data) => {
            // console.log(data)
            for (const index in data) {

                $("#top_five").append(`<div class="col-12">
                        <div class="card">
                            <div class="card-body">
                                <div id="calendar${index}"></div>
                            </div>
                        </div>
                    </div>`);
                console.log(data[index]);
                loadCalender(index, data[index]);
            }
            // setTimeout(() => {
            // }, 1500);
        }).catch((error) => {
            console.log(error.message);
        })

        $("#loader-wrapper").fadeOut();
        $('body').removeClass('no-scroll');
    }
    getData('<?php echo $month; ?>');

    // ######################################################
    $(document).on("change", "#attendanceMonth", function() {
        let month = $(this).val();
        location.href = `?month=${month}`;

    });
    // ######################################################
</script>