<?php
require_once '../connect.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    try {
        $conn->beginTransaction();
 
        $bookId = $_POST['bookId'];
        
        $getImageQuery = "SELECT coverimage FROM book WHERE bookid = :bookId";
        $imageStmt = $conn->prepare($getImageQuery);
        $imageStmt->execute([':bookId' => $bookId]);
        $imageResult = $imageStmt->fetch(PDO::FETCH_ASSOC);
        
        $query = "CALL delete_book(:bookId)";
        $stmt = $conn->prepare($query);
        $stmt->execute([':bookId' => $bookId]);
 
        if ($imageResult && $imageResult['coverimage']) {
            $imagePath = 'BookImages/' . $imageResult['coverimage'];
            if (file_exists($imagePath)) {
                unlink($imagePath);
            }
        }
 
        $conn->commit();
        
        echo json_encode(['success' => true]);
 
    } catch(PDOException $e) {
        if ($conn->inTransaction()) {
            $conn->rollBack();
        }
        echo json_encode(['success' => false, 'error' => $e->getMessage()]);
    } catch(Exception $e) {
        if ($conn->inTransaction()) {
            $conn->rollBack(); 
        }
        echo json_encode(['success' => false, 'error' => $e->getMessage()]);
    }
 }

?>