<?php
header("Content-Type: application/json");
require_once "../config.php";   // $dbh = new PDO(...)

$action = $_POST['action'] ?? $_GET['action'] ?? '';

try {
    switch ($action) {

        // 👉 INSERT book
        case 'insert':
            try {
                $bookname         = $_POST['bookName'] ?? null;
                $category         = !empty($_POST['categoryId']) ? $_POST['categoryId'] : null;
                $authors          = isset($_POST['authoresId']) ? $_POST['authoresId'] : [];
                $authorIds        = is_array($authors) ? implode(',', $authors) : $authors;
                $edition          = $_POST['edition'] ?? null;
                $volume           = $_POST['volume'] ?? null;
                $publisher        = !empty($_POST['publisherId']) ? $_POST['publisherId'] : null;
                $publication_year = !empty($_POST['publicationYear']) ? $_POST['publicationYear'] : null;
                $cbrb_no          = $_POST['cbrbNo'] ?? null;
                $acc_no           = $_POST['accestionNo'] ?? null;
                $isbn             = $_POST['isbnNo'] ?? null;
                $price            = $_POST['price'] ?? 0;
                $purchase_date    = $_POST['purchaseDate'] ?? null;
                $rack_id          = !empty($_POST['rackId']) ? $_POST['rackId'] : null;
                $total_count      = !empty($_POST['noOfCopices']) ? $_POST['noOfCopices'] : 1;

                $current_count = $total_count;
                $total_price   = $price * $total_count;

                $department_id = !empty($_POST['departmentId']) ? $_POST['departmentId'] : null;
                $degree_id     = !empty($_POST['degreeId']) ? $_POST['degreeId'] : null;
                $status        = isset($_POST['status']) ? $_POST['status'] : 1;

                $sql = "INSERT INTO tblbooks(
                BookName, CatId, AuthorIds, Edition, Volume, Publisher, PublicationYear, 
                CbrbNo, AccessionNumber, ISBNNumber, BookPrice, total_price, PurchaseDate, rack_id, 
                total_count, current_count, department_id, degree_id, Status
            ) VALUES(
                :bookname, :category, :authorIds, :edition, :volume, :publisher, :publication_year, 
                :cbrb_no, :acc_no, :isbn, :price, :total_price, :purchase_date, :rack_id, 
                :total_count, :current_count, :department_id, :degree_id, :status
            )";

                $query = $dbh->prepare($sql);
                $query->bindParam(':bookname', $bookname, PDO::PARAM_STR);
                $query->bindParam(':category', $category, PDO::PARAM_INT);
                $query->bindParam(':authorIds', $authorIds, PDO::PARAM_STR);
                $query->bindParam(':edition', $edition, PDO::PARAM_STR);
                $query->bindParam(':volume', $volume, PDO::PARAM_STR);
                $query->bindParam(':publisher', $publisher, PDO::PARAM_INT);
                $query->bindParam(':publication_year', $publication_year, PDO::PARAM_INT);
                $query->bindParam(':cbrb_no', $cbrb_no, PDO::PARAM_STR);
                $query->bindParam(':acc_no', $acc_no, PDO::PARAM_STR);
                $query->bindParam(':isbn', $isbn, PDO::PARAM_STR);
                $query->bindParam(':price', $price, PDO::PARAM_STR);
                $query->bindParam(':total_price', $total_price, PDO::PARAM_STR);
                $query->bindParam(':purchase_date', $purchase_date, PDO::PARAM_STR);
                $query->bindParam(':rack_id', $rack_id, PDO::PARAM_INT);
                $query->bindParam(':total_count', $total_count, PDO::PARAM_INT);
                $query->bindParam(':current_count', $current_count, PDO::PARAM_INT);
                $query->bindParam(':department_id', $department_id, PDO::PARAM_INT);
                $query->bindParam(':degree_id', $degree_id, PDO::PARAM_INT);
                $query->bindParam(':status', $status, PDO::PARAM_INT);

                // --- Debug: print query with values ---
                $debugQuery = $sql;
                $replacements = [
                    ':bookname' => $bookname,
                    ':category' => $category,
                    ':authorIds' => $authorIds,
                    ':edition' => $edition,
                    ':volume' => $volume,
                    ':publisher' => $publisher,
                    ':publication_year' => $publication_year,
                    ':cbrb_no' => $cbrb_no,
                    ':acc_no' => $acc_no,
                    ':isbn' => $isbn,
                    ':price' => $price,
                    ':total_price' => $total_price,
                    ':purchase_date' => $purchase_date,
                    ':rack_id' => $rack_id,
                    ':total_count' => $total_count,
                    ':current_count' => $current_count,
                    ':department_id' => $department_id,
                    ':degree_id' => $degree_id,
                    ':status' => $status,
                ];

                foreach ($replacements as $placeholder => $value) {
                    if (is_null($value)) {
                        $value = 'NULL';
                    } elseif (is_string($value)) {
                        $value = "'" . addslashes($value) . "'";
                    }
                    $debugQuery = str_replace($placeholder, $value, $debugQuery);
                }

                // Print the query
                echo "<pre>$debugQuery</pre>";

                if ($query->execute()) {
                    echo json_encode([
                        "status"  => "success",
                        "message" => "Book inserted successfully"
                    ]);
                } else {
                    $err = $query->errorInfo();
                    echo json_encode([
                        "status"  => "error",
                        "message" => $err[2] ?? "Unknown DB error"
                    ]);
                }
            } catch (Exception $e) {
                echo json_encode([
                    "status"  => "error",
                    "message" => $e->getMessage()
                ]);
            }

            // 👉 READ all books
        case 'viewById':
            $id = $_POST['BookId'] ?? '';
            $stmt = $dbh->query("SELECT * FROM tblbooks WHERE id = :id");
            $stmt->bindParam(':id', $id, PDO::PARAM_INT);
            $stmt->execute();
            $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
            if ($data) {
                echo json_encode([
                    "status" => "success",
                    "data"   => $data
                ]);
            } else {
                echo json_encode([
                    "status"  => "error",
                    "message" => "No books found"
                ]);
            }
            break;
        default:
            $stmt = $dbh->query("SELECT * FROM tblbooks ORDER BY id DESC");
            $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
            echo $data
                ? json_encode(["status" => "success", "data" => $data])
                : json_encode(["status" => "error", "message" => "No books found"]);
            break;

        // 👉 UPDATE book
        case 'update':
            $id = $_POST['id'] ?? '';
            if ($id === '') {
                echo json_encode(["status" => "error", "message" => "Missing id"]);
                break;
            }

            $updateFields = [
                'bookName',
                'categoryId',
                'authoresId',
                'isbnNo',
                'copices',
                'price',
                'purchaseDate',
                'rackId',
                'departmentId',
                'degreeId',
                'edition',
                'volume',
                'publisherId',
                'publicationYear',
                'cbrbNo',
                'accestionNo'
            ];

            $set = [];
            foreach ($updateFields as $f) {
                if (isset($_POST[$f])) {
                    $set[] = "$f = :$f";
                }
            }

            if (!$set) {
                echo json_encode(["status" => "error", "message" => "No data to update"]);
                break;
            }

            $sql = "UPDATE tblbooks SET " . implode(', ', $set) . " WHERE id = :id";
            $stmt = $dbh->prepare($sql);
            $stmt->bindValue(':id', $id, PDO::PARAM_INT);

            foreach ($updateFields as $f) {
                if (isset($_POST[$f])) {
                    $stmt->bindValue(':' . $f, $_POST[$f]);
                }
            }
            $stmt->execute();

            echo json_encode(["status" => "success", "message" => "Book updated"]);
            break;

        // 👉 DELETE book
        case 'delete':
            $id = $_POST['BookId'] ?? '';
            if ($id === '') {
                echo json_encode(["status" => "error", "message" => "Missing id"]);
                break;
            }
            $stmt = $dbh->prepare("DELETE FROM tblbooks WHERE id = :id");
            $stmt->bindParam(':id', $id, PDO::PARAM_INT);
            $stmt->execute();
            echo json_encode(["status" => "success", "message" => "Book deleted"]);
            break;
    }
} catch (Exception $e) {
    echo json_encode(["status" => "errowwr", "message" => $e->getMessage()]);
}
