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

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

require '../connect.php';

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

    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        throw new Exception('Invalid request method');
    }


    $isbn = $_POST['isbn'] ?? null;
    $title = $_POST['title'] ?? null;
    $genre = $_POST['genre'] ?? null;
    $publishedYear = $_POST['publishedYear'] ?? null;
    $description = $_POST['description'] ?? null;
    $totalCopies = $_POST['totalCopies'] ?? 0;
    $format = $_POST['format'] ?? null;
    $language = $_POST['language'] ?? null;
    $publisher = $_POST['publisher'] ?? null;
    $pages = $_POST['pages'] ?? null;
    $authorId = $_POST['author'] ?? null; 

    // file upload
    $coverImage = null;
    if (isset($_FILES['coverImage']) && $_FILES['coverImage']['error'] === UPLOAD_ERR_OK) {
        $uploadDir = '../BookImages/';
        if (!file_exists($uploadDir)) {
            mkdir($uploadDir, 0777, true);
        }
        
        $fileExtension = pathinfo($_FILES['coverImage']['name'], PATHINFO_EXTENSION);
        $fileName = uniqid() . '.' . $fileExtension;
        $targetPath = $uploadDir . $fileName;
        
        if (move_uploaded_file($_FILES['coverImage']['tmp_name'], $targetPath)) {
            $coverImage = $fileName;
        }
    }


    if (!$isbn || !$title || !$genre || !$publishedYear || !$format || 
        !$language || !$publisher || !$pages || !$authorId) {
        throw new Exception('Missing required fields');
    }

    /*
    // Insert into Book table
    $sql = "INSERT INTO Book (ISBN, Title, Genre, PublishedYear, Description, CoverImage, TotalCopies) 
            VALUES (:isbn, :title, :genre, :publishedYear, :description, :coverImage, :totalCopies)";
    //echo "RUNNING!";
    $stmt = $conn->prepare($sql);
    $stmt->execute([
        ':isbn' => $isbn,
        ':title' => $title,
        ':genre' => $genre,
        ':publishedYear' => $publishedYear,
        ':description' => $description,
        ':coverImage' => $coverImage,
        ':totalCopies' => $totalCopies
    ]);

    $bookId = $conn->lastInsertId();
    error_log("Generated BookID: " . $bookId);

    // Insert into Book_Details table
    $sql = "INSERT INTO Book_Details (BookID, Format, Language, Publisher, Pages) 
    VALUES (:bookId, :format, :language, :publisher, :pages)";

    $stmt = $conn->prepare($sql);
    $stmt->execute([
    ':bookId' => $bookId,
    ':format' => $format,
    ':language' => $language,
    ':publisher' => $publisher,
    ':pages' => $pages
    ]);
    */

    $sql = "CALL add_book(:ISBN, :Title, :Genre, :PublishedYear, :Description, :TotalCopies, :Format, :Language, :Publisher, :Pages, :AuthorID, :CoverImage)";
    $stmt = $conn->prepare($sql);
    $stmt->execute([
        ':ISBN' => $isbn,
        ':Title' => $title,
        ':Genre' => $genre,
        ':PublishedYear' => $publishedYear,
        ':Description' => $description,
        ':CoverImage' => $coverImage,
        ':TotalCopies' => $totalCopies,
        ':Format' => $format,
        ':Language' => $language,
        ':Publisher' => $publisher,
        ':Pages' => $pages,
        ':AuthorID' =>  $authorId
    ]);

    $bookId = $conn->lastInsertId();

    $allowedConditions = ['New', 'Good', 'Damaged'];
    foreach ($_POST['condition'] as $index => $condition) {
        if (!in_array($condition, $allowedConditions)) {
            throw new Exception('Invalid condition value: ' . $condition);
        }
    }

    if (isset($_POST['condition']) && isset($_POST['quantity']) && 
        is_array($_POST['condition']) && is_array($_POST['quantity'])) {

        $sql = "INSERT INTO Book_Copies (BookID, Condition) 
                VALUES (:bookId, :condition)";
        $stmt = $conn->prepare($sql);

        foreach ($_POST['condition'] as $index => $condition) {
            $quantity = $_POST['quantity'][$index] ?? 0;
            if ($condition && $quantity > 0) {
                // Loop through the quantity to insert individual rows
                for ($i = 1; $i <= $quantity; $i++) {
                    $stmt->execute([
                        ':bookId' => $bookId,
                        ':condition' => $condition
                    ]);
                }
            }
        }
    }
    // Commit the transaction
    $conn->commit();

    echo json_encode(['success' => true, 'message' => 'Book added successfully']);
} catch (Exception $e) {
    if ($conn->inTransaction()) {
        $conn->rollBack();
    }

    if (isset($targetPath) && file_exists($targetPath)) {
        unlink($targetPath);
    }

    error_log("Error in AddBook.php: " . $e->getMessage());
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}