<?php 

include '../db_connect.php';

session_start();


if($_SERVER["REQUEST_METHOD"] == "POST") {
    $user_id = $_SESSION['user_id'];
    $text_content = $_POST['text_content'];
    $image_path = NULL;

    if(!empty($_FILES['image']['name'])){
        $upload_dir = "../posts/"; 
        $target_dir = "posts/"; 

      
        $filename = $user_id . "_" . basename($_FILES['image']['name']);
        $target_file = $upload_dir . $filename;

        
        if(move_uploaded_file($_FILES['image']['tmp_name'], $target_file)){
            $image_path = $target_dir . $filename; 
        }
    }

    
    $stmt = $pdo->prepare("INSERT INTO posts (user_id, text_content, image_path) VALUES (:user_id, :text_content, :image_path)");
    $stmt->execute([
        ':user_id' => $user_id,
        ':text_content' => $text_content,
        ':image_path' => $image_path
    ]);

    header("Location: ../index.php"); 
    exit();
}


?>