<?php session_start(); include 'db_conn.php'; ?>
<!DOCTYPE html>
<html>
    <head>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta charset="UTF-8">
        <title>OggleCalendar</title>
        <link rel="stylesheet" href="assets/style.css" type="text/css" />
        <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet" />
        <script
            src="assets/jquery-3.2.1.min.js"
            crossorigin="anonymous">
        </script>
        <script>
            var allday_fix_ival = false;
            var displayed_week_start;
            var displayed_day_start;
            var black_color = "#272727";
            var blue_color = "#1976d2";
            var events = [];
            var selected_labels = [];
            var view = "week";
            var sidebar = 1;
            var ivals = [];
            var event_event_listener = false;
        </script>
        <script src='https://www.google.com/recaptcha/api.js'></script>
        <script src="assets/event_create.js"></script>
        <script src="assets/event_display.js"></script>
        <script src="assets/sidebar.js"></script>
        <script src="assets/uidatetime.js"></script>
        <script src="assets/util.js"></script>
        <script src="assets/view.js"></script>
        <script src="assets/login.js"></script>
        <script src="assets/settings.js"></script>
        <script>
            function showSet()
            {
                var popup = document.createElement('div');
                popup.className = "register-popup";
                popup.innerHTML = "<div id='overlay'></div><div id='register-content'>Set!</div>";
                document.body.appendChild(popup);
                overlay = document.getElementById("overlay");
                window.getComputedStyle(popup).opacity;

                popup.style.opacity = 1;

                setTimeout(function() { closeOpacityBox('.register-popup'); }, 1000);
            }

            function setMyLabels()
            {
                $.post('/setLabels.php', {labels: selected_labels},
                function(data) { console.log(data); });
            }
            function setLabel(label)
            {
                if (document.getElementById("labelId-" + label).checked) {
                    selected_labels.push(label);
                }
                else {
                    for (var i = 0; i < selected_labels.length; i++) {
                        if (label == selected_labels[i]) {
                            selected_labels.splice(i, 1);
                        }
                    }
                }
            }

            /* Zet de knop die de form van de redactie en admin page gesubmit
             * naar clicked. */
            function formSubmit(clicked) {
                $(clicked).attr("clicked", "true");
            }

            /* Zet de knop die de form van de redactie en admin page gesubmit
             * naar clicked. Is een van de table heads. */
            function formSort(clicked) {
                $(clicked).attr("clicked", "true");
            }

            /* Laad de tabel aarin je evenementen kan screenen. */
            function loadScreenTable(after = function(){})
            {
               $.get("redactie/screen_evenementen/screenen.php", function(data)
               {
                   $("#main-content")[0].innerHTML = "";
                   $("#main-content").append(data);


                   // $('#register').on('click', function() {
                   //     if ($('.dropdown-login').hasClass('show'))
                   // }

                   after();
               });
               $(window).resize(contentResize);
            }

            function loadGenInvite()
            {
                $.get("/generate_invite.php", function(data)
                {
                    $("#main-content")[0].innerHTML = "";
                    $("#main-content").append(data);
                });
            }

            function loadLabelManager(after = function(){})
            {
                $.get("redactie/label_management/label_manager.php", function(data)
                {
                    $("#main-content")[0].innerHTML = "";
                    $("#main-content").append(data);

                    after();
                });
                $(window).resize(contentResize);
            }

            function loadAccountSettings(after = function(){})
            {
                $.get("accountPanelSettings.php", function(data)
                {
                    $("#main-content")[0].innerHTML = "";
                    $("#main-content").append(data);

                    after();
                });
                $(window).resize(contentResize);
            }

            /* Maakt een ajax call als er in de screenen page op een submit knop
             * is geklikt en update dan de informatie van de page.
             */
            function submitScreenTable()
            {
                var formData = $(".screenen_form").serialize();

                if($("button[clicked='true'][onclick='formSort(this)']").length > 0){
                    var buttonClicked = $("button[clicked='true'][onclick='formSort(this)']").val();
                    var submitKnop = "&column_name=" + buttonClicked;
                    formData = formData + submitKnop;
                } else if($("input[clicked='true']").length > 0){
                    var buttonClicked = ($("input[clicked='true']").val());
                    var submitKnop = "&submit=" + buttonClicked;
                    formData = formData + submitKnop;
                } else if($("button[clicked='true']").length > 0){
                    var buttonClicked = ($("button[clicked='true']").val());
                    var submitKnop = "&submit=" + buttonClicked;
                    formData = formData + submitKnop;
                }

                $.ajax({
                        type : 'POST',
                        url  : 'redactie/screen_evenementen/screenen.php',
                        cache : false,
                        data : formData,
                        success: function(new_data) {

                        },
                        error : function(xhr, ajaxOptions, thrownError) {
                            alert(thrownError);
                            var json = xhr.responseJSON;
                            console.log(json);
                        }
                }).done(function(data) {
                    $("#main-content")[0].innerHTML = "";
                    $("#main-content").append(data);
                });

                $(window).resize(contentResize);

                return false;
            }

            /* Laad de tabel aarin je evenementen kan bekijken en verwijderen.. */
            function loadOverzichtEvenementen(after = function(){})
            {

               $.get("redactie/evenementen_overzicht/evenementen_overzicht.php", function(data)
               {
                   $("#main-content")[0].innerHTML = "";
                   $("#main-content").append(data);


                   // $('#register').on('click', function() {
                   //     if ($('.dropdown-login').hasClass('show'))
                   // }

                   after();
               });
               $(window).resize(contentResize);
            }

            /* Maakt een ajax call als er in de evenementen page op een submit knop
             * is geklikt en update dan de informatie van de page.
             */
            function submitOverzichtEvenementen()
            {
                var formData = $(".evenementen_overzicht_form").serialize();

                if($("button[clicked='true'][onclick='formSort(this)']").length > 0){
                    var buttonClicked = $("button[clicked='true'][onclick='formSort(this)']").val();
                    var submitKnop = "&column_name=" + buttonClicked;
                    formData = formData + submitKnop;
                } else if($("input[clicked='true']").length > 0){
                    var buttonClicked = ($("input[clicked='true']").val());
                    var submitKnop = "&submit=" + buttonClicked;
                    formData = formData + submitKnop;
                } else if($("button[clicked='true']").length > 0){
                    var buttonClicked = ($("button[clicked='true']").val());
                    var submitKnop = "&submit=" + buttonClicked;
                    formData = formData + submitKnop;
                }

                $.ajax({
                        type : 'POST',
                        url  : 'redactie/evenementen_overzicht/evenementen_overzicht.php',
                        cache : false,
                        data : formData,
                        success: function(new_data) {

                        },
                        error : function(xhr, ajaxOptions, thrownError) {
                            alert(thrownError);
                            var json = xhr.responseJSON;
                            console.log(json);
                        }
                }).done(function(data) {
                    $("#main-content")[0].innerHTML = "";
                    $("#main-content").append(data);
                });

                $(window).resize(contentResize);

                return false;
            }


            /* Laad de tabel aarin je evenementen kan bekijken en verwijderen.. */
            function loadUserScreenTable(after = function(){})
            {

               $.get("redactie/screen_gebruikers/screenen_users.php", function(data)
               {
                   $("#main-content")[0].innerHTML = "";
                   $("#main-content").append(data);


                   // $('#register').on('click', function() {
                   //     if ($('.dropdown-login').hasClass('show'))
                   // }

                   after();
               });
               $(window).resize(contentResize);
            }

            /* Maakt een ajax call als er in de evenementen page op een submit knop
             * is geklikt en update dan de informatie van de page.
             */
            function submitScreenUserTable()
            {
                var formData = $(".screen_gebruikers_form").serialize();

                if($("button[clicked='true'][onclick='formSort(this)']").length > 0){
                    var buttonClicked = $("button[clicked='true'][onclick='formSort(this)']").val();
                    var submitKnop = "&column_name=" + buttonClicked;
                    formData = formData + submitKnop;
                } else if($("input[clicked='true']").length > 0){
                    var buttonClicked = ($("input[clicked='true']").val());
                    var submitKnop = "&submit=" + buttonClicked;
                    formData = formData + submitKnop;
                } else if($("button[clicked='true']").length > 0){
                    var buttonClicked = ($("button[clicked='true']").val());
                    var submitKnop = "&submit=" + buttonClicked;
                    formData = formData + submitKnop;
                }

                $.ajax({
                        type : 'POST',
                        url  : 'redactie/screen_gebruikers/screenen_users.php',
                        cache : false,
                        data : formData,
                        success: function(new_data) {

                        },
                        error : function(xhr, ajaxOptions, thrownError) {
                            alert(thrownError);
                            var json = xhr.responseJSON;
                            console.log(json);
                        }
                }).done(function(data) {
                    $("#main-content")[0].innerHTML = "";
                    $("#main-content").append(data);
                });

                $(window).resize(contentResize);

                return false;
            }




            function getUserID()
            {
            <?php
                if (isset($_SESSION['user_id']))
                {
                    echo "return {$_SESSION['user_id']};";
                } else {
                    echo "return -1;";
                }
            ?>
            }


            /* Laad de tabel aarin je users kan aanpassen.. */
            function loadUserTable(after = function(){})
            {
               $.get("redactie/gebruikers/gebruikers.php", function(data)
               {
                   $("#main-content")[0].innerHTML = "";
                   $("#main-content").append(data);

                   after();
               });
               $(window).resize(contentResize);
            }

            /* Maakt een ajax call als er in de user page op een submit knop
             * is geklikt en update dan de informatie van de page.
             */
            function submitUserTable()
            {
                var formData = $(".gebruikers_form").serialize();

                if($("button[clicked='true'][onclick='formSort(this)']").length > 0){
                    var buttonClicked = $("button[clicked='true'][onclick='formSort(this)']").val();
                    var submitKnop = "&column_name=" + buttonClicked;
                    formData = formData + submitKnop;
                } else if($("input[clicked='true']").length > 0){
                    var buttonClicked = ($("input[clicked='true']").val());
                    var submitKnop = "&submit=" + buttonClicked;
                    formData = formData + submitKnop;
                } else if($("button[clicked='true']").length > 0){
                    var buttonClicked = ($("button[clicked='true']").val());
                    var submitKnop = "&submit=" + buttonClicked;
                    formData = formData + submitKnop;
                }

                $.ajax({
                        type : 'POST',
                        url  : 'redactie/gebruikers/gebruikers.php',
                        cache : false,
                        data : formData,
                        success: function(new_data) {

                        },
                        error : function(xhr, ajaxOptions, thrownError) {
                            alert(thrownError);
                            var json = xhr.responseJSON;
                            console.log(json);
                        }
                }).done(function(data) {
                    $("#main-content")[0].innerHTML = "";
                    $("#main-content").append(data);
                });

                $(window).resize(contentResize);

                return false;
            }


            function loadAgenda(pre = function(){}, after = function(){})
            {
                $.get("/agenda.php", function(data)
                {
                    view = "week";
                    $("#content")[0].innerHTML = "";
                    $("#content").append(data);

                    g = $("#grid");
                    diff = g.prop('scrollHeight') - g.height();
                    g.scrollTop(diff / 2);

                    if (window.innerWidth >= 980)
                    {
                        $("#sidebar").css('width', 225);
                    }
                    pre();

                    updateTime();
                    updateEvents();
                    fixDates();
                    contentResize();
                    showCurrentDay()
                    ivals.push(setInterval(updateEvents, 5000));
                    ivals.push(setInterval(updateTime, 60000));

                    // $('#register').on('click', function() {
                    //     if ($('.dropdown-login').hasClass('show'))
                    // }
                    <?php
                    if (isset($_SESSION['logged_in']))
                    {
                        $stmt = $db->prepare("SELECT label_id FROM User_labels WHERE user_id=:uid");
                        $stmt->execute(array("uid" => $_SESSION['user_id']));
                        $results = $stmt->fetchAll();

                        foreach($results as $result)
                        {
                            echo "$('#labelId-{$result["label_id"]}')[0].checked = true; setLabel('{$result["label_id"]}');";
                        }
                    ?>
                    $('.hour-row').unbind('click');
                    $('.hour-row').on('click', function(e) {
                        if (e.target.className == 'hour-row' ||
                        (typeof e.target.id === "string" &&
                        e.target.id.match("day-\\d*-hour-\\d*")))
                        {
                            var divID = e.target.id;
                            clearStoredTimeVal();
                            createEventBox(divID);
                        }
                        $(this).on('change', 'input.allDayCheckbox', function () {

                            var startTimeVal    = $('#start-time').val(),
                                endTimeVal      = $('#end-time').val();



                            if (localStorage.getItem("startTimeVal") === null) {

                                localStorage.setItem("startTimeVal", startTimeVal);
                                localStorage.setItem("endTimeVal", endTimeVal);
                            }

                            if ($(this).is(':checked')) {
                                $('#start-time').val('00:00');
                                $('#end-time').val('00:00');
                            } else {
                                $('#start-time').val(localStorage.getItem("startTimeVal"));
                                $('#end-time').val(localStorage.getItem("endTimeVal"));
                                clearStoredTimeVal();
                            }
                        });
                    });
<?php } ?>

                    after();
                    setTimeout(redisplayEvents, 1000);
                });
                $(window).resize(contentResize);
            }

            function alldayfix()
            {
                redisplayEvents();
            }

            var adf = [];

            $(window).ready(function() {
                displayed_week_start = getCurrentWeek();
                loadAgenda(function() {
                    $("#sidebar").on('transitionstart', function()
                    {
                        console.log('transition start');
                        adf.push(setInterval(alldayfix, 100));
                        console.log(adf);
                        setTimeout(function () {$("#sidebar").trigger('transitionend');}, 1000);
                    });
                    $("#sidebar").on('transitionend', function() {
                        console.log('transition end');
                        for (let interval of adf)
                        {
                            clearInterval(interval);
                        }
                        adf.length = 0;
                        redisplayEvents();
                    });
                }, function() {
<?php
if (isset($_REQUEST['invite_token'])) {
?>
                    registerPopup("<?php echo $_REQUEST['invite_token']; ?>");
<?php
}
?>
                    $(document).on('click', function(e) {
                        if ($(this).parents('.eventCreate').length < 0) {
                            clearStoredTimeVal();
                        }
                    });

                    $(document).on('click', '.event', function(e) {
                        if (e.target.closest(".eventBox"))
                        {
                            return;
                        }

                        var ev_data = findEventData(e.target.closest(".event").id);
                        if (ev_data !== null)
                        {
                            createEventInfo(ev_data);
                        }
                    });

                    $("#days").click(function(e) {
                        var evBox = $('.eventBox');
                        if (evBox.length === 0)
                        {
                            return;
                        }
                        closeOpacityBox('.eventBox');
                    });
                });

                // Need to use mouseup() here because otherwise the 'click' is already on the eventBox (so it shouldn't remove() it).
                $("#header,#sidebar").on('mouseup', function(e) {

                    var $eventBox = $('.eventBox');
                    if ($eventBox.length === 0)
                    {
                        return;
                    }
                    // if the target of the click isn't the $eventBox nor a descendant of the $eventBox
                    if (!$eventBox.is(e.target) && $eventBox.has(e.target).length === 0)
                    {
                        closeOpacityBox(".eventBox");
                    }
                });
            });

            function createEventInfo(eventData) {
                if ($(".eventInfo,.eventCreate").length)
                {
                    closeOpacityBox(".eventInfo,.eventCreate");
                    return;
                }

                var clickedEvent = document.getElementById(eventData.event_id);
                var eventDiv = document.createElement('div');

                var is_all_day_event = $(clickedEvent).parents().index($(".all-day")) == 1;
                var display_box_left = $("#week .day-column").index(clickedEvent.parentElement) <= 4
                                    && (!is_all_day_event || (parseInt(clickedEvent.style.left) / $("#week .day-column").width() <= 4));


                eventData.start_date_disp = new Date(eventData.start_date).format('F jS, h:i');
                eventData.end_date_disp = new Date(eventData.end_date).format('F jS, h:i');

                eventDiv.setAttribute('class', 'eventBox z-depth-4 eventInfo');

                eventDiv.style.opacity = 0;
                eventDiv.style.color = black_color;

                if (display_box_left)
                {
                    eventDiv.style.left = clickedEvent.offsetWidth * 0.9 + "px";
                } else {
                    eventDiv.style.right = clickedEvent.offsetWidth * 0.9 + "px";
                }


                if (view == 'day' || is_all_day_event)
                {
                    eventDiv.style.right = eventDiv.style.left = 0;
                    eventDiv.style.top = 0;
                }

                $.post('event_info.php', eventData, function(data)
                {
                    eventDiv.innerHTML = data;

                    /* need to append it somewhere, because otherwise it has
                     * no height. */
                    document.body.appendChild(eventDiv);
                    if (view == 'day' || is_all_day_event)
                    {
                        eventDiv.style.top = 1 + clickedEvent.offsetHeight + "px";
                    }

                    if (parseInt(clickedEvent.style.top) + $(clickedEvent).height() + $(eventDiv).height() > $("#grid")[0].scrollHeight)
                    {
                        eventDiv.style.bottom = 0;
                        eventDiv.style.top = "initial";
                    }
                    clickedEvent.appendChild(eventDiv);
                    $(".eventbox-top").css("background-color", '#' + eventData.clr.split(',')[0]);
                    eventDiv.style.transition = "opacity 0.2s ease-in-out, top 0.2s ease-in-out,"
                                              + "right 0.2s ease-in-out, left 0.2s ease-in-out";
                    eventDiv.style.width = $("#week .day-column").width() * 2 - 3 + "px";
                    eventDiv.style.opacity = 1;

                    /* No idea why, but it differs per browser. */
                    var addOne = (/Chrome/.test(navigator.userAgent)) ? 0 : 1;
                    if (display_box_left)
                    {
                        eventDiv.style.left = clickedEvent.offsetWidth + 11 + addOne + "px";
                    } else {
                        eventDiv.style.right = clickedEvent.offsetWidth + 11 + addOne + "px";
                    }

                    if (view == 'day' || is_all_day_event)
                        eventDiv.style.right = eventDiv.style.left = 0;

                    if (view == 'week' && is_all_day_event && !display_box_left)
                    {
                        eventDiv.style.right = 0;
                        eventDiv.style.left = "initial";
                    }
                });
            }

            function clearStoredTimeVal () {
                window.localStorage.removeItem("startTimeVal");
                window.localStorage.removeItem("endTimeVal");
            }

            function deleteEvent(eventID) {
                $.ajax({
                    url: 'db_requests/deleteEvent.php',
                    type: 'POST',
                    data: {
                        id: eventID
                    },
                    success: function(data) {
                        console.log('deleteEventData:' + data);
                        updateEvents();
                    }
                });
            }

            function closeLoginBox() {
                $(".dropdown-login").remove();

                updateEvents();
            }

            function createLoginDropdown() {
                var loginButton = document.getElementById('login');
                var loginDiv = document.createElement('div');
                loginDiv.setAttribute('class', 'dropdown-login');

                loginDiv.innerHTML =
                    '<form action="javascript:;" method="post" onsubmit="verifyLogin(this)">' +
                    '    <label>Username :  </label><input type="text" name="username" class="loginInput" /><br><br>' +
                    '    <label>Password :  </label><input type="password" name="password" class="loginInput" /><br><br>' +
                    '    <input type="submit" name="submit" value=" Submit "/><br />' +
                    '</form>';

                loginButton.appendChild(loginDiv);
            }

            function verifyLogin(e)
            {
            //     var formInputs = ;
            //     $.ajax({
            //        url: "login.php",
            //        data: formInputs,
            //        succes: function() {
            //            alert('Succesfully logged in!');
            //        }
            //    });

                console.log('got here at least');
                $.post('login.php', $(e).serialize(), function(e)
                {
                    closeLoginBox();
                });

                var seshId =
                '<?php
                    if (isset($_SESSION['user_id'])) {
                        echo $_SESSION['user_id'];
                    } else {
                        echo "no session ID";
                    };
                ?>';

                console.log('logged in with ID: ' + seshId);
            }

            function getSessionID() {
                <?php $session_id = (isset($_SESSION['user_id'])) ? $_SESSION['user_id'] : '"not set"'; ?>

                return <?php echo $session_id; ?>;
            }

            var width = 0;
        </script>
    </head>
    <body>
        <?php
            if (!empty($_POST["newLabelName"]))
            {
                $labelName = strip_tags ($_POST["newLabelName"]);
                $labelColor = strip_tags ($_POST["labelColor"]);
                include 'db_conn.php';
                try {
                    $stmt = $db->prepare("INSERT INTO `Labels` (label, color_id) VALUES (:label, :color)");
                    $stmt->bindParam(':label', $labelName, PDO::PARAM_STR);
                    $stmt->bindParam(':color', $labelColor, PDO::PARAM_INT);
                    $stmt->execute();
                    echo "<script>alert('Label succesfully added')</script>";
                } catch (Exception $e) {
                    $err = $stmt->errorInfo();
                    if (isset($err[1]))
                    {
                        if ($err[1] != 1062)
                        {
                            die('database error');
                        }
                    }
                }
            }
            if (!empty($_POST["removedLabel"]))
            {
                $labelID = $_POST["removedLabel"];
                include 'db_conn.php';
                try {
                    $stmt = $db->prepare("DELETE FROM `Labels` WHERE label_id='$labelID'");
                    $stmt->execute();
                    echo "<script>alert('Label succesfully removed')</script>";
                } catch (Exception $e) {
                    $err = $stmt->errorInfo();
                    if (isset($err[1]))
                    {
                        if ($err[1] != 1062)
                        {
                            die('database error');
                        }
                    }
                }
            }
        ?>
        <div id="header" class="z-depth-1">
            <div id="minButton" class='icon' data-icon="menu" onclick='sidebarToggle();'></div>
            <div id="logo-wrapper" onclick="location='/'"><div id="logo" class="bold"><span class='np blue'>Oggle</span></div>Calendar</div>
            <div class="weekNumber mobile-invisible">Week: <?php echo ltrim(date('W'), '0'); ?></div>
            <div class='prevWeekButton icon morepad' data-icon="navigate_before" onclick="showPrev()"></div>
            <div class='nextWeekButton icon nopad' data-icon="navigate_next" onclick="showNext()"></div>
            <div class="date mobile-invisible"><?php echo date('F Y'); ?></div>
            <span class="right-divide"></span>

<?php
            if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true)
            {
?>
            <div id="login" class="mobile-invisible" onclick="loginPopup();">Login</div>
            <div id="register" class="mobile-invisible" onclick="registerPopup();">Register</div>
<?php
            } else {
?>
            <div id="logout" class="mobile-invisible" onclick="logout();">Logout</div>
            <span id="settings" class='icon' data-icon='settings' onclick='settingsToggle()'></span>
<?php
            }
?>
        </div>
        <div id="content">
        </div>
    </body>
</html>
