<?php
session_start();
include('includes/config.php');
require_once('../includes/phpqrcode/qrlib.php'); // Include QR code library

// Check if admin is logged in
if (strlen($_SESSION['alogin']) == 0) {
    header('location:index.php');
    exit;
}

if (isset($_POST['add_copies'])) {

    $book_id = intval($_POST['book_id']);
    $copies = intval($_POST['copies']);

    if ($copies <= 0) {
        $_SESSION['error'] = "Invalid number of copies.";
        header("location:book-copies.php?bookid=$book_id");
        exit;
    }

    // Fetch book details
    $sql = "SELECT BookName, ISBNNumber, BookPrice, total_count, current_count 
            FROM tblbooks 
            WHERE id = :book_id";
    $query = $dbh->prepare($sql);
    $query->bindParam(':book_id', $book_id, PDO::PARAM_INT);
    $query->execute();
    $book = $query->fetch(PDO::FETCH_ASSOC);

    if (!$book) {
        $_SESSION['error'] = "Invalid book ID.";
        header("location:book-copies.php?bookid=$book_id");
        exit;
    }

    $book_price = floatval($book['BookPrice']);

    try {
        $dbh->beginTransaction();

        // Last copy number
        $sql = "SELECT book_no FROM tblbookcopies 
                WHERE book_id = :book_id 
                ORDER BY id DESC LIMIT 1";
        $query = $dbh->prepare($sql);
        $query->bindParam(':book_id', $book_id, PDO::PARAM_INT);
        $query->execute();
        $last_copy = $query->fetch(PDO::FETCH_ASSOC);

        $last_number = 0;
        if ($last_copy && preg_match('/(\d+)$/', $last_copy['book_no'], $matches)) {
            $last_number = intval($matches[1]);
        }

        // Prepare QR dir
        $qrDir = "../uploads/qrcodes/";
        if (!file_exists($qrDir)) {
            mkdir($qrDir, 0755, true);
        }

        // LOOP THROUGH EACH MODAL ROW
        for ($i = 0; $i < $copies; $i++) {

            // Get modal values
            $acc_no = $_POST['accession_no'][$i];
            $rack_id = $_POST['rack_id'][$i];
            $shift = $_POST['shift'][$i];

            // $cupboard = $_POST['rack_id'][$i] ?? null;
            // $shelf    = $_POST['shelf_no'][$i] ?? null;
            // $floor    = $_POST['floor'][$i] ?? null;

            $next_number = $last_number + ($i + 1);

            // Create book_no
            $book_no = "BOOK-" . str_pad($book_id, 5, "0", STR_PAD_LEFT)
                . "-" . str_pad($next_number, 3, "0", STR_PAD_LEFT);

            // QR generation
            $qrFileName = "bookcopy_" . $book_id . "_" . $next_number . ".png";
            $qrFullPath = $qrDir . $qrFileName;
            $qrRelativePath = "uploads/qrcodes/" . $qrFileName;

            $qrContent = "http://localhost/library_software/admin/view-bookcopy.php?bookcopy="
                . urlencode($book_no);

            QRcode::png($qrContent, $qrFullPath, QR_ECLEVEL_L, 4);

            // Insert new copy
            $sql = "INSERT INTO tblbookcopies 
                        (book_id, book_no, accession_no, rack_id, shift, book_status, QRCode)
                    VALUES 
                        (:book_id, :book_no, :acc_no, :rack_id, :shift, 'available', :qrcode)";

            $query = $dbh->prepare($sql);

            $query->execute([
                ':book_id' => $book_id,
                ':book_no' => $book_no,
                ':acc_no' => $acc_no,
                ':rack_id' => $rack_id,
                ':shift' => $shift,
                ':qrcode' => $qrRelativePath
            ]);
        }

        // Update book counts
        $additional_price = $copies * $book_price;
        $sql = "UPDATE tblbooks 
                SET total_price = total_price + :additional_price,
                    total_count = total_count + :copies,
                    current_count = current_count + :copies
                WHERE id = :book_id";
        $query = $dbh->prepare($sql);
        $query->bindParam(':additional_price', $additional_price, PDO::PARAM_STR);
        $query->bindParam(':copies', $copies, PDO::PARAM_INT);
        $query->bindParam(':book_id', $book_id, PDO::PARAM_INT);
        $query->execute();

        $dbh->commit();
        $_SESSION['msg'] = "Successfully added $copies copies.";

    } catch (Exception $e) {
        $dbh->rollBack();
        $_SESSION['error'] = "Error: " . $e->getMessage();
    }

    header("location:book-copies.php?bookid=$book_id");
    exit;
}
?>