<?php
session_start();
error_reporting(0);
include('includes/config.php');

if (strlen($_SESSION['alogin']) == 0) {
  header('location:index.php');
  exit;
}

$bookid = isset($_GET['bookid']) ? (int) $_GET['bookid'] : 0;
if ($bookid <= 0) {
  die('Invalid book id');
}

// Fetch book
$sqlB = "SELECT id, BookName, ISBNNumber, BookPrice, total_price FROM tblbooks WHERE id = :id";
$qB = $dbh->prepare($sqlB);
$qB->bindParam(':id', $bookid, PDO::PARAM_INT);
$qB->execute();
$book = $qB->fetch(PDO::FETCH_ASSOC);
if (!$book) {
  die('Book not found');
}

// Fetch copies
$sqlC = "SELECT bc.id, bc.book_no, bc.accession_no, bc.cbrb_no, bc.shift,
                bc.book_status, bc.QRCode,
                r.rack_no, r.shelf_no, r.floor
         FROM tblbookcopies bc
         LEFT JOIN tbl_racks r ON r.id = bc.rack_id
         WHERE bc.book_id = :bid 
         ORDER BY bc.id ASC";

$qC = $dbh->prepare($sqlC);
$qC->bindParam(':bid', $bookid, PDO::PARAM_INT);
$qC->execute();
$copies = $qC->fetchAll(PDO::FETCH_ASSOC);
?>

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <title>Book Copies | <?= htmlentities($book['BookName']) ?></title>
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <link rel="icon" type="image/x-icon" href="../<?php echo $_SESSION['logo']; ?>">

  <!-- Bootstrap -->
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css" rel="stylesheet">

  <!-- FontAwesome -->
  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">

  <!-- DataTables -->
  <link href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap4.min.css" rel="stylesheet">

  <style>
    .square-card {
      width: 100%;
      background-color: #f8f9fa;
      border: 1px solid #dee2e6;
      box-shadow: 0 4px 8px rgba(0, 0, 0, 0.05);
      border-radius: 5px;
    }

    .flash-message {
      max-width: 600px;
      margin: 0 auto 15px;
    }

    .table-wrapper {
      overflow-x: auto;
      padding: 10px;
    }

    .col-md-12 h5 {
      color: #0d6efd;
      font-size: 20px;
    }

    .dataTables_filter {
      float: right;
      margin-bottom: 10px;
    }

    .dataTables_filter input {
      height: 32px;
      font-size: 0.95rem;
      padding: 4px 8px;
    }

    div.dataTables_filter label {
      color: #000 !important;
      font-weight: bold;
    }

    div.dataTables_filter label i {
      color: #000 !important;
    }
  </style>
</head>

<body>

  <div class="d-flex flex-column min-vh-100">
    <?php include('includes/header.php'); ?>

    <div class="main-content flex-grow-1">
      <div class="row pad-botm mb-4">
        <div class="col-md-12">
          <h5 class="header-line">
            COPIES OF: <?= htmlentities($book['BookName']) ?> (ISBN: <?= htmlentities($book['ISBNNumber']) ?>)
          </h5>
        </div>
      </div>

      <!-- Flash Messages -->
      <div class="row justify-content-center">
        <div class="col-md-8">
          <?php foreach (['error', 'msg', 'updatemsg', 'delmsg'] as $type): ?>
            <?php if (!empty($_SESSION[$type])): ?>
              <div class="alert alert-<?php echo ($type == 'error') ? 'danger' : 'success'; ?> flash-message">
                <strong><?php echo ucfirst($type); ?> :</strong> <?php echo htmlentities($_SESSION[$type]); ?>
                <?php $_SESSION[$type] = ""; ?>
              </div>
            <?php endif; ?>
          <?php endforeach; ?>
        </div>
      </div>

      <!-- Copies Table -->
      <div class="card square-card mb-5">
        <div class="card-header bg-secondary text-white d-flex justify-content-between align-items-center">
          <span><i class="fa fa-layer-group mr-2"></i> Copies List</span>
          <div>
            <button class="btn btn-success btn-sm" data-toggle="modal" data-target="#addCopiesModal">
              <i class="fa fa-plus"></i> Add Copies
            </button>
            <a href="manage-books.php" class="btn btn-light btn-sm">
              <i class="fa fa-arrow-left"></i> Back
            </a>
          </div>
        </div>
        <div class="card-body table-wrapper">
          <table id="copiesTable" class="table table-bordered table-hover table-sm text-dark">
            <thead class="table-theme-header">
              <tr>
                <th>#</th>
                <th>Book No</th>
                <th>Accession No</th>
                <th>Cupboard</th>
                <th>Shift</th>
                <th>Status</th>
                <th>Actions</th>
              </tr>
            </thead>
            <tbody>
              <?php if ($copies):
                $i = 1;
                foreach ($copies as $c): ?>
                  <tr>
                    <td><?= $i++ ?></td>
                    <td><?= htmlentities($c['book_no']) ?></td>
                    <td><?= htmlentities($c['accession_no']) ?></td>
                    <td>
                      Cupboard: <?= htmlentities($c['rack_no'] ?? '-') ?><br>
                      Shelf: <?= htmlentities($c['shelf_no'] ?? '-') ?><br>
                      Book: <?= htmlentities($c['floor'] ?? '-') ?>
                    </td>
                    <td><?= htmlentities($c['shift'] == 1 ? 'I' : 'II') ?></td>
                    <td>
                      <span class="badge badge-<?=
                        $c['book_status'] == 'available' ? 'success' :
                        ($c['book_status'] == 'issued' ? 'warning' :
                          ($c['book_status'] == 'damaged' ? 'danger' :
                            ($c['book_status'] == 'lost' ? 'secondary' : 'dark'))) ?>">
                        <?= ucfirst($c['book_status']) ?>
                      </span>
                    </td>
                    <td>
                      <!-- <a class="btn btn-sm btn-success mb-1" href="copy-view.php?id=<?= (int) $c['id'] ?>">
                        <i class="fa fa-eye"></i> View
                      </a> -->
                      <?php if ($c['book_status'] == 'issued') { ?>
                      <?php } else { ?>
                        <a class="btn btn-sm btn-primary mb-1" href="copy-edit.php?id=<?= (int) $c['id'] ?>">
                          <i class="fa fa-edit"></i> Edit
                        </a>
                      <?php } ?>
                      <!-- <a class="btn btn-sm btn-danger mb-1"
                        href="copy-delete.php?id=<?= (int) $c['id'] ?>&bookid=<?= (int) $bookid ?>"
                        onclick="return confirm('Delete this copy?');">
                        <i class="fa fa-trash"></i> Delete
                      </a> -->
                      <?php if (!empty($c['QRCode'])): ?>
                        <button class="btn btn-sm btn-info mb-1" onclick="openPrintModal(<?= (int) $c['id'] ?>)">
                          <i class="fa fa-qrcode"></i> Print QR
                        </button>
                      <?php endif; ?>

                    </td>
                  </tr>
                <?php endforeach; else: ?>
                <tr>
                  <td colspan="4" class="text-center text-muted">No copies found</td>
                </tr>
              <?php endif; ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>

  <!-- Add Copies Modal -->
  <div class="modal fade" id="addCopiesModal" tabindex="-1" role="dialog" aria-labelledby="addCopiesLabel"
    aria-hidden="true">
    <div class="modal-dialog" role="document">
      <form method="POST" action="add-copies.php" id="addCopiesForm">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title" id="addCopiesLabel">Add Copies</h5>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
              <span aria-hidden="true">&times;</span>
            </button>
          </div>

          <div class="modal-body">
            <input type="hidden" name="book_id" value="<?= $bookid ?>">

            <div class="form-group">
              <label>Price per Copy</label>
              <input type="number" id="pricePerCopy" class="form-control"
                value="<?= htmlentities($book['BookPrice']) ?>" readonly>
            </div>

            <div class="form-group">
              <label>Number of Copies</label>
              <input type="number" id="numCopies" class="form-control" name="copies" min="1" required>
            </div>

            <div id="dynamicFields"></div>


            <div class="form-group">
              <label>Total Price</label>
              <input type="number" id="totalPrice" class="form-control" readonly>
            </div>
          </div>

          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
            <button type="submit" name="add_copies" class="btn btn-primary">Add Copies</button>
          </div>
        </div>
      </form>
    </div>
  </div>




  <div class="modal fade" id="printPositionModal" tabindex="-1" role="dialog" aria-labelledby="printPositionLabel"
    aria-hidden="true">
    <div class="modal-dialog" role="document">
      <form method="GET" action="print-qrcode.php">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title">Select Label Position</h5>
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
              <span>&times;</span>
            </button>
          </div>
          <div class="modal-body">
            <input type="hidden" name="id" id="printCopyId">

            <div class="form-group">
              <label>Row (1–8)</label>
              <input type="number" class="form-control" name="row" min="1" max="8" maxlength="1" oninput="if(this.value.length>1) this.value=this.value.slice(0,1); 
                  if(this.value>8) this.value=8; 
                  if(this.value<1 && this.value!='') this.value=1;" required>
            </div>

            <div class="form-group">
              <label>Column (1–3)</label>
              <input type="number" class="form-control" name="col" min="1" max="3" maxlength="1" oninput="if(this.value.length>1) this.value=this.value.slice(0,1); 
                  if(this.value>3) this.value=3; 
                  if(this.value<1 && this.value!='') this.value=1;" required>
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
            <button type="submit" class="btn btn-primary">Print</button>
          </div>
        </div>
      </form>
    </div>
  </div>


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

  <!-- jQuery -->
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

  <!-- Bootstrap JS -->
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js"></script>

  <!-- DataTables -->
  <script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
  <script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap4.min.js"></script>

  <script>
    $(document).ready(function () {
      $('#copiesTable').DataTable({
        pageLength: 10,
        ordering: true,
        responsive: true,
        language: { search: "🔍 Search copies:" }
      });
    });

    document.getElementById("numCopies").addEventListener("input", function () {
      let price = parseFloat(document.getElementById("pricePerCopy").value) || 0;
      let copies = parseInt(this.value) || 0;
      document.getElementById("totalPrice").value = (price * copies).toFixed(2);
    });

    function openPrintModal(copyId) {
      document.getElementById("printCopyId").value = copyId;
      $("#printPositionModal").modal("show");
    }
    $("#numCopies").on("input", function () {
      let count = parseInt($(this).val()) || 0;
      let container = $("#dynamicFields");
      container.html("");

      for (let i = 1; i <= count; i++) {

        let block = `
        <div class="border rounded p-3 mb-3 copy-block">
          <h6>Copy ${i}</h6>

          <div class="form-group">
            <label>Accession No</label>
            <input type="text" name="accession_no[]" class="form-control accession-input" required>
            <small class="text-danger acc-error d-none">Accession already exists!</small>
          </div>

          <div class="form-group">
            <label>Cupboard Info</label>
            <select name="rack_id[]" class="form-control rack-select" required>
              <option value="">-- Select Cupboard --</option>
              <?php
              $racks = $dbh->query("SELECT r.* 
                                        FROM tbl_racks r 
                                        LEFT JOIN tblbookcopies b ON r.id = b.rack_id 
                                        WHERE b.rack_id IS NULL 
                                        ORDER BY r.id ASC")
                ->fetchAll(PDO::FETCH_ASSOC);
              foreach ($racks as $r) {
                echo "<option value='{$r['id']}'>Cupboard {$r['rack_no']} - Shelf {$r['shelf_no']} - Book {$r['floor']}</option>";
              }
              ?>
            </select>
            <small class="text-danger rack-error d-none">This rack is already selected!</small>
          </div>

          <div class="form-group">
            <label>Shift</label>
            <select name="shift[]" class="form-control" required>
              <option value="1">I</option>
              <option value="2">II</option>
            </select>
          </div>

        </div>
        `;

        container.append(block);
      }
    });


    // -------------------------
    // ACC No Unique Check (AJAX) — FIXED FOR JSON
    // -------------------------
    $(document).on("blur", ".accession-input", function () {
      let input = $(this);
      let accNo = input.val().trim();

      if (accNo === "") return;

      $.ajax({
        url: "accession.php",
        type: "POST",
        data: { accession_no: accNo },
        dataType: "json",  // IMPORTANT
        success: function (response) {

          if (response.exists === true) {
            input.addClass("is-invalid");
            input.siblings(".acc-error").removeClass("d-none");
          } else {
            input.removeClass("is-invalid");
            input.siblings(".acc-error").addClass("d-none");
          }
        }
      });
    });



    // -------------------------
    // RACK UNIQUE CHECK (inside modal only)
    // -------------------------
    $(document).on("change", ".rack-select", function () {
      let selectedRack = $(this).val();
      let current = $(this);

      let duplicate = false;

      $(".rack-select").not(current).each(function () {
        if ($(this).val() === selectedRack && selectedRack !== "") {
          duplicate = true;
        }
      });

      if (duplicate) {
        current.addClass("is-invalid");
        current.siblings(".rack-error").removeClass("d-none");
        current.val("");       // RESET selection
      } else {
        current.removeClass("is-invalid");
        current.siblings(".rack-error").addClass("d-none");
      }
    });


    // -------------------------
    // Prevent form submit if errors exist
    // -------------------------
    $("#addCopiesForm").on("submit", function (e) {
      let stop = false;

      $(".is-invalid").each(function () {
        stop = true;
      });

      if (stop) {
        alert("Please fix all errors before submitting!");
        e.preventDefault();
      }
    });
// 🔸 Check Accession No (AJAX + prevents duplicate message)
$(document).on("blur", ".accession-input", function () {
    let currentInput = $(this);
    let currentValue = currentInput.val().trim();

    // Remove old warning messages
    currentInput.siblings(".acc-error").addClass("d-none");
    currentInput.removeClass("is-invalid");

    if (currentValue === "") return;

    // AJAX call
    $.ajax({
        url: "check_accession.php",
        type: "POST",
        dataType: "json",
        data: { accession_no: currentValue },
        success: function (response) {

            if (response.exists === true) {
                currentInput.addClass('is-invalid');
                currentInput.siblings(".acc-error").removeClass("d-none");
            } else {
                currentInput.removeClass('is-invalid');
                currentInput.siblings(".acc-error").addClass("d-none");
            }
        }
    });
});

  </script>

</body>

</html>