<?php
    include "db.php";
?>


<!DOCTYPE html>
<html lang="et">

<head>
    <?php include ('head.html'); ?>
</head>

<body>

    <header>
        <?php include('header.php'); ?>
    </header>

    <main>
        <div class="card-block container">
            <form method="post" action="" enctype="multipart/form-data">
                <?php
                $index = mysqli_escape_string($mysqli, $_GET['id']);
                $sql = "SELECT * FROM document WHERE id='$index'";
                $insert = $mysqli->query($sql);

                while ($row = mysqli_fetch_array($insert)){

                    $edited = $row['edited'];
                    $authorId = $row['authorId'];
                    $checked = $row['state'];

                    ?>

                    <div>
                        <div style="display: inline-block">
                            <?php
                            if ($checked == 2){
                                ?>
                                <a href="index.php">Juhendid</a> <i class="fa fa-arrow-right"></i> <a href=files.php?check=new>Uued</a> <i class="fa fa-arrow-right"></i> <?= $row['title']; ?>
                                <?php
                            } else if ($checked == 3){
                                ?>
                                <a href="index.php">Juhendid</a> <i class="fa fa-arrow-right"></i> <a href=files.php?check=old>Arhiiv</a> <i class="fa fa-arrow-right"></i> <?= $row['title']; ?>
                                <?php
                            }else{
                                $department = $row['department'];
                                ?>
                                <a href="index.php">Juhendid</a> <i class="fa fa-arrow-right"></i> <a href=files.php?department=<?= str_replace(" ", "%20", $department); ?>><?= $department; ?></a> <i class="fa fa-arrow-right"></i> <?= $row['title']; ?>
                                <?php
                                $id = $row['id'];
                                $sql = "SELECT * FROM favourite WHERE userId = $authorId AND documentId = '$id'";
                                $action = $mysqli->query($sql);
                                if (($action->num_rows) > 0) {
                                    ?>
                                    <i class="fa fa-heart favourite heartBox" title="Ei meeldi" id="<?= $row['id']; ?>" style="cursor: pointer"></i>
                                    <?php
                                } else {
                                    ?>
                                    <i class="fa fa-heart-o favourite heartBox" title="Meeldib" id="<?= $row['id']; ?>" style="cursor: pointer"></i>
                                    <?php
                                }
                            }
                            ?>
                        </div>


                        <?php
                        if ($right == 2){
                            $sql = "SELECT * FROM history WHERE documentId='$index' ORDER BY editDate";
                            $insert2 = $mysqli->query($sql);
                            $count = 1;
                            ?>

                            <div class="btn-group" style="position: absolute; right: 200px">
                                <button class="btn btn-info dropdown-toggle" id="historyButton" type="button" data-toggle="dropdown" aria-haspopup="true" style="height: 20px; box-sizing: border-box; line-height: 2px; font-size: 11px">AJALUGU</button>

                                <div class="dropdown-menu">
                                    <?php
                                    if (($insert2->num_rows) > 0){
                                        while ($row2 = mysqli_fetch_array($insert2)){?>
                                            <a class="dropdown-item classCount" data-toggle="modal" data-target="#historyModal">Ver. <?=$count;?> - <?=date('d.m.Y', strtotime($row2['editDate']));?></a><div style="display: none"><?= $row2['content'];?></div>
                                            <?php
                                            $count = $count + 1;
                                        }
                                    }
                                    ?>
                                </div>
                            </div>

                            <?php
                        }
                        ?>

                        <div style="display: inline-block; right: 20px; position: absolute">
                            <?= "<strong>" . 'Uuendatud: ' . "</strong>"  . date('d.m.Y', strtotime($edited));?>
                        </div>
                    </div>

                    <div style="height: 20px"></div>

                    <div class="box">

                        <div class="text-center" style="width: 900px; padding-bottom: 20px; margin: 0 auto; font-size: 35px">
                            <?= $row['title']; ?>
                        </div>

                        <div id="oldContent" style="display: none">
                            <?= $row['content']; ?>
                        </div>

                        <div id="newContent" style="padding-bottom: 50px; width: 900px; margin: 0 auto; word-wrap: break-word">
                            <?= $row['content']; ?>
                        </div>
                    </div>
                <?php
                    $ifEdit = $row['ifEdit'];
                    break;
                }
                ?>

                <div class="text-center" id="salvesta" style="padding-bottom: 70px">
                    
                    <?php 
                    
                    if ($right == 1){?>
                        <button class="btn btn-primary fa fa-download" id="download" onclick="buttonClicked(this)" type="button"> Lae alla</button>
                        <button class="btn btn-primary fa fa-hand-paper-o" data-toggle="modal" data-target="#myModal" type="button"> Teavita veast</button>
                        <?php
                    }
                    else{?>
                        <button class="btn btn-primary fa fa-download" id="download" onclick="buttonClicked(this)" type="button"> Lae alla</button>
                        <?php
                        if ($checked == 2){?>
                            <button class="btn btn-success fa fa-check" id="confirm" onclick="buttonClicked(this)" type="button"> Kinnita</button>
                            <?php
                        }
                        ?>
                        <button class="btn btn-info fa fa-refresh" id="edit" onclick="buttonClicked(this)" type="button"> Muuda</button>
                        <?php
                        if (!($checked == 3)){?>
                            <button class="btn btn-info fa fa-lock" id="archive" onclick="buttonClicked(this)" type="button"> Arhiivi</button>
                            <?php
                        }
                        else{?>
                            <button class="btn btn-info fa fa-recycle" id="restore" onclick="buttonClicked(this)" type="button"> Taasta</button>
                            <?php
                        }
                    }
                    ?>
                    <button class="btn btn-primary fa fa-backward" id="back" onclick="buttonClicked(this)" type="button"> Tagasi</button>
                    <button class="btn btn-primary fa fa-floppy-o" id="save" onclick="buttonClicked(this)" type="button" style="display: none"> Salvesta</button>
                    <button class="btn btn-primary fa fa-ban" id="cancel" onclick="buttonClicked(this)" type="button" style="display: none"> Loobu</button>
                </div>
                <input type="hidden" name="hiddenContent" id="hiddenContent"/>
            </form>
        </div>


        <!-- Modal Subscription -->
        <div class="modal fade modal-ext" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
            <div class="modal-dialog" role="document">
                <!--Content-->
                <div class="modal-content">
                    <!--Header-->
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                        <h4 class="modal-title w-100" id="myModalLabel">Teavita veast</h4>
                    </div>
                    <!--Body-->
                    <div class="modal-body">
                        <div class="md-form">
                            <i class="fa fa-eye prefix"></i>
                            <input type="text" id="faulty" class="form-control">
                            <label for="form22">Kopeeri vigane lause</label>
                        </div>

                        <div class="md-form">
                            <i class="fa fa-check prefix"></i>
                            <input type="text" id="correct" class="form-control">
                            <label for="form32">Parandatud lause</label>
                        </div>

                        <div class="text-center" data-dismiss="modal">
                            <button class="btn btn-primary" id="sendFix">Saada</button>
                        </div>
                    </div>
                </div>
                <!--/.Content-->
            </div>
        </div>
        

        <div class="modal fade bd-example-modal-lg" id="historyModal" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
            <div class="modal-dialog modal-lg">
                <!--Content-->
                <div class="modal-content">
                    <!--Header-->
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                        <h4 class="modal-title" id="historyLabel"></h4>
                    </div>
                    <!--Body-->
                    <div class="modal-body-history" style="padding: 10px">
                        ...
                    </div>
                    <!--Footer-->
                    <div class="modal-footer">
                        <button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>
                    </div>
                </div>
                <!--/.Content-->
            </div>
        </div>


    </main>

    <!--Footer-->
    <footer class="page-footer fixed-bottom" style="text-align: center">
        <?php include ('footer.html'); ?>
    </footer>
    <!--/.Footer-->


    <!-- SCRIPTS -->
    <script src="ckeditor/ckeditor.js"></script>
    <script type="text/javascript" src="js/jquery-3.1.1.min.js"></script>
    <script type="text/javascript" src="js/tether.min.js"></script>
    <script type="text/javascript" src="js/bootstrap.min.js"></script>
    <script type="text/javascript" src="js/mdb.min.js"></script>
    <script src="sweetalert-master/dist/sweetalert.min.js"></script>
    <script type="text/javascript">
        function buttonClicked(buttonElement) {
            var buttonClickedId = buttonElement.id;
            var ifEdit = <?= $ifEdit; ?>;
            var fileId = <?= $index; ?>;
            var lastEdit = '<?= $edited; ?>';
            if (buttonClickedId === 'edit'){
                if (ifEdit == 0){
                    $.post(
                        'updateDocument.php',
                        {
                            id: fileId,
                            ifEdit: 1,
                            content: ''
                        },
                        function (v) {
                            CKEDITOR.replace('newContent');
                            $('#edit').hide();
                            $('#download').hide();
                            $('#back').hide();
                            $('#confirm').hide();
                            $('#archive').hide();
                            $('#save').show();
                            $('#cancel').show();
                            scroll(0,0);
                        }
                    );
                }
                else{
                    event.preventDefault();
                    toastr['error']('See dokument on hetkel juba töötlemisel!');
                }
            }
            else if (buttonClickedId === 'save'){
                CKEDITOR.instances['newContent'].destroy();
                $('#hiddenContent').val($('#newContent').html());
                var newContent = $('#hiddenContent').val();
                var oldContent = $('#oldContent').html();
                $.post(
                    'updateDocument.php',
                    {
                        id: fileId,
                        ifEdit: 0,
                        lastEdit: lastEdit,
                        content: newContent,
                        oldContent: oldContent
                    },
                    function (v) {
                        console.log(v);
                        $('#edit').show();
                        $('#download').show();
                        $('#confirm').show();
                        $('#archive').show();
                        $('#back').hide();
                        $('#save').hide();
                        $('#cancel').hide();
                        scroll(0,0);
                        toastr["success"]("Dokument edukalt uuendatud!");
                        setTimeout (function () {
                            location.reload();
                        }, 500);
                    }
                );
            }
            else if (buttonClickedId === 'cancel'){
                $.post(
                    'updateDocument.php',
                    {
                        id: fileId,
                        ifEdit: 0,
                        content: ''
                    },
                    function (v) {
                        CKEDITOR.instances['newContent'].destroy();
                        $('#edit').show();
                        $('#download').show();
                        $('#confirm').show();
                        $('#archive').show();
                        $('#back').show();
                        $('#save').hide();
                        $('#cancel').hide();
                        scroll(0,0);
                        toastr["info"]("Dokumendi muutmine katkestatud!");
                    }
                );
            }
            else if (buttonClickedId === 'download'){
                window.location.href = 'download.php?id=<?= $index; ?>';
            }
            else if (buttonClickedId === 'confirm' || buttonClickedId === 'restore'){
                swal({
                        title: "Kas oled kindel, et soovid dokumendi kõigile nähtavaks teha?",
                        type: "info",
                        confirmButtonColor: "#0040aa",
                        confirmButtonText: "Jah",
                        showCancelButton: true,
                        cancelButtonText: "Ei",
                        closeOnConfirm: false
                    },
                    function(isConfirm){
                        if (isConfirm){
                            $.post(
                                'updateDocument.php',
                                {
                                    id: fileId,
                                    ifEdit: 0,
                                    content: '',
                                    confirm: 1
                                },
                                function (v) {
                                    $('#edit').show();
                                    $('#download').show();
                                    $('#confirm').hide();
                                    $('#restore').hide();
                                    $('#back').show();
                                    $('#save').hide();
                                    $('#cancel').hide();
                                    scroll(0,0);
                                    toastr["info"]("Dokument kõigile kättesaadav!");
                                    setTimeout (function () {
                                        location.reload();
                                    }, 300);
                                }
                            );
                        }
                    }
                );
            }
            else if (buttonClickedId === "archive"){
                swal({
                        title: "Kas oled kindel, et soovid dokumendi arhiveerida?",
                        type: "info",
                        confirmButtonColor: "#0040aa",
                        confirmButtonText: "Jah",
                        showCancelButton: true,
                        cancelButtonText: "Ei",
                        closeOnConfirm: false
                    },
                    function(isConfirm){
                        if (isConfirm){
                            $.post(
                                'updateDocument.php',
                                {
                                    id: fileId,
                                    ifEdit: 0,
                                    content: '',
                                    archive: 3
                                },
                                function (v) {
                                    $('#download').show();
                                    $('#edit').show();
                                    $('#archive').hide();
                                    $('#confirm').hide();
                                    $('#back').show();
                                    $('#save').hide();
                                    $('#cancel').hide();
                                    scroll(0,0);
                                    toastr["info"]("Dokument saadeti arhiivi!");
                                    setTimeout (function () {
                                        location.reload();
                                    }, 300);
                                }
                            );
                        }
                    }
                );
            }
            else if (buttonClickedId === 'back'){
                window.location = document.referrer
            }
        }

        $('#sendFix').click(function () {
            $.post(
                'sendFix.php',
                {
                    id: <?= $index; ?>,
                    userId: 1,
                    faulty: document.getElementById('faulty').value,
                    correct: document.getElementById('correct').value
                },
                function (v) {
                    $('#faulty').val('');
                    $('#correct').val('');
                    toastr["success"]("Parandus saadetud!");
                }
            )
        });

        $('#correct').keyup(function (e) {
            if (e.keyCode == 13) {
                $('#sendFix').trigger("click");
            }
        });

        $('.dropdown-item').click(function() {
            var ver = $(this).text();
            $('#historyLabel').html(ver);
            var divContent = $(this).next('div').html();
            $('.modal-body-history').html(divContent);
        });



        $('.favourite').click(function () {
            var documentId = $(this).attr('id');
            var ourHeart = $(this);
            if (ourHeart.hasClass('fa-heart-o')){
                $.post(
                    'userFavourites.php',
                    {
                        ifNew: 1,
                        userId: <?=$authorId; ?>,
                        documentId: documentId
                    },
                    function (v) {
                        ourHeart.toggleClass('fa-heart-o').toggleClass('fa-heart');
                        ourHeart.attr('title', 'Ei meeldi');

                    }
                );
            }
            else if (ourHeart.hasClass('fa-heart')){
                $.post(
                    'userFavourites.php',
                    {
                        ifNew: 0,
                        userId: <?=$authorId; ?>,
                        documentId: documentId
                    },
                    function (v) {
                        ourHeart.toggleClass('fa-heart-o').toggleClass('fa-heart');
                        ourHeart.attr('title', 'Meeldib');
                    }
                );
            }
        });

    </script>

</body>
</html>