<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    print_r($_POST);
    $title = $_POST['title'];
    $author = $_POST['author'];
    $year = $_POST['year'];
    $desc = $_POST['description'];

    if(isset($_FILES['image'])) {

        $fileData = file_get_contents($_FILES['image']['tmp_name']);
        $uploadDir = __DIR__ . '/../uploads/'; 
        $newFileName = uniqid() . '_' . $_FILES['image']['name']; 
        $uploadPath = $uploadDir . $newFileName;

        if(move_uploaded_file($_FILES['image']['tmp_name'], $uploadPath)) {
            $mysqli = require __DIR__ . "/../db/database.php";

            $sql_insert_book = "INSERT INTO books(title, author, year, description, image) VALUES (?, ?, ?, ?, ?)";
            $stmt_insert_user = $mysqli->prepare($sql_insert_book);
            $stmt_insert_user->bind_param("ssiss", $title, $author, $year, $desc, $newFileName);

            if($stmt_insert_user->execute()) {
                $message = "Book inserted successfully!";
            } else {
                $error_message = "Error inserting book: " . $mysqli->error;
            }
        } else {
            $error_message = "Error moving uploaded file.";
        }
    } else {
        $error_message = "Error uploading file: " . $_FILES['image']['error'];
    }
} 

