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

if (isset($_POST['editPostId'])) {
    $postId = $_POST['editPostId'];
    $title = $_POST['editPostTitle'];
    $content = $_POST['editPostContent'];
    $categoryId = $_POST['editPostCategory'];
    $status = $_POST['editPostStatus'];
    $commentStatus = $_POST['editCommentStatus'];
    $post_modified = date('Y-m-d H:i');

    // Handle the image upload (optional)
    $image = null;
    if (!empty($_FILES['editPostImage']['name'])) {
        $targetDir = "../uploads/";
        $targetFile = $targetDir . basename($_FILES['editPostImage']['name']);
        move_uploaded_file($_FILES['editPostImage']['tmp_name'], $targetFile);
        $image = basename($_FILES['editPostImage']['name']);
    }

    $posts_model = new posts_model();

    // Update the post details in the database
    $result = $posts_model->update_post($postId, $title, $content, $categoryId, $status, $commentStatus, $post_modified, $image);

    if ($result) {
        $_SESSION['notification'] = [
            'title' => 'Success',
            'type' => 'success',
            'message' => 'Successfully Updated post details'
        ];
        header('location:posts.php');
        exit();
    } else {
        $_SESSION['notification'] = [
            'title' => 'Success',
            'type' => 'success',
            'message' => 'Successfully Updated post details'
        ];
        header('location:posts.php');
        exit();
    }
}
?>
