<div style='display: none' class='new_post'>
    <div class="entry-wrapper">

        <div class="data-wrapper">
            <form method='post' autocomplete='off' enctype="multipart/form-data">
                <div class="post_c_header">
                    <h1>Beitrag erstellen</h1>
                    <div class="close_entry_button"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-x-square" viewBox="0 0 16 16">
                <path d="M14 1a1 1 0 0 1 1 1v12a1 1 0 0 1-1 1H2a1 1 0 0 1-1-1V2a1 1 0 0 1 1-1h12zM2 0a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V2a2 2 0 0 0-2-2H2z" />
                <path d="M4.646 4.646a.5.5 0 0 1 .708 0L8 7.293l2.646-2.647a.5.5 0 0 1 .708.708L8.707 8l2.647 2.646a.5.5 0 0 1-.708.708L8 8.707l-2.646 2.647a.5.5 0 0 1-.708-.708L7.293 8 4.646 5.354a.5.5 0 0 1 0-.708z" />
            </svg>schließen ohne zu speichern
        </div>
                </div>
                <?php select_category();?>
                <textarea id='title' type='text' name='title' required
                    placeholder='Titel & Teaser' maxlength='255'></textarea>
                <div class="form-floating" id='image_1_wrapper1'>
                    <input id='image_1' type='file' name='image_1' accept=".png,.jpg,.jpeg,.gif,.mp4">
                    <label for="image_1">0 von 5 max. Bilder</label>
                </div>

                <div class="form-floating" id='image_2_wrapper2' style="display: none">
                    <input id='image_2' type='file' name='image_2' accept=".png,.jpg,.jpeg,.gif,.mp4"
                        >
                    <label for="image_2">2 von 5 max. Bilder</label>
                </div>

                <div class="form-floating" id='image_3_wrapper3' style="display: none">
                    <input id='image_3' type='file' name='image_3' accept=".png,.jpg,.jpeg,.gif,.mp4"
                        >
                    <label for="image_3">3 von 5 max. Bilder</label>
                </div>
                <div class="form-floating" id='image_4_wrapper4' style="display: none">
                    <input id='image_4' type='file' name='image_4' accept=".png,.jpg,.jpeg,.gif,.mp4"
                        >
                    <label for="image_4">4 von 5 max. Bilder</label>
                </div>
                <div class="form-floating" id='image_5_wrapper5' style="display: none">
                    <input id='image_5' type='file' name='image_5' accept=".png,.jpg,.jpeg,.gif,.mp4"
                        >
                    <label for="image_5">5 von 5 max. Bilder</label>
                </div>

                <textarea id='description' name="description" rows="4" cols="50"
                    placeholder='Beschreibungstext (maximal 750 Zeichen)' maxlength='750'></textarea>

                <input id='absenden' type='submit' name='submit_post' value='Beitrag veröffentlichen'>
            </form>
        </div>
    </div>
</div>

<script>
    // Funktion, die aufgerufen wird, wenn ein Bild hochgeladen wird
    function handleImageUpload(inputElement, nextWrapperId) {
        const fileInput = inputElement;
        const nextWrapper = document.getElementById(nextWrapperId);

        fileInput.addEventListener('change', function() {
            if (fileInput.files.length > 0) {
                nextWrapper.style.display = 'flex';
            } else {
                nextWrapper.style.display = 'none';
            }
        });
    }

    // Event-Listener für die Bild-Eingabefelder
    document.addEventListener('DOMContentLoaded', function() {
        const image1Input = document.getElementById('image_1');
        handleImageUpload(image1Input, 'image_2_wrapper2');

        const image2Input = document.getElementById('image_2');
        handleImageUpload(image2Input, 'image_3_wrapper3');

        const image3Input = document.getElementById('image_3');
        handleImageUpload(image3Input, 'image_4_wrapper4');

        const image4Input = document.getElementById('image_4');
        handleImageUpload(image4Input, 'image_5_wrapper5');
    });
</script>

<?php

if(isset($_POST['submit_post'])){
    if($_POST['title'] != ""){
        $slideshow_header_id = createSlideshowHeader();
        $i = 1;
        while ($i <= 5) {
          if(!$_FILES['image_'.$i]['name'] == "") {
            uploadImage('image_'.$i, $slideshow_header_id);
          }
          $i++;
        }
        $current_date = new DateTime();
        $content = str_replace(array('\r\n', '\n\r', '\n', '\r'), '<br>', $_POST['description']);

        $insertquery = "INSERT INTO community_board_post
        (creation_date, creation_contact, title, content, gallery_id)
        VALUES (
            '" . $current_date->format('Y-m-d H:i:s') . "',
            '" . $GLOBALS['main_contact']['id'] . "',
            '" . $_POST['title'] . "',
            '" . $content . "',
            '" . $slideshow_header_id ."'
        )";
        $result = @mysqli_query($GLOBALS['mysql_con'], $insertquery);

        $post_id = mysqli_insert_id($GLOBALS['mysql_con']);

        $insert2 = "INSERT INTO community_board_post_category_link
        (community_board_post_id, community_board_category_id)
        VALUES (
            '" . $post_id . "',
            '" . $_POST['category'] ."'
        )";
        $result2 = @mysqli_query($GLOBALS['mysql_con'], $insert2);
        $host  = $_SERVER['HTTP_HOST'];
        $uri   = $_SERVER["REDIRECT_URL"];
        echo "<script type='text/javascript'>window.location.href = 'https://".$host.$uri."';</script>";
    }
}

function select_category(){
    $query = "SELECT * FROM community_board_category ORDER BY sorting";
    $result = @mysqli_query($GLOBALS['mysql_con'], $query);
    echo "<select id='category' name='category'>";
    echo "<option value='0'>Kategorie auswählen</option>";
    while($row = @mysqli_fetch_array($result)){
        echo "<option value='".$row['id']."'>".$row['description']."</option>";
    }
    echo "</select>";
}

function uploadImage($name, $header_id){
    $upload_folder = '/userdata/intranet/community_board/';
    $filename = pathinfo($_FILES[$name]['name'], PATHINFO_FILENAME);
    $extension = strtolower(pathinfo($_FILES[$name]['name'], PATHINFO_EXTENSION));
  
    $allowed_extensions = array('png', 'jpg', 'jpeg', 'gif', 'mp4');
    if(!in_array($extension, $allowed_extensions)) {
        die();
    }
  
    $saveFilename = $header_id . "_" . cleanFilename($_FILES[$name]['name']);
  
    define("PATH_RESIZE", "../../userdata/intranet/community_board/");
    define("PATH_ORIGINAL_FRONTEND", "/userdata/intranet/community_board/");
    move_uploaded_file($_FILES[$name]['tmp_name'], PATH_RESIZE . $saveFilename);
  
    $description = 'image';
    $preview = "<img src='".PATH_ORIGINAL_FRONTEND.$saveFilename."'>";
    if($extension == 'mp4'){
      $description = 'video';
      $preview = "<video src='".PATH_ORIGINAL_FRONTEND.$saveFilename."'>";
    }
  
    createSlideshowLine($header_id, $preview, $saveFilename, $description);
}

function createSlideshowHeader(){
    $insert_slideshow_header = $GLOBALS['pdo_conn']->prepare("INSERT INTO slideshow_header VALUES (NULL, ".$GLOBALS['language']['id'].", '', 1000, 500, 'fade', 'yes', 4, 1, 'fixed', 'bottom', '', '', 1, 0)");
    $insert_slideshow_header->execute();
    $id = $GLOBALS['pdo_conn']->lastInsertId();
    return $id;
}
  
function createSlideshowLine($header_id, $preview, $filename, $description){
    $insert_slideshow_line = $GLOBALS['pdo_conn']->prepare("INSERT INTO slideshow_line VALUES(NULL, :header_id, :preview, :filename, :description, '', '', '', '', '', 0, 0, 0)");
    $insert_slideshow_line->execute(array(':header_id' => $header_id, ':preview' => $preview, ':filename' => $filename, ':description' => $description));
}

