<?php

session_start();

if (!isset($_GET['id'])) {

    http_response_code(400); 
    echo "Book ID is missing";
    exit; 
}

require __DIR__ . "/../db/database.php";

$bookId = $_GET['id'];
if (!is_numeric($bookId)) {

    http_response_code(400); 
    echo "Invalid book ID";
    exit; 
}

//delete image file section
$sql = "SELECT image FROM books WHERE id = ?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("i", $bookId);
$stmt->execute();
$stmt->bind_result($image);
$stmt->fetch();
$stmt->close();

// Check if image exists before attempting to delete
if ($image) {
    $imagePath = "../uploads/" . $image;
    if (file_exists($imagePath)) {
        unlink($imagePath);
        echo "Image deleted successfully.";
    } else {
        echo "Image not found.";
    }
} else {
    echo "No image associated with this book.";
}

// delete entry
$sql = "DELETE FROM books WHERE id = ?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("i", $bookId);
$result = $stmt->execute();

if ($result) {

    http_response_code(200); 
    echo "Book deleted successfully";
} else {

    http_response_code(500); 
    echo "Error deleting book";
}


$stmt->close();
$mysqli->close();
