<?php
// add_book.php
// Processing moved to top so header() can be sent before any output.

ini_set('display_errors', 1);
error_reporting(E_ALL);

// include DB connection (only once)
include 'include/dbcon.php';

// --- compute the next barcode (needed both for display and for inserts) ---
$pre_barcode = "VNHS";
$suf_barcode = "LMS";

$mid_barcode = 0;
$result = mysqli_query($con, "SELECT mid_barcode FROM barcode ORDER BY mid_barcode DESC LIMIT 1");
if ($result && $row = mysqli_fetch_assoc($result)) {
    $mid_barcode = (int)$row['mid_barcode'];
}
$new_mid = $mid_barcode + 1;
$generate_barcode = $pre_barcode . $new_mid . $suf_barcode;

// --- handle POST (form submission) ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit'])) {
    // Basic server-side validation + sanitization
    $book_title     = isset($_POST['book_title']) ? trim($_POST['book_title']) : '';
    $category_id    = isset($_POST['category_id']) ? (int)$_POST['category_id'] : 0;
    $author         = isset($_POST['author']) ? trim($_POST['author']) : '';
    $author_2       = isset($_POST['author_2']) ? trim($_POST['author_2']) : '';
    $author_3       = isset($_POST['author_3']) ? trim($_POST['author_3']) : '';
    $author_4       = isset($_POST['author_4']) ? trim($_POST['author_4']) : '';
    $author_5       = isset($_POST['author_5']) ? trim($_POST['author_5']) : '';
    $book_copies    = isset($_POST['book_copies']) ? (int)$_POST['book_copies'] : 0;
    $book_pub       = isset($_POST['book_pub']) ? trim($_POST['book_pub']) : '';
    $publisher_name = isset($_POST['publisher_name']) ? trim($_POST['publisher_name']) : '';
    $isbn           = isset($_POST['isbn']) ? trim($_POST['isbn']) : '';
    $copyright_year = isset($_POST['copyright_year']) ? trim($_POST['copyright_year']) : '';
    $status         = isset($_POST['status']) ? trim($_POST['status']) : '';
    // mid passed on form hidden input (fallback to computed $new_mid)
    $mid_from_form  = isset($_POST['new_barcode']) ? (int)$_POST['new_barcode'] : $new_mid;
    $mid_to_use     = $mid_from_form > 0 ? $mid_from_form : $new_mid;

    // Determine remarks based on status
    if ($status === 'Lost' || $status === 'Damaged') {
        $remark = 'Not Available';
    } else {
        $remark = 'Available';
    }

    // Handle image upload (optional)
    $upload_dir = __DIR__ . '/upload/'; // absolute path to upload folder
    if (!is_dir($upload_dir)) {
        mkdir($upload_dir, 0755, true);
    }

    $book_image = ''; // default empty
    if (isset($_FILES['image']) && isset($_FILES['image']['tmp_name']) && $_FILES['image']['tmp_name'] !== '') {
        $fileTmp  = $_FILES['image']['tmp_name'];
        $fileName = basename($_FILES['image']['name']);
        $fileSize = (int)$_FILES['image']['size'];
        $fileErr  = (int)$_FILES['image']['error'];

        // Basic validation
        $maxSize = 10 * 1024 * 1024; // 10 MB
        $allowed_ext = array('jpg','jpeg','png','gif','webp');

        // extension
        $ext = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
        if ($fileErr !== UPLOAD_ERR_OK) {
            // you can handle specific errors here
            die("Upload error (code: $fileErr).");
        }
        if ($fileSize > $maxSize) {
            die("File is too large. Max is 10MB.");
        }
        if (!in_array($ext, $allowed_ext)) {
            die("Invalid file type. Allowed: " . implode(', ', $allowed_ext));
        }

        // create a safe unique filename to avoid collisions
        $safeName = preg_replace('/[^A-Za-z0-9_\-\.]/', '_', pathinfo($fileName, PATHINFO_FILENAME));
        $uniqName = $safeName . '_' . time() . '.' . $ext;
        $destination = $upload_dir . $uniqName;

        if (!move_uploaded_file($fileTmp, $destination)) {
            die("Failed to move uploaded file.");
        }

        // store filename relative to script (as your app expects)
        $book_image = $uniqName;
    }

    // Compose generated barcode
    $pre = $pre_barcode;
    $mid = $mid_to_use;
    $suf = $suf_barcode;
    $gen = $pre . $mid . $suf;

    // Use transaction for both inserts (book and barcode)
    mysqli_begin_transaction($con);
    try {
        // Insert into `book` using prepared statement
        $stmt = mysqli_prepare($con, "INSERT INTO book (book_title, category_id, author, author_2, author_3, author_4, author_5, book_copies, book_pub, publisher_name, isbn, copyright_year, status, book_barcode, book_image, date_added, remarks) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), ?)");
        if ($stmt === false) {
            throw new Exception('Prepare failed (book insert): ' . mysqli_error($con));
        }

        // Correct type string with 16 characters (one per bound variable)
        $types = 'sisssssissssssss';
        mysqli_stmt_bind_param($stmt, $types,
            $book_title,
            $category_id,
            $author,
            $author_2,
            $author_3,
            $author_4,
            $author_5,
            $book_copies,
            $book_pub,
            $publisher_name,
            $isbn,
            $copyright_year,
            $status,
            $gen,
            $book_image,
            $remark
        );

        $exec = mysqli_stmt_execute($stmt);
        if ($exec === false) {
            throw new Exception('Execute failed (book insert): ' . mysqli_stmt_error($stmt));
        }
        mysqli_stmt_close($stmt);

        // Insert into `barcode`
        $stmt2 = mysqli_prepare($con, "INSERT INTO barcode (pre_barcode, mid_barcode, suf_barcode) VALUES (?, ?, ?)");
        if ($stmt2 === false) {
            throw new Exception('Prepare failed (barcode insert): ' . mysqli_error($con));
        }
        mysqli_stmt_bind_param($stmt2, 'sis', $pre, $mid, $suf);
        $exec2 = mysqli_stmt_execute($stmt2);
        if ($exec2 === false) {
            throw new Exception('Execute failed (barcode insert): ' . mysqli_stmt_error($stmt2));
        }
        mysqli_stmt_close($stmt2);

        // commit
        mysqli_commit($con);

        // redirect to view barcode page
        header('Location: view_barcode.php?code=' . urlencode($gen));
        exit;

    } catch (Exception $e) {
        mysqli_rollback($con);
        // For production, log the error and show user-friendly message
        // For now, show the error (helpful for debugging)
        die('Error saving book: ' . $e->getMessage());
    }
}

// If not redirected, the script will continue and render the form HTML below.
// Important: no output was sent before potential header() call above.
?>

<?php include ('header.php'); ?>

        <div class="page-title">
            <div class="title_left">
                <h3>
                    <small>Home / Books /</small> Add Book
                </h3>
            </div>
        </div>
        <div class="clearfix"></div>
 
        <div class="row">
            <div class="col-md-12 col-sm-12 col-xs-12">
                <div class="x_panel">
                    <div class="x_title">
                        <h2><i class="fa fa-plus"></i> Add Book</h2>
                        <ul class="nav navbar-right panel_toolbox">
                            <li><a class="collapse-link"><i class="fa fa-chevron-up"></i></a></li>
                            <li><a class="close-link"><i class="fa fa-close"></i></a></li>
                        </ul>
                        <div class="clearfix"></div>
                    </div>
                    <div class="x_content">
                        <!-- content starts here -->

                            <form method="post" enctype="multipart/form-data" class="form-horizontal form-label-left">
                            <!-- pass the mid barcode so processing uses the same mid we showed on the form -->
                            <input type="hidden" name="new_barcode" value="<?php echo htmlspecialchars($new_mid); ?>">

                                <div class="form-group">
                                    <label class="control-label col-md-4" for="first-name">Title <span class="required" style="color:red;">*</span>
                                    </label>
                                    <div class="col-md-4">
                                        <input type="text" name="book_title" id="first-name2" required="required" class="form-control col-md-7 col-xs-12">
                                    </div>
                                </div>

                                <div class="form-group">
                                    <label class="control-label col-md-4" for="first-name">Author 1 <span class="required" style="color:red;">*</span>
                                    </label>
                                    <div class="col-md-4">
                                        <input type="text" name="author" id="first-name2" required="required" class="form-control col-md-7 col-xs-12">
                                    </div>
                                </div>

                                <div class="form-group">
                                    <label class="control-label col-md-4" for="first-name">Author 2
                                    </label>
                                    <div class="col-md-4">
                                        <input type="text" name="author_2" id="first-name2" class="form-control col-md-7 col-xs-12">
                                    </div>
                                </div>

                                <div class="form-group">
                                    <label class="control-label col-md-4" for="first-name">Author 3
                                    </label>
                                    <div class="col-md-4">
                                        <input type="text" name="author_3" id="first-name2" class="form-control col-md-7 col-xs-12">
                                    </div>
                                </div>

                                <div class="form-group">
                                    <label class="control-label col-md-4" for="first-name">Author 4
                                    </label>
                                    <div class="col-md-4">
                                        <input type="text" name="author_4" id="first-name2" class="form-control col-md-7 col-xs-12">
                                    </div>
                                </div>

                                <div class="form-group">
                                    <label class="control-label col-md-4" for="first-name">Author 5
                                    </label>
                                    <div class="col-md-4">
                                        <input type="text" name="author_5" id="first-name2" class="form-control col-md-7 col-xs-12">
                                    </div>
                                </div>

                                <div class="form-group">
                                    <label class="control-label col-md-4" for="last-name">Publication
                                    </label>
                                    <div class="col-md-4">
                                        <input type="text" name="book_pub" id="last-name2" class="form-control col-md-7 col-xs-12">
                                    </div>
                                </div>

                                <div class="form-group">
                                    <label class="control-label col-md-4" for="last-name">Publisher
                                    </label>
                                    <div class="col-md-4">
                                        <input type="text" name="publisher_name" id="last-name2" class="form-control col-md-7 col-xs-12">
                                    </div>
                                </div>

                                <div class="form-group">
                                    <label class="control-label col-md-4" for="last-name">ISBN <span class="required" style="color:red;">*</span>
                                    </label>
                                    <div class="col-md-4">
                                        <input type="text" name="isbn" id="last-name2" class="form-control col-md-7 col-xs-12" required="required">
                                    </div>
                                </div>

                                <div class="form-group">
                                    <label class="control-label col-md-4" for="last-name">Copyright
                                    </label>
                                    <div class="col-md-4">
                                        <input type="text" name="copyright_year" id="last-name2" class="form-control col-md-7 col-xs-12">
                                    </div>
                                </div>

                                <div class="form-group">
                                    <label class="control-label col-md-4" for="last-name">Copies <span class="required" style="color:red;">*</span>
                                    </label>
                                    <div class="col-md-1">
                                        <input type="number" name="book_copies" step="1" min="0" max="1000" required="required"  class="form-control col-md-7 col-xs-12">
                                    </div>
                                </div>

                                <div class="form-group">
                                    <label class="control-label col-md-4" for="last-name">Status <span class="required" style="color:red;">*</span>
                                    </label>
                                    <div class="col-md-4">
                                        <select name="status" class="select2_single form-control" tabindex="-1" required="required">
                                            <option value="New">New</option>
                                            <option value="Old">Old</option>
                                            <option value="Lost">Lost</option>
                                            <option value="Damaged">Damaged</option>
                                            <option value="Replacement">Replacement</option>
                                            <option value="Hardbound">Hardbound</option>
                                        </select>
                                    </div>
                                </div>

                                <div class="form-group">
                                    <label class="control-label col-md-4" for="last-name">Category <span class="required" style="color:red;">*</span>
                                    </label>
                                    <div class="col-md-4">
                                        <select name="category_id" class="select2_single form-control" tabindex="-1" required="required">
                                        <?php
                                        $result = mysqli_query($con,"SELECT * FROM category");
                                        while ($row = mysqli_fetch_array($result)) {
                                            echo '<option value="' . htmlspecialchars($row['category_id']) . '">' . htmlspecialchars($row['classname']) . '</option>';
                                        }
                                        ?>
                                        </select>
                                    </div>
                                </div>

                                <div class="form-group">
                                    <label class="control-label col-md-4" for="last-name">Book Image
                                    </label>
                                    <div class="col-md-4">
                                        <input type="file" style="height:44px;" name="image" id="last-name2" class="form-control col-md-7 col-xs-12">
                                    </div>
                                </div>

                                <div class="ln_solid"></div>
                                <div class="form-group">
                                    <div class="col-md-9 col-sm-9 col-xs-12 col-md-offset-3">
                                        <a href="book.php"><button type="button" class="btn btn-primary"><i class="fa fa-times-circle-o"></i> Cancel</button></a>
                                        <button type="submit" name="submit" class="btn btn-success"><i class="fa fa-plus-square"></i> Submit</button>
                                    </div>
                                </div>
                            </form>

                        <!-- content ends here -->
                    </div>
                </div>
            </div>
        </div>

<?php include ('footer.php'); ?>
