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

header('Content-Type: application/json');
error_reporting(0); 

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

        $required = ['bookId', 'isbn', 'title', 'genre', 'publishedYear', 'description', 'totalCopies'];
        foreach ($required as $field) {
            if (!isset($_POST[$field])) {
                throw new Exception("Missing required field: $field");
            }
        }

        $bookId = $_POST['bookId'];
        if (!is_numeric($bookId)) {
            throw new Exception('Invalid book ID');
        }

        // Initialize variables
        $imageName = null;
        $oldImage = null;
        $uploadDir = __DIR__ . '/../BookImages/'; 

        $stmt = $conn->prepare("SELECT coverimage FROM book WHERE bookid = ?");
        $stmt->execute([$bookId]);
        $oldImage = $stmt->fetchColumn();

        // Handle file upload
        if (isset($_FILES['coverImage']) && $_FILES['coverImage']['error'] === UPLOAD_ERR_OK) {
            // Create directory if not exists
            if (!file_exists($uploadDir)) {
                mkdir($uploadDir, 0777, true);
            }

            $fileExtension = strtolower(pathinfo($_FILES['coverImage']['name'], PATHINFO_EXTENSION));
            $allowedTypes = ['jpg', 'jpeg', 'png', 'gif'];
            if (!in_array($fileExtension, $allowedTypes)) {
                throw new Exception('Invalid file type. Allowed: JPG, JPEG, PNG, GIF.');
            }

            // Generate unique filename
            $fileName = uniqid() . '_' . basename($_FILES['coverImage']['name']);
            $targetPath = $uploadDir . $fileName;

            if (!move_uploaded_file($_FILES['coverImage']['tmp_name'], $targetPath)) {
                throw new Exception('Failed to upload image.');
            }
            $imageName = $fileName;
        }

        // Start transaction
        $conn->beginTransaction();

        $bookParams = [
            ':isbn' => $_POST['isbn'],
            ':title' => $_POST['title'],
            ':genre' => $_POST['genre'],
            ':publishedYear' => $_POST['publishedYear'],
            ':description' => $_POST['description'],
            ':totalCopies' => $_POST['totalCopies'],
            ':bookId' => $bookId,
            ':format' => $_POST['format'],
            ':language' => $_POST['language'],
            ':pages' => $_POST['pages'],
            ':publisher' => $_POST['publisher'],
        ];

        if ($imageName) {
            $bookParams[':coverImage'] = $imageName;
        }
        else {
            $bookParams[':coverImage'] = $oldImage;
        }

        $stmt = $conn->prepare('CALL update_book(:bookId, :title, :isbn, :genre, :publishedYear, :description, :totalCopies, :coverImage, :language, :publisher, :pages, :format)');
        $stmt->execute($bookParams);

        // Delete old image after successful update
        if ($imageName && $oldImage && $imageName != $oldImage) {
            $oldImagePath = $uploadDir . $oldImage;
            if (file_exists($oldImagePath)) {
                unlink($oldImagePath);
            }
        }

        $conn->commit();
        echo json_encode(['success' => true, 'message' => 'Book updated successfully']);

    } catch (Exception $e) {
        $conn->rollBack();
        // Delete new image if error occurred
        if (isset($targetPath) && file_exists($targetPath)) {
            unlink($targetPath);
        }
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }
}
?>