<?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;
}

$bookid = isset($_GET['bookid']) ? intval($_GET['bookid']) : 0;
if ($bookid <= 0) {
  $_SESSION['error'] = "Invalid Book ID.";
  header('location:manage-books.php');
  exit;
}

// Fetch existing book record
$sqlOld = "SELECT * FROM tblbooks WHERE id = :bookid";
$qOld = $dbh->prepare($sqlOld);
$qOld->bindParam(':bookid', $bookid, PDO::PARAM_INT);
$qOld->execute();
$book = $qOld->fetch(PDO::FETCH_ASSOC);

if (!$book) {
  $_SESSION['error'] = "Book not found.";
  header('location:manage-books.php');
  exit;
}

// Fetch lists
$authorsList = $dbh->query("SELECT id, AuthorName, AuthorID, is_deleted FROM tblauthors ORDER BY AuthorName ASC")->fetchAll(PDO::FETCH_OBJ);
$categories = $dbh->query("SELECT id, CategoryName, CategoryCode, is_deleted FROM tblcategory")->fetchAll(PDO::FETCH_OBJ);
$publishers = $dbh->query("SELECT id, PublisherName, RniNumber FROM tblpublishers")->fetchAll(PDO::FETCH_OBJ);
$racks = $dbh->query("SELECT * FROM tbl_racks")->fetchAll(PDO::FETCH_OBJ);
$departments = $dbh->query("SELECT department_id, department_name, department_code FROM tbldepartment")->fetchAll(PDO::FETCH_OBJ);
$degrees = $dbh->query("SELECT degree_id, degree_name FROM tbldegree")->fetchAll(PDO::FETCH_OBJ);

// Selected authors
$selectedAuthorIds = !empty($book['AuthorIds'])
  ? array_filter(array_map('trim', explode(',', $book['AuthorIds'])))
  : [];

// Old book counts
$oldTotalCount = (int) ($book['total_count'] ?? 0);
$oldCurrentCount = (int) ($book['current_count'] ?? 0);

// Handle update
if (isset($_POST['update'])) {
  $bookname = trim($_POST['bookname']);
  $category = intval($_POST['category']);
  $authorInputs = isset($_POST['authors']) ? array_map('intval', array_filter($_POST['authors'])) : [];
  $authorIdsCsv = implode(',', $authorInputs);


  $isbn = trim($_POST['isbn']);
  $edition = trim($_POST['edition']);
  $volume = trim($_POST['volume']);
  $publisher = !empty($_POST['publisher']) ? intval($_POST['publisher']) : null;
  $pub_year = !empty($_POST['publication_year']) ? trim($_POST['publication_year']) : null;
  // $cbrb_no = $_POST['cbrb_no'] ?? null;
  // $acc_no = $_POST['acc_no'] ?? null;
  $price = is_numeric($_POST['price']) ? floatval($_POST['price']) : 0;
  $purchase_date = !empty($_POST['purchase_date']) ? $_POST['purchase_date'] : null;
  $rack_id = !empty($_POST['rack_id']) ? intval($_POST['rack_id']) : null;
  $newTotalCount = isset($_POST['total_count']) ? (int) $_POST['total_count'] : $oldTotalCount;
  $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;

  $total_price = $price * max(0, $newTotalCount);
  $diff = $newTotalCount - $oldTotalCount;
  $newCurrentCount = max(0, $oldCurrentCount + $diff);

  // Update book
  $sql = "UPDATE tblbooks SET
                BookName = :bookname,
                CatId = :category,
               AuthorIds = :authorIds,

                ISBNNumber = :isbn,
                Edition = :edition,
                Volume = :volume,
                Publisher = :publisher,
                PublicationYear = :pub_year,
                BookPrice = :price,
                total_price = :total_price,
                PurchaseDate = :purchase_date,
                total_count = :total_count,
                current_count = :current_count,
                department_id = :department_id,
                degree_id = :degree_id,
                Status = :status
            WHERE id = :bookid";

  $query = $dbh->prepare($sql);
  $query->bindParam(':bookname', $bookname);
  $query->bindParam(':category', $category);
  $query->bindParam(':authorIds', $authorIdsCsv);

  $query->bindParam(':isbn', $isbn);
  $query->bindParam(':edition', $edition);
  $query->bindParam(':volume', $volume);
  $query->bindParam(':publisher', $publisher);
  $query->bindParam(':pub_year', $pub_year);
  $query->bindParam(':price', $price);
  $query->bindParam(':total_price', $total_price);
  $query->bindParam(':purchase_date', $purchase_date);
  $query->bindParam(':total_count', $newTotalCount);
  $query->bindParam(':current_count', $newCurrentCount);
  $query->bindParam(':department_id', $department_id);
  $query->bindParam(':degree_id', $degree_id);
  $query->bindParam(':status', $status);
  $query->bindParam(':bookid', $bookid);
  $query->execute();

  // Update rack for all existing copies
  $updateRack = $dbh->prepare("UPDATE tblbookcopies SET rack_id = :rack_id WHERE book_id = :bookid");
  $updateRack->bindParam(':rack_id', $rack_id);
  $updateRack->bindParam(':bookid', $bookid);
  $updateRack->execute();

  $_SESSION['msg'] = "Book updated successfully!";
  header('location:manage-books.php');
  exit;

}
?>

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

<head>
  <meta charset="UTF-8">
  <title>Edit 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);
  }

  option[disabled] {
    color: #999 !important;
    font-style: italic;
  }
</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-edit mr-2"></i>Edit 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" id="editBookForm">

                <!-- Book Name -->
                <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
                    value="<?= htmlentities($book['BookName']) ?>">
                </div>

                <!-- Category -->
                <div class="form-group">
                  <label class="form-label">Category</label>
                  <select name="category" class="form-control select2">
                    <option value="">Select Category</option>
                    <?php foreach ($categories as $cat): ?>
                      <?php
                      // Show only active categories or the selected deleted category
                      if ($cat->is_deleted == 0 || $cat->id == $book['CatId']):
                        $selected = ($cat->id == $book['CatId']) ? 'selected' : '';
                        $disabled = ($cat->id == $book['CatId'] && $cat->is_deleted == 1) ? 'disabled' : '';
                        $label = htmlentities($cat->CategoryName . ' | ' . $cat->CategoryCode);

                        // Append (Deleted) for disabled option
                        if ($disabled) {
                          $label .= ' (Category Deleted!)';
                        }
                        ?>
                        <option value="<?= $cat->id ?>" <?= $selected ?>     <?= $disabled ?>>
                          <?= $label ?>
                        </option>
                      <?php endif; ?>
                    <?php endforeach; ?>
                  </select>
                </div>


                <!-- Dynamic Authors -->
                <label class="form-label">Authors<span class="text-danger">*</span></label>
                <div id="authorFields">
                  <?php if (empty($selectedAuthorIds))
                    $selectedAuthorIds = ['']; ?>
                  <?php foreach ($selectedAuthorIds as $index => $aid): ?>
                    <div class="input-group mb-2 author-row">
                      <div class="input-group-prepend">
                        <span
                          class="input-group-text"><?= ($index + 1) ?><?= ($index == 0 ? 'st' : ($index == 1 ? 'nd' : ($index == 2 ? 'rd' : 'th'))) ?>
                          Author</span>
                      </div>
                      <select name="authors[]" class="form-control select2" required>
                        <option value="">Select Author</option>
                        <?php foreach ($authorsList as $a):
                          // Show only active authors or the selected inactive author
                          if ($a->is_deleted == 0 || $a->id == $aid):
                            $selected = ($a->id == $aid) ? 'selected' : '';
                            $disabled = ($a->id == $aid && $a->is_deleted == 1) ? 'disabled' : '';
                            $label = htmlentities($a->AuthorName . ' | ' . $a->AuthorID);

                            // Append (Deleted) for disabled option
                            if ($disabled) {
                              $label .= ' (Author Deleted!)';
                            }
                            ?>
                            <option value="<?= $a->id ?>" <?= $selected ?>       <?= $disabled ?>>
                              <?= $label ?>
                            </option>
                            <?php
                          endif;
                        endforeach; ?>
                      </select>

                      <div class="input-group-append">
                        <?php if ($index == 0): ?>
                          <!-- <button type="button" class="btn btn-success add-author-btn">+</button> -->
                          <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>

                        <?php else: ?>
                          <!-- <button type="button" class="btn btn-danger remove-author-btn">-</button> -->
                          <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>
                        <?php endif; ?>
                      </div>
                    </div>
                  <?php endforeach; ?>
                </div>


                <!-- ISBN -->
                <div class="form-group">
                  <label class="form-label">ISBN Number</label>
                  <input type="text" name="isbn" id="isbn" class="form-control"
                    value="<?= htmlentities($book['ISBNNumber'] ?? '') ?>">
                  <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">Per Book Price</label>
                  <input type="text" name="price" class="form-control" value="<?= htmlentities($book['BookPrice']) ?>">
                </div>

                <div class="form-group">
                  <label class="form-label">Purchase Date</label>
                  <input type="date" name="purchase_date" class="form-control"
                    value="<?= htmlentities($book['PurchaseDate']) ?>">
                </div>

                <!-- <div class="form-group">
                  <label class="form-label">Cupboard Info<span class="text-danger">*</span></label>
                  <select name="rack_id" class="form-control" required>
                    <option value="">Select Cupboard</option>
                    <?php
                    $racks = $dbh->query("SELECT * FROM tbl_racks")->fetchAll(PDO::FETCH_OBJ);
                    foreach ($racks as $rack) {
                      // Fetch rack from first copy
                      $copyRack = $dbh->prepare("SELECT rack_id FROM tblbookcopies WHERE book_id = :bookid LIMIT 1");
                      $copyRack->bindParam(':bookid', $bookid);
                      $copyRack->execute();
                      $copyRackId = $copyRack->fetchColumn();
                      $sel = ($rack->id == $copyRackId) ? 'selected' : '';
                      echo "<option value='{$rack->id}' $sel>Rack: {$rack->rack_no} | Shelf: {$rack->shelf_no} | Floor: {$rack->floor}</option>";
                    }
                    ?>
                  </select>
                </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
                    $departments = $dbh->query("SELECT department_id, department_name, is_deleted FROM tbldepartment ORDER BY department_name ASC")->fetchAll(PDO::FETCH_OBJ);
                    foreach ($departments as $dept):
                      if ($dept->is_deleted == 0 || $dept->department_id == $book['department_id']):
                        $selected = ($dept->department_id == $book['department_id']) ? 'selected' : '';
                        $disabled = ($dept->department_id == $book['department_id'] && $dept->is_deleted == 1) ? 'disabled' : '';
                        $label = htmlentities($dept->department_name);
                        if ($disabled) {
                          $label .= ' (Deleted)';
                        }
                        ?>
                        <option value="<?= $dept->department_id ?>" <?= $selected ?>     <?= $disabled ?>><?= $label ?></option>
                        <?php
                      endif;
                    endforeach;
                    ?>
                  </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
                    $degrees = $dbh->query("SELECT degree_id, degree_name, is_deleted FROM tbldegree ORDER BY degree_name ASC")->fetchAll(PDO::FETCH_OBJ);
                    foreach ($degrees as $deg):
                      if ($deg->is_deleted == 0 || $deg->degree_id == $book['degree_id']):
                        $selected = ($deg->degree_id == $book['degree_id']) ? 'selected' : '';
                        $disabled = ($deg->degree_id == $book['degree_id'] && $deg->is_deleted == 1) ? 'disabled' : '';
                        $label = htmlentities($deg->degree_name);
                        if ($disabled) {
                          $label .= ' (Deleted)';
                        }
                        ?>
                        <option value="<?= $deg->degree_id ?>" <?= $selected ?>     <?= $disabled ?>><?= $label ?></option>
                        <?php
                      endif;
                    endforeach;
                    ?>
                  </select>
                </div>




                <!-- Edition -->
                <div class="form-group">
                  <label class="form-label">Edition</label>
                  <select name="edition" class="form-control">
                    <option value="">Select Edition</option>
                    <?php
                    for ($i = 1; $i <= 50; $i++) {
                      // Check if this edition number matches the one in the database
                      $sel = ($i == $book['Edition']) ? 'selected' : '';
                      echo "<option value='{$i}' {$sel}>" . ordinal($i) . " Edition</option>";
                    }

                    // Function to convert number into ordinal (1st, 2nd, 3rd, etc.)
                    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>


                <!-- Volume -->
                <div class="form-group">
                  <label class="form-label">Volume</label>
                  <select name="volume" class="form-control">
                    <option value="">Select Volume</option>
                    <?php
                    for ($i = 1; $i <= 50; $i++) {
                      $vol = "Vol {$i}";
                      $sel = ($vol == $book['Volume']) ? 'selected' : '';
                      echo "<option value='{$vol}' {$sel}>{$vol}</option>";
                    }
                    ?>
                  </select>
                </div>


                <!-- Publisher -->
                <div class="form-group">
                  <label class="form-label">Publisher</label>
                  <select name="publisher" class="form-control select2">
                    <option value="">Select Publisher</option>
                    <?php
                    $publishers = $dbh->query("SELECT id, PublisherName, is_deleted FROM tblpublishers ORDER BY PublisherName ASC")->fetchAll(PDO::FETCH_OBJ);
                    foreach ($publishers as $p):
                      if ($p->is_deleted == 0 || $p->id == $book['Publisher']):
                        $selected = ($book['Publisher'] == $p->id) ? 'selected' : '';
                        $disabled = ($p->id == $book['Publisher'] && $p->is_deleted == 1) ? 'disabled' : '';
                        $label = htmlentities($p->PublisherName);
                        if ($disabled) {
                          $label .= ' (Deleted)';
                        }
                        ?>
                        <option value="<?= $p->id ?>" <?= $selected ?>     <?= $disabled ?>><?= $label ?></option>
                        <?php
                      endif;
                    endforeach;
                    ?>
                  </select>
                </div>


                <!-- Publication Year -->
                <div class="form-group">
                  <label class="form-label">Publication Year</label>
                  <select name="publication_year" class="form-control">
                    <?php
                    $currentYear = date("Y");
                    for ($y = $currentYear; $y >= 1900; $y--) {
                      $selected = ($book['PublicationYear'] == $y) ? 'selected' : '';
                      echo "<option value='{$y}' {$selected}>{$y}</option>";
                    }
                    ?>
                  </select>
                </div>

                <!-- CBRB No -->
                <!-- <div class="form-group">
                  <label class="form-label">CBRB No</label>
                  <input type="text" name="cbrb_no" class="form-control"
                    value="<?= htmlentities($book['CbrbNo'] ?? '') ?>">
                </div> -->
                <!-- <div class="form-group">
                  <label class="form-label">Accession No</label>
                  <input type="text" name="acc_no" class="form-control"
                    value="<?= htmlentities($book['AccessionNumber'] ?? '') ?>">
                </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="<?= htmlentities($book['total_count']) ?>" required>
                        </div> -->


                <!-- <div class="form-group">
                            <label class="form-label">Status</label>
                            <select name="status" class="form-control" required>
                                <option value="1" <?= $book['Status'] == 1 ? 'selected' : '' ?>>Active</option>
                                <option value="0" <?= $book['Status'] == 0 ? 'selected' : '' ?>>Inactive</option>
                            </select>
                        </div> -->

                <!-- Other fields (same as add form) -->
                <!-- Copies, Price, Publication Year, CBRB, Rack, Department, Degree, Publisher, Status -->

                <div class="d-flex justify-content-between">
                  <!-- <a href="manage-books.php" class="btn btn-secondary">Cancel</a> -->
                  <button type="submit" name="update" class="btn btn-primary"><i class="fas fa-save"></i> Update
                    Book</button>
                </div>
              </form>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <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>
    $(document).ready(function () {
      $('.select2').select2({ width: '100%' });

      $(document).on('click', '.add-author-btn', function () {
        let row = `<?php ob_start(); ?>
        <div class="input-group mb-2 author-row">
            <select name="authors[]" class="form-control select2" required>
                <option value="">Select Author</option>
                <?php foreach ($authorsList as $a): ?>
                    <option value="<?= $a->id ?>"><?= addslashes($a->AuthorName . ' | ' . $a->AuthorID) ?></option>
                <?php endforeach; ?>
            </select>
            <div class="input-group-append">
                <button type="button" class="btn btn-danger remove-author-btn">-</button>
            </div>
        </div>
        <?php echo trim(preg_replace('/\s+/', ' ', ob_get_clean())); ?>`;
        $('#authorFields').append(row);
        $('.select2').select2({ width: '100%' });
      });

      $(document).on('click', '.remove-author-btn', function () {
        $(this).closest('.author-row').remove();
      });

      $('#isbn').on('blur', function () {
        var isbn = $(this).val().trim();
        if (!isbn) { $('#isbn-status').html(''); return; }
        $.post('check_isbn.php', { isbn: isbn, bookid: <?= $bookid ?> }, function (data) {
          $('#isbn-status').html(data);
        });
      });
    });
  </script>
</body>

</html>