<?php
// add_post.php
// Autors: Kārlis Mālnieks
// pievieno datubazes savienojumu
require_once 'db_connection.php';

// parbauda vai metode ir POST
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // iegust lietotaja ID no sesijas
    $userId = $_SESSION['user_id'];
    // iegust izveleto cilni un aprakstu no POST datiem
    $tab = $_POST['tab'];
    $description = $_POST['description'];
    $imagePaths = [];

    // parbauda vai atteli ir augslupladeti
    if (isset($_FILES['images'])) {
        foreach ($_FILES['images']['tmp_name'] as $key => $tmpName) {
            // parbauda vai nav kludas augsluplade
            if ($_FILES['images']['error'][$key] === UPLOAD_ERR_OK) {
                $fileTmpPath = $_FILES['images']['tmp_name'][$key];
                $fileName = $_FILES['images']['name'][$key];
                $fileType = $_FILES['images']['type'][$key];

                // atlauto failu tipu parbaude
                $allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
                if (in_array($fileType, $allowedTypes)) {
                    // sagatavo augsluplades direktoriju un faila nosaukumu
                    $uploadDir = '../uploads/';
                    $newFileName = uniqid('post_', true) . '.' . pathinfo($fileName, PATHINFO_EXTENSION);
                    $destPath = $uploadDir . $newFileName;

                    // parbauda vai fails tika veiksmigi augslupladets
                    if (move_uploaded_file($fileTmpPath, $destPath)) {
                        $imagePaths[] = $destPath;
                    }
                }
            }
        }
    }

    // attelu celsu saglaba JSON formata
    $imagePathsJson = json_encode($imagePaths);

    // sagatavo SQL pieprasijumu, lai pievienotu jaunu ierakstu
    $sql = "INSERT INTO posts (user_id, tab, description, image) VALUES (:user_id, :tab, :description, :image)";
    $stmt = $pdo->prepare($sql);
    $stmt->bindParam(':user_id', $userId);
    $stmt->bindParam(':tab', $tab);
    $stmt->bindParam(':description', $description);
    $stmt->bindParam(':image', $imagePathsJson);

    // izpilda pieprasijumu un atgriez rezultatu
    if ($stmt->execute()) {
        echo json_encode(['success' => true]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Neizdevās pievienot ierakstu.']);
    }
}
?>
