<?php

// Check if the there is any Data posted
if (!empty($_POST) && $_POST['title'] != '') {
    // Insert new Blog-Post
    try {
        if (isset($_FILES) && !empty($_FILES['post_image'])) {
            // Allow only these File extensions
            $AllowedExtension = array('jpg', 'jpeg', 'png');
            $ImageFileType = pathinfo($_FILES['post_image']['name'], PATHINFO_EXTENSION);
            // Check for Fileextensions
            if (!in_array($ImageFileType, $AllowedExtension)) {
                throw new Exception('Nicht erlaubter Dateityp');
            }
            // Upload into Directory
            $TargetDir = 'uploads/';
            $UploadFile = $TargetDir . sha1(basename($_FILES['post_image']['name'])) . '.' . $ImageFileType;
            // Move the File into the TargetDir
            if (move_uploaded_file($_FILES['post_image']['tmp_name'], $UploadFile)) {
                $_POST['post_image'] = $UploadFile;
            } else {
                throw new Exception('Fehler beim Datei upload');
            }
        }
        $BlogPost = new BlogPost(null);
        $BlogPost->AddNewPost($_POST);
        header('Location: index.php');
    } catch (Exception $e) {
        $Notices[] = $e->getMessage();
    }
}