<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);
include('includes/config.php');

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

if (isset($_POST['add'])) {
  $bookname = $_POST['bookname'];
  $category = $_POST['category'];
  $authors = isset($_POST['authors']) ? $_POST['authors'] : [];
  $authorIds = implode(',', $authors);
  $edition = $_POST['edition'] ?? null;
  $volume = $_POST['volume'] ?? null;
  $publisher = !empty($_POST['publisher']) ? $_POST['publisher'] : null;
  $publication_year = !empty($_POST['publication_year']) ? $_POST['publication_year'] : null;
  // $cbrbNumbers = $_POST['cbrb_no'] ?? null;
  $accessionNumbers = $_POST['accession_no']; // array
  $isbn = $_POST['isbn'];
  $price = $_POST['price'];
  $purchase_date = $_POST['purchase_date'];
  $rack_ids = $_POST['rack_id']; // array
  $total_count = $_POST['total_count'];

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

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

  $sql = "INSERT INTO tblbooks(
                BookName, CatId, AuthorIds, Edition, Volume, Publisher, PublicationYear, 
                ISBNNumber, BookPrice, total_price, PurchaseDate, 
                total_count, current_count, department_id, degree_id, Status
            ) VALUES(
                :bookname, :category, :authorIds, :edition, :volume, :publisher, :publication_year, 
                :isbn, :price, :total_price, :purchase_date, 
                :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(':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(':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);
  $query->execute();

  $lastInsertId = $dbh->lastInsertId();

  if ($lastInsertId) {
    require_once('../includes/phpqrcode/qrlib.php');
    $qrDir = '../uploads/qrcodes/';
    if (!file_exists($qrDir)) {
      mkdir($qrDir, 0755, true);
    }

    // Generate book copies with individual QR codes
    for ($i = 1; $i <= $total_count; $i++) {

      $acc_no_single = $accessionNumbers[$i - 1]; // pick correct accession number
      // $cbrb_no_single = $cbrbNumbers[$i - 1]; // pick correct cbrb number
      $rack_id_single = $rack_ids[$i - 1];
      $shift_single = $_POST['shift'][$i - 1];


      $book_no = "BOOK-" . str_pad($lastInsertId, 5, "0", STR_PAD_LEFT) . "-" . str_pad($i, 3, "0", STR_PAD_LEFT);

      $qrFileName = 'bookcopy_' . $lastInsertId . '_' . $i . '.png';
      $qrFullPath = $qrDir . $qrFileName;
      $qrRelativePath = 'uploads/qrcodes/' . $qrFileName;

      $copyUrl = "http://localhost/library_software/admin/view-bookcopy.php?bookcopy=" . urlencode($book_no);
      QRcode::png($copyUrl, $qrFullPath, QR_ECLEVEL_L, 4);

      $sqlCopy = "INSERT INTO tblbookcopies 
(book_id, accession_no, book_no, rack_id, shift, book_status, QRCode) 
VALUES 
(:book_id, :acc_no_single, :book_no, :rack_id, :shift, 1, :qrcode)";


      $queryCopy = $dbh->prepare($sqlCopy);
      $queryCopy->bindParam(':book_id', $lastInsertId, PDO::PARAM_INT);
      $queryCopy->bindParam(':acc_no_single', $acc_no_single, PDO::PARAM_STR);
      // $queryCopy->bindParam(':cbrb_no_single', $cbrb_no_single, PDO::PARAM_STR);
      $queryCopy->bindParam(':book_no', $book_no, PDO::PARAM_STR);
      $queryCopy->bindParam(':qrcode', $qrRelativePath, PDO::PARAM_STR);
      $queryCopy->bindParam(':rack_id', $rack_id_single, PDO::PARAM_INT);
      $queryCopy->bindParam(':shift', $shift_single, PDO::PARAM_INT);


      $queryCopy->execute();
    }


    $_SESSION['last_book_copies'] = $total_count;
    $_SESSION['last_book_id'] = $lastInsertId;

    header('location:add-book-success.php');
    exit;
  }
}
?>

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

<head>
  <meta charset="UTF-8">
  <title>Add Book | Library System</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="../<?php echo $_SESSION['logo']; ?>">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css" rel="stylesheet">
  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
  <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
</head>
<style>
  .add-author-btn:hover {
    background-color: #28a745 !important;
    transform: scale(1.1);
    box-shadow: 0px 4px 8px rgba(0, 128, 0, 0.3);
  }

  .remove-author-btn:hover {
    background-color: #dc3545 !important;
    transform: scale(1.1);
    box-shadow: 0px 4px 8px rgba(255, 0, 0, 0.3);
  }

  .is-invalid {
    border: 1px solid red !important;
    background-color: #ffe6e6 !important;
  }
</style>

<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 mb-4">
        <div class="col-md-12">
          <h5 class="header-line" style="font-size:20px; color:#0d6efd;"><i class="fas fa-book-medical mr-2"></i>Add
            Book</h5>
        </div>
      </div>

      <div class="row justify-content-center">
        <div class="col-lg-6 col-md-8 col-sm-10 mx-auto">
          <div class="card square-card">
            <div class="card-header bg-secondary text-white d-flex justify-content-between align-items-center">
              <div>
                <i class="fas fa-info-circle mr-2"></i> Book Information
              </div>
              <a href="manage-books.php" class="btn btn-light btn-sm">
                <i class="fa fa-arrow-left"></i> Back
              </a>
            </div>

            <div class="card-body">
              <form method="post">
                <div class="form-group">
                  <label class="form-label">Book Name<span class="text-danger">*</span></label>
                  <input type="text" name="bookname" class="form-control" required autocomplete="off">
                </div>

                <div class="form-group">
                  <label class="form-label">Category</label>
                  <select name="category" id="category" class="form-control select2">
                    <option value="">Select Category</option>
                    <?php
                    $sql = "SELECT * FROM tblcategory WHERE Status=1 AND is_deleted=0";
                    $query = $dbh->prepare($sql);
                    $query->execute();
                    $results = $query->fetchAll(PDO::FETCH_OBJ);
                    foreach ($results as $result) {
                      echo '<option value="' . htmlentities($result->id) . '">' . htmlentities($result->CategoryName . " | " . $result->CategoryCode) . '</option>';
                    }
                    ?>
                  </select>
                </div>

                <!-- Dynamic Authors -->
                <div class="form-group">
                  <label class="form-label">Authors<span class="text-danger">*</span></label>
                  <div id="authorFields">
                    <div class="input-group mb-2">
                      <select name="authors[]" class="form-control select2 author-select" required>
                        <option value="">Select Author</option>
                        <?php
                        $sql = "SELECT * FROM tblauthors WHERE is_deleted=0";
                        $query = $dbh->prepare($sql);
                        $query->execute();
                        $authors = $query->fetchAll(PDO::FETCH_OBJ);
                        foreach ($authors as $result) {
                          echo '<option value="' . htmlentities($result->id) . '">' . htmlentities($result->AuthorName . " | " . $result->AuthorID) . '</option>';
                        }
                        ?>
                      </select>
                      <!-- <div class="input-group-append">
                      <button type="button" class="btn btn-success add-author-btn">+</button>
                    </div> -->

                      <div class="input-group-append">
                        <button type="button" class="btn btn-success add-author-btn shadow-sm rounded-circle"
                          style="padding: 3px 8px; font-size: 18px; transition: 0.3s; margin-top: 2px;">
                          <i class="fas fa-plus"></i>
                        </button>
                      </div>



                    </div>
                  </div>
                </div>

                <div class="form-group">
                  <label class="form-label">ISBN Number</label>
                  <input type="text" name="isbn" id="isbn" class="form-control" autocomplete="off">
                  <small class="form-text text-muted">ISBN must be unique</small>
                  <span id="isbn-status"></span>
                </div>

                <div class="form-group">
                  <label class="form-label">Number of Copies<span class="text-danger">*</span></label>
                  <input type="number" name="total_count" class="form-control" min="1" value="1" required>
                </div>

                <div class="form-group">
                  <label class="form-label">Per Book Price</label>
                  <input type="text" name="price" class="form-control">
                </div>

                <div class="form-group">
                  <label class="form-label">Purchase Date</label>
                  <input type="date" name="purchase_date" class="form-control">
                </div>

                <div class="form-group">
                  <label class="form-label">Cupboard Info (Cupboard | Shelf | Book No)</label>
                  <div id="rackSelectContainer">
                    <select name="rack_id[]" class="form-control select2 mb-2" required>
                      <option value="">Select cupboard</option>
                      <?php
                      $sql = "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";
                      $query = $dbh->prepare($sql);
                      $query->execute();
                      $results = $query->fetchAll(PDO::FETCH_OBJ);

                      foreach ($results as $rack) {
                        echo '<option value="' . htmlentities($rack->id) . '">' .
                          htmlentities($rack->rack_no . " | " . $rack->shelf_no . " | " . $rack->floor) .
                          '</option>';
                      }
                      ?>
                    </select>
                  </div>
                </div>
                <div class="form-group">
                  <label class="form-label">Shift</label>
                  <div id="shiftContainer">
                    <select name="shift[]" class="form-control mb-2" required>
                      <option value="">Select Shift</option>
                      <option value="1">I</option>
                      <option value="2">II</option>
                    </select>
                  </div>
                </div>
                <div class="form-group">
                  <label class="form-label">Department</label>
                  <select name="department_id" class="form-control select2">
                    <option value="">Select Department</option>
                    <?php
                    $sql = "SELECT department_id, department_name, department_code FROM tbldepartment WHERE is_deleted=0";
                    $query = $dbh->prepare($sql);
                    $query->execute();
                    $departments = $query->fetchAll(PDO::FETCH_OBJ);
                    foreach ($departments as $dept) {
                      echo '<option value="' . htmlentities($dept->department_id) . '">' . htmlentities($dept->department_name . " | " . $dept->department_code) . '</option>';
                    }
                    ?>
                  </select>
                </div>

                <div class="form-group">
                  <label class="form-label">Degree</label>
                  <select name="degree_id" class="form-control select2">
                    <option value="">Select Degree</option>
                    <?php
                    $sql = "SELECT degree_id, degree_name FROM tbldegree WHERE is_deleted=0";
                    $query = $dbh->prepare($sql);
                    $query->execute();
                    $degrees = $query->fetchAll(PDO::FETCH_OBJ);
                    foreach ($degrees as $deg) {
                      echo '<option value="' . htmlentities($deg->degree_id) . '">' . htmlentities($deg->degree_name) . '</option>';
                    }
                    ?>
                  </select>
                </div>

                <div class="form-group">
                  <label class="form-label">Edition</label>
                  <select name="edition" class="form-control select2">
                    <option value="">Select Edition</option>
                    <?php
                    for ($i = 1; $i <= 50; $i++) {
                      echo "<option value='{$i}'>" . ordinal($i) . " Edition</option>";
                    }
                    function ordinal($number)
                    {
                      $ends = ['th', 'st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th'];
                      if ((($number % 100) >= 11) && (($number % 100) <= 13))
                        return $number . 'th';
                      else
                        return $number . $ends[$number % 10];
                    }
                    ?>
                  </select>
                </div>

                <div class="form-group">
                  <label class="form-label">Volume</label>
                  <select name="volume" class="form-control select2">
                    <option value="">Select Volume</option>
                    <?php
                    for ($i = 1; $i <= 50; $i++) {
                      echo "<option value='Vol {$i}'>Vol {$i}</option>";
                    }
                    ?>
                  </select>
                </div>

                <div class="form-group">
                  <label class="form-label">Publisher</label>
                  <select name="publisher" class="form-control select2">
                    <option value="">Select Publisher</option>
                    <?php
                    $sql = "SELECT id, PublisherName, RniNumber FROM tblpublishers WHERE is_deleted=0";
                    $query = $dbh->prepare($sql);
                    $query->execute();
                    $publishers = $query->fetchAll(PDO::FETCH_OBJ);
                    foreach ($publishers as $p) {
                      echo '<option value="' . htmlentities($p->id) . '">' . htmlentities($p->PublisherName . " | " . $p->RniNumber) . '</option>';
                    }
                    ?>
                  </select>
                </div>

                <div class="form-group">
                  <label class="form-label">Publication Year</label>
                  <select name="publication_year" class="form-control select2">
                    <?php
                    $currentYear = date("Y");
                    for ($y = $currentYear; $y >= 1900; $y--) {
                      echo "<option value='{$y}'>{$y}</option>";
                    }
                    ?>
                  </select>
                </div>
                <!-- <div class="form-group">
                  <label class="form-label">C.B,R,B.NO</label>
                  <div id="cbrbContainer">
                    <input type="text" name="cbrb_no[]" class="form-control mb-2" placeholder="Enter C.B,R,B.NO">
                  </div>
                </div> -->
                <div class="form-group">
                  <label class="form-label">Accession Numbers</label>
                  <div id="accessionContainer">
                    <input type="text" name="accession_no[]" class="form-control mb-2" placeholder="Enter Accession No">
                  </div>
                </div>


                <div class="d-flex justify-content-between">
                  <button type="submit" name="add" class="btn btn-primary">
                    <i class="fas fa-plus"></i> Add Book
                  </button>
                </div>
              </form>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

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

  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js"></script>

  <script>
    $(document).ready(function () {
      // Initialize select2 for all dropdowns
      $('.select2').select2({ width: '100%' });

      // Function to update available authors in dropdowns to prevent duplicates
      function updateAuthorOptions() {
        // Get all selected author IDs
        let selectedAuthors = [];
        $('.author-select').each(function () {
          let val = $(this).val();
          if (val) selectedAuthors.push(val);
        });

        // Disable already selected authors in other dropdowns
        $('.author-select').each(function () {
          let currentSelect = $(this);
          currentSelect.find('option').prop('disabled', false); // Enable all first
          selectedAuthors.forEach(function (authorId) {
            if (authorId !== currentSelect.val()) {
              currentSelect.find('option[value="' + authorId + '"]').prop('disabled', true);
            }
          });
        });

        // Refresh select2 dropdowns
        $('.author-select').select2({ width: '100%' });
      }

      // Add new author dropdown dynamically
      $(document).on('click', '.add-author-btn', function () {
        let newField = `
            <div class="input-group mb-2">
                <select name="authors[]" class="form-control select2 author-select" required>
                    <option value="">Select Author</option>
                    <?php foreach ($authors as $result) {
                      echo '<option value="' . htmlentities($result->id) . '">' . htmlentities($result->AuthorName . " | " . $result->AuthorID) . '</option>';
                    } ?>
                </select>
              <div class="input-group-append">
    <button type="button" class="btn btn-danger remove-author-btn shadow-sm rounded-circle"
        style="padding: 3px 8px; font-size: 18px;  margin-top: 2px;">
        <i class="fas fa-minus"></i>
    </button>
</div>
            </div>`;
        $('#authorFields').append(newField);

        // Initialize select2 on new dropdown
        $('.select2').select2({ width: '100%' });

        // Update available options to prevent duplicates
        updateAuthorOptions();
      });

      // Remove author field dynamically
      $(document).on('click', '.remove-author-btn', function () {
        $(this).closest('.input-group').remove();
        updateAuthorOptions();
      });

      // Whenever an author is selected/unselected, update available options
      $(document).on('change', '.author-select', function () {
        updateAuthorOptions();
      });
    });
    $('input[name="total_count"]').on('input', function () {
      let count = $(this).val();
      let container = $('#accessionContainer');
      let rackContainer = $('#rackSelectContainer');
      let shiftContainer = $('#shiftContainer');
      shiftContainer.empty();
      rackContainer.empty();
      container.empty();

      for (let i = 1; i <= count; i++) {
        container.append(`<input type="text" name="accession_no[]" class="form-control mb-2" placeholder="Accession No for Copy ${i}" required>`);
      }

      for (let i = 1; i <= count; i++) {
        rackContainer.append(`
            <select name="rack_id[]" class="form-control select2 mb-2" required>
                <option value="">Select cupboard for Copy ${i}</option>
                <?php
                foreach ($results as $rack) {
                  echo '<option value="' . htmlspecialchars($rack->id) . '">' .
                    htmlspecialchars($rack->rack_no . " | " . $rack->shelf_no . " | " . $rack->floor) .
                    '</option>';
                }
                ?>
            </select>
        `);
      }
      for (let i = 1; i <= count; i++) {
        shiftContainer.append(`
      <select name="shift[]" class="form-control mb-2" required>
          <option value="">Select Shift for Copy ${i}</option>
          <option value="1">I</option>
          <option value="2">II</option>
      </select>
  `);
      }
      $('.select2').select2({ width: '100%' });
    });

  </script>
  <script>
    $(document).ready(function () {
      // 🔹 Dynamic validation for Accession Numbers
      $(document).on('input', 'input[name="accession_no[]"]', function () {
        const currentInput = $(this);
        const currentValue = currentInput.val().trim();
        const allValues = [];

        $('input[name="accession_no[]"]').each(function () {
          const val = $(this).val().trim();
          if (val) allValues.push(val);
        });

        // Remove any existing warning
        currentInput.removeClass('is-invalid');
        currentInput.next('.text-danger').remove();

        // 🔸 Check duplicate in the form itself
        const duplicates = allValues.filter(v => v === currentValue).length;
        if (duplicates > 1) {
          currentInput.addClass('is-invalid');
          currentInput.after('<small class="text-danger">Duplicate accession number entered</small>');
          return;
        }

        // 🔸 Check from Database (AJAX)
        if (currentValue !== '') {
          $.ajax({
            url: 'check_accession.php',
            type: 'POST',
            dataType: 'json',
            data: { accession_no: currentValue },
            success: function (response) {
              if (response.exists) {
                currentInput.addClass('is-invalid');
                currentInput.after('<small class="text-danger">This accession number already exists</small>');
              }
            }
          });
        }
      });
      $('input[name="total_count"]').on('input', function () {
        let count = $(this).val();

        let container = $('#rackSelectContainer');
        container.empty();

        for (let i = 1; i <= count; i++) {
          container.append(`
            <select name="rack_id[]" class="form-control select2 mb-2" required>
                <option value="">Select cupboard for Copy ${i}</option>
                <?php
                foreach ($results as $rack) {
                  echo '<option value="' . htmlentities($rack->id) . '">' .
                    htmlentities($rack->rack_no . " | " . $rack->shelf_no . " | " . $rack->floor) .
                    '</option>';
                }
                ?>
            </select>
        `);
        }

        $('.select2').select2({ width: '100%' });
      });
      function updateRackOptions() {
        let selectedValues = [];

        // collect selected rack ids
        $('select[name="rack_id[]"]').each(function () {
          let val = $(this).val();
          if (val) selectedValues.push(val);
        });

        // disable selected rack ids in all dropdowns
        $('select[name="rack_id[]"]').each(function () {
          let currentSelect = $(this);
          currentSelect.find('option').prop('disabled', false); // reset first

          selectedValues.forEach(function (id) {
            if (currentSelect.val() !== id) {
              currentSelect.find('option[value="' + id + '"]').prop('disabled', true);
            }
          });

          currentSelect.select2(); // refresh select2
        });
      }

      // event listener for rack selection change
      $(document).on('change', 'select[name="rack_id[]"]', function () {
        updateRackOptions();
      });

      //Prevent form submission if invalid inputs exist
      $('form').on('submit', function (e) {
        if ($('.is-invalid').length > 0) {
          e.preventDefault();
          alert('Please fix duplicate or existing accession numbers before submitting.');
        }
      });
    });
  </script>