<?php
$category_id = 0;
if(isset($_GET['category_id'])){
    $category_id = $_GET['category_id'];
}

function load_categories($category_id){
    $query = "SELECT * FROM community_board_category ORDER BY sorting";
    $result = @mysqli_query($GLOBALS['mysql_con'], $query);
    $active_all = '';
    if($category_id == 0){
        $active_all = 'active';
    }
    echo "<a href='?' class='category_item ".$active_all."'>Alle</a>";
    while($row = @mysqli_fetch_array($result)){
        $active = '';
        if($category_id == $row['id']){
            $active = 'active';
        }
        echo "<a href='?category_id=".$row['id']."' class='category_item ".$active."'>".$row['description']."</a>";
    }
}

function load_all_posts($category_id){
    $where = "";
    if($category_id != 0){
        $where = "WHERE community_board_category_id	= ".$category_id;
    }
    $query = "SELECT * FROM community_board_post_category_link ".$where;
    $result = @mysqli_query($GLOBALS['mysql_con'], $query);
    while($row = @mysqli_fetch_array($result)){
        load_post($row['community_board_post_id'], $row['community_board_category_id']);
    }
}

function load_post($post_id, $category_id){
    $query = "SELECT * FROM community_board_post WHERE id = ".$post_id;
    $result = @mysqli_query($GLOBALS['mysql_con'], $query);
    $row = @mysqli_fetch_array($result);
    $user = get_user_from_id($row['creation_contact']);
    $user_image = 'platzhalter.png';
    if($user['image'] != ""){
        $user_image = $user['image'];
    }
    ?>
    <div class='post'  data-id='<?= $post_id?>'>
        <div class='post_header'>
            <div>
                <img src='/userdata/intranet/contact/<?= $user_image?>'>
                <div>
                    <p class="post_header_name"><?= $user['name']?></p>
                    <p class="post_header_category">Kategorie: <?= get_category_from_id($category_id)?></p>
                </div>
            </div>
                <?php if($user['id'] == $GLOBALS['main_contact']['id']){?>
                    <div class='delete_post' data-id='<?= $post_id?>'>
                    <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-trash3" viewBox="0 0 16 16"><path d="M6.5 1h3a.5.5 0 0 1 .5.5v1H6v-1a.5.5 0 0 1 .5-.5ZM11 2.5v-1A1.5 1.5 0 0 0 9.5 0h-3A1.5 1.5 0 0 0 5 1.5v1H2.506a.58.58 0 0 0-.01 0H1.5a.5.5 0 0 0 0 1h.538l.853 10.66A2 2 0 0 0 4.885 16h6.23a2 2 0 0 0 1.994-1.84l.853-10.66h.538a.5.5 0 0 0 0-1h-.995a.59.59 0 0 0-.01 0H11Zm1.958 1-.846 10.58a1 1 0 0 1-.997.92h-6.23a1 1 0 0 1-.997-.92L3.042 3.5h9.916Zm-7.487 1a.5.5 0 0 1 .528.47l.5 8.5a.5.5 0 0 1-.998.06L5 5.03a.5.5 0 0 1 .47-.53Zm5.058 0a.5.5 0 0 1 .47.53l-.5 8.5a.5.5 0 1 1-.998-.06l.5-8.5a.5.5 0 0 1 .528-.47ZM8 4.5a.5.5 0 0 1 .5.5v8.5a.5.5 0 0 1-1 0V5a.5.5 0 0 1 .5-.5Z"/></svg>
                    </div>
                <?php } ?>

        </div>
        <div class='post_image_slider'>
            <?= load_image_slider($row['gallery_id'])?>
        </div>
        <div class='post_content'>
            <div class="post_toolbar">
                <div class="like <?= check_if_liked($post_id)?>">
                    <svg xmlns="http://www.w3.org/2000/svg" width="30.251" height="28.101" viewBox="0 0 30.251 28.101">
    <path id="heart-sharp" d="M18,31.5l-.633-.422c-3.008-2.009-6.814-4.279-9.633-7.616A16.471,16.471,0,0,1,3.375,12.423,7.934,7.934,0,0,1,11.185,4.5,8.863,8.863,0,0,1,18,7.89,8.863,8.863,0,0,1,24.815,4.5a7.933,7.933,0,0,1,7.81,7.921A16.448,16.448,0,0,1,28.266,23.46c-2.819,3.339-6.625,5.61-9.633,7.618Z" transform="translate(-2.874 -4)" stroke-width="1"/>
    </svg>

                    <span class='like_count_<?= $row['id']?>'>0</span>
                </div>
                <div class="comment">
                <svg xmlns="http://www.w3.org/2000/svg" width="37" height="31.864" viewBox="0 0 37 31.864">
  <path id="comment" d="M36,12.857a10.019,10.019,0,0,1-2.411,6.459A16.287,16.287,0,0,1,27.04,24,23.346,23.346,0,0,1,18,25.715a27.434,27.434,0,0,1-2.913-.161,21.959,21.959,0,0,1-9.241,4.862,15.169,15.169,0,0,1-2.29.442.789.789,0,0,1-.613-.181,1.014,1.014,0,0,1-.352-.583v-.02a.265.265,0,0,1-.01-.241.541.541,0,0,0,.04-.2q-.01-.04.09-.191l.121-.181.141-.171.161-.181q.141-.161.623-.693l.693-.763q.211-.231.623-.794a8.178,8.178,0,0,0,.653-1.025q.241-.462.542-1.185a12.788,12.788,0,0,0,.522-1.527A14.748,14.748,0,0,1,1.818,18.5,9.747,9.747,0,0,1,0,12.857,9.569,9.569,0,0,1,1.426,7.865,13.7,13.7,0,0,1,5.263,3.757a19.542,19.542,0,0,1,5.746-2.742A23.923,23.923,0,0,1,18,0a23.346,23.346,0,0,1,9.04,1.718A16.287,16.287,0,0,1,33.589,6.4,10.018,10.018,0,0,1,36,12.857Z" transform="translate(0.5 0.5)" stroke-width="1"/>
</svg>

                    <span class='comment_count_<?= $row['id']?>'>0</span>
                </div>
            </div>
            <h3><?= $row['title']?></h3>
            <p class="post_content_desc"><?= $row['content']?></p>
            <span id="read_more">Mehr lesen</span>
            <div class='post_comments'>
                <?= load_comments($post_id)?>
                <div class='new_comment'>
                <form method='post' autocomplete="off">
                    <input type='hidden' name='input_post_id' value='<?= $post_id?>'>
                    <input type='text' id="new_comment_textarea"name='input_comment' placeholder='Kommentar schreiben'></input>
                    <label>
                        <input type='submit' name='submit_comment' value='Kommentar senden'>
                    </label>    
                </form>
                </div>
            </div>
        </div>
    </div>
    <?php
}

if(isset($_POST['submit_comment'])){
    if($_POST['input_comment'] != ""){
        $comment = str_replace(array('\r\n', '\n\r', '\n', '\r'), '<br>', $_POST['input_comment']);
        $query = "INSERT INTO community_board_comment
        (community_board_post_id, main_contact_id, comment)
        VALUES (
            '" . $_POST['input_post_id'] . "',
            '" . $GLOBALS['main_contact']['id'] . "',
            '" . $comment ."'
        )";
        $result = @mysqli_query($GLOBALS['mysql_con'], $query);
        $host  = $_SERVER['HTTP_HOST'];
        $uri   = $_SERVER["REDIRECT_URL"];
        echo "<script type='text/javascript'>window.location.href = 'https://".$host.$uri."';</script>";
    }
}

function load_image_slider($gallery_id){
    $select_slideshow = $GLOBALS['pdo_conn']->prepare("SELECT * FROM slideshow_line WHERE header_id = ".$gallery_id);
    $select_slideshow->execute(array());
    $res_slideshow = $select_slideshow->fetchALL(PDO::FETCH_ASSOC);
    if($res_slideshow[0]['id'] == 0){
        return;
    }
    echo "<div class='image_slider'>";
    echo "<div class='img_owl'>";
    foreach ($res_slideshow as $key => $value) {
        echo "<div class='image'>";
        if($value['description'] == 'video'){
            echo "<div class='video_settings'>";
            echo '<div data_id="'.$value['id'].'" class="play"><svg xmlns="http://www.w3.org/2000/svg" width="43.713" height="49.926" viewBox="0 0 43.713 49.926">
            <path id="play" d="M3.041.39,42.953,23.148q.78.439.78,1.925t-.78,1.827L3.041,49.658a2.047,2.047,0,0,1-1.462.268A2.591,2.591,0,0,1,.02,49.073v-48Q1.531-.585,3.041.39Z" transform="translate(-0.02 -0.029)"/>
          </svg></div>';
            echo '<div data_id="'.$value['id'].'" class="pause" style="display: none"><svg xmlns="http://www.w3.org/2000/svg" width="49.951" height="49.951" viewBox="0 0 49.951 49.951">
            <path id="pause" d="M43.728,49.951H37.484a6.245,6.245,0,0,1-6.244-6.244V6.244a6.018,6.018,0,0,1,1.829-4.415A6.011,6.011,0,0,1,37.484,0h6.244a6.018,6.018,0,0,1,4.415,1.829,6.011,6.011,0,0,1,1.829,4.415V43.707a6.245,6.245,0,0,1-6.244,6.244Zm-31.22,0H6.264a6.018,6.018,0,0,1-4.415-1.829A6.007,6.007,0,0,1,.021,43.707V6.244A6.018,6.018,0,0,1,1.85,1.829,6.011,6.011,0,0,1,6.265,0h6.244a6.018,6.018,0,0,1,4.415,1.829,6.011,6.011,0,0,1,1.829,4.415V43.707a6.018,6.018,0,0,1-1.829,4.415,6.011,6.011,0,0,1-4.415,1.829Z" transform="translate(-0.021)"/>
          </svg></div>';
            echo "</div>";
            echo "<video data_id='".$value['id']."' src='/userdata/intranet/community_board/".$value['filename']."'>";
        }else {
            echo "<img src='/userdata/intranet/community_board/".$value['filename']."'>";
        }
        echo "</div>";
    }
    echo "</div>";
    echo "</div>";
}

function load_comments($post_id){
    $query = "SELECT * FROM community_board_comment WHERE community_board_post_id = ".$post_id;
    $result = @mysqli_query($GLOBALS['mysql_con'], $query);
    while($row = @mysqli_fetch_array($result)){
        $user = get_user_from_id($row['main_contact_id']);
        $user_image = 'platzhalter.png';
        if($user['image'] != ""){
            $user_image = $user['image'];
        }
        ?>
        <div class='post_comment_item'>
            <img src='/userdata/intranet/contact/<?= $user_image?>'>
            <div>
                <p class="comment_item_content"><?php echo nl2br($row['comment'])?></p>
                <p class="comment_item_author">von: <?= $user['name']?></p>
            </div>
        </div>
        <?php
    }
}

function check_if_liked($post_id){
    $return = '';
    $query = "SELECT * FROM community_board_post_likes WHERE community_board_post_id = ".$post_id." AND main_contact_id = ".$GLOBALS['main_contact']['id'];
    $result = @mysqli_query($GLOBALS['mysql_con'], $query);
    if (@mysqli_num_rows($result) >= 1) {
        $return = 'is_liked';
    }
    return $return;
}

function get_user_from_id($user_id){
    $query = "SELECT * FROM main_contact WHERE id = ".$user_id;
    $result = @mysqli_query($GLOBALS['mysql_con'], $query);
    $row = @mysqli_fetch_array($result);
    return $row;
}

function get_category_from_id($category_id){
    $query = "SELECT * FROM community_board_category WHERE id = ".$category_id;
    $result = @mysqli_query($GLOBALS['mysql_con'], $query);
    $row = @mysqli_fetch_array($result);
    return $row['description'];
}

?>

<div class='community_board'>
    <div class="community_board_header">
        <div class='category_filter'>
            <?= load_categories($category_id);?>
        </div>
        <button class='new_post_button'>+</button>
        <?php require_once('show_community_board_cardform.inc.php')?>
    </div>
    <div class='posts'>
        <?= load_all_posts($category_id);?>
    </div>
</div>
<script>
$('.post').each(function(){
    var post_id = $(this).attr('data-id');
    ajax_action(post_id, 'count_likes', true, '.like_count_'+post_id);
    ajax_action(post_id, 'count_comments', true, '.comment_count_'+post_id);
});

$('.post').on('click', '.like', function() {
    var post_id = $(this).parent().parent().parent().attr('data-id');
    $(this).toggleClass("is_liked");
    ajax_action(post_id, 'update_likes', false);
    setTimeout(function() { 
        ajax_action(post_id, 'count_likes', true, '.like_count_'+post_id);
        ajax_action(post_id, 'count_comments', true, '.comment_count_'+post_id);
    }, 500);
});

function ajax_action(post_id, action, show, content_class = 0){
    $.ajax({
        type: 'POST',
        url: "/module/community_board/community_board_ajax.inc.php",
        data: { 
            post_id : post_id,
            action : action,
            status : status,
            main_contact_id : <?= $GLOBALS['main_contact']['id'] ?>,
        }, 
        success: function(data){
            if(show == true){
                $(content_class).html(data)
            }
        }
    });     
}

$('.posts').on('click', '.delete_post', function() {
    var post_id = $(this).attr('data-id');
    ajax_action(post_id, 'delete_post', false);
    location.reload();
});

$('.new_post_button').click(function() {
    $('.new_post').show();
});
        $('span#read_more').click(function() {
            const $readMoreSpan = $(this);
            const $previousDiv = $readMoreSpan.prev();
            const $nextDiv = $readMoreSpan.next();

            if ($previousDiv.hasClass('show_all')) {
                // Wenn die Klasse 'show_all' bereits vorhanden ist, entferne sie
                $previousDiv.removeClass('show_all');
                $readMoreSpan.html('mehr lesen');
            } else {
                // Wenn die Klasse 'show_all' nicht vorhanden ist, füge sie hinzu
                $previousDiv.addClass('show_all');
                $readMoreSpan.html('weniger lesen');
            }

            $nextDiv.slideToggle();
        });
 

$('.comment').click(function() {
    $(this).parent().next().next().next().next().slideToggle();
});


$(document).ready(function() {
        // Funktion zum Ausblenden des '.new_post'-Elements
        function hideNewPost() {
            $('.new_post').hide();
        }

        // Event-Listener für das Klicken auf den Schließen-Button
        $('.close_entry_button').click(function() {
            hideNewPost();
        });

        // Event-Listener für das Drücken der Escape-Taste
        $(document).keyup(function(e) {
            if (e.key === 'Escape') {
                hideNewPost();
            }
        });
    });
</script>