<?php
session_start();
date_default_timezone_set('Africa/Nairobi');    
include_once 'model/posts_model.php';

// Check if the form is submitted
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Retrieve form data
    $title = $_POST['postTitle'];
    $content = $_POST['postContent'];
    $category_id = $_POST['postCategory'];
    $post_status = $_POST['postStatus'];
    $comment_status = $_POST['commentStatus'];
    $post_name = preg_replace('/\s+/', '-', strtolower($title)); // Generate post_name from title

    // Truncate to 10 characters max
    $post_name = substr($post_name, 0, 10);

    // Ensure no trailing hyphen (if title is longer than 10 characters)
    $post_name = rtrim($post_name, '-');
    
    // Author ID should come from the session
    $author_id = $_SESSION['user_id'];  // Make sure you set the session correctly
    
    // Get current date
    $post_date = date('Y-m-d H:i:s');
    
    // Handle the image upload
    if (isset($_FILES['postImage']) && $_FILES['postImage']['error'] == 0) {
        // Get the file details
        $image = $_FILES['postImage'];
        $image_name = $image['name'];
        $image_tmp_name = $image['tmp_name'];
        $image_size = $image['size'];
        $image_ext = strtolower(pathinfo($image_name, PATHINFO_EXTENSION));  // Convert to lowercase for comparison

        // Define allowed image extensions and max size (5MB)
        $allowed_ext = ['jpg', 'jpeg', 'png', 'gif'];
        $max_size = 5 * 1024 * 1024;  // 5MB

        // Validate the image extension
        if (!in_array($image_ext, $allowed_ext)) {
            $_SESSION['notification'] =[
            'type' => "error", 
            'title' => 'Error',
            'message' => "Invalid file type. Only JPG, PNG, GIF files are allowed."
            ];
            header('Location:posts.php');
            exit;
        }

        // Validate the image size
        if ($image_size > $max_size) {
            $_SESSION['notification'] =[
            'type' => "error", 
            'title' => 'Error',
            'message' => "The file size exceeds the maximum allowed size of 5MB."
            ];
            header('Location:posts.php');
            exit;
        }
        
        // Move the uploaded image to the 'uploads' directory
        $upload_dir = '../uploads/';
        $new_image_name = time() . '.' . $image_ext;  // Generate a unique name for the image
        $upload_path = $upload_dir . $new_image_name;
        
        if (move_uploaded_file($image_tmp_name, $upload_path)) {
            // Image uploaded successfully, now save the post
            $posts_model = new posts_model();
            if ($posts_model->add_post($author_id, $post_date, $content, $title, $category_id, $post_status, $comment_status, $post_name, $new_image_name)) {
                $_SESSION['notification'] =[
                    'type' => "success", 
                    'title' => 'Success',
                    'message' => "Post added successfully!."
                    ];
                header('Location:posts.php');
                exit;
                
            } else {

                $_SESSION['notification'] =[
                    'type' => "error", 
                    'title' => 'Error',
                    'message' => "Failed to add the post."
                ];
                header('Location:posts.php');
                exit;
            }
        } else {
                $_SESSION['notification'] =[
                    'type' => "error", 
                    'title' => 'Error',
                    'message' => "Failed to upload the image."
                ];
                header('Location:posts.php');
                exit;
        }
    } else {
            $_SESSION['notification'] =[
                'type' => "error", 
                'title' => 'Error',
                'message' => "Please upload an image."
            ];
            header('Location:posts.php');
            exit;
    }
}
?>
