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

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

$id = isset($_GET['id']) ? (int) $_GET['id'] : 0;

// Get copy + book
$sql = "SELECT 
          c.id, c.book_id, c.book_no, c.accession_no, c.shift,
          c.book_status, c.reason, c.rack_id,
          b.BookName,
          r.rack_no, r.shelf_no, r.floor
        FROM tblbookcopies c
        JOIN tblbooks b ON b.id = c.book_id
        LEFT JOIN tbl_racks r ON r.id = c.rack_id
        WHERE c.id = :id";

$q = $dbh->prepare($sql);
$q->bindParam(':id', $id, PDO::PARAM_INT);
$q->execute();
$copy = $q->fetch(PDO::FETCH_ASSOC);

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

  // Get new values
  $new_accession = trim($_POST['accession_no']);
  $old_accession = $copy['accession_no'];

  $new_rack_id = (int) $_POST['rack_id'];
  $old_rack_id = (int) $copy['rack_id'];

  $new_shift = (int) $_POST['shift'];
  $old_shift = (int) $copy['shift'];

  // 1. Shift update
  if ($new_shift !== $old_shift) {
    $updShift = $dbh->prepare("UPDATE tblbookcopies SET shift = :sh WHERE id = :id");
    $updShift->execute([':sh' => $new_shift, ':id' => $id]);
    $copy['shift'] = $new_shift;
  }

  // 2. Rack update
  if ($new_rack_id !== $old_rack_id) {
    $updRack = $dbh->prepare("UPDATE tblbookcopies SET rack_id = :rack WHERE id = :id");
    $updRack->execute([':rack' => $new_rack_id, ':id' => $id]);
    $copy['rack_id'] = $new_rack_id;
  }

  // 3. Check duplicate accession (except current id)
  $checkAcc = $dbh->prepare("SELECT id FROM tblbookcopies WHERE accession_no = :acc AND id != :id");
  $checkAcc->execute([':acc' => $new_accession, ':id' => $id]);

  if ($checkAcc->rowCount() > 0) {
    $_SESSION['error'] = "Accession Number already exists! Try another.";
    header("location:copy-edit.php?id=" . $id);
    exit;
  }

  // Detect changes
  $accession_changed = ($old_accession !== $new_accession);

  // Status change
  $new_status = in_array($_POST['book_status'], ['available', 'damaged', 'lost', 'NA'])
    ? $_POST['book_status']
    : $copy['book_status'];

  $old_status = $copy['book_status'];
  $status_changed = ($old_status !== $new_status);

  $reason = trim($_POST['reason'] ?? '');
  $changed_by = $_SESSION['alogin'] ?? 'Admin';

  // If status changed → reason required
  if ($status_changed && $reason === '') {
    $_SESSION['error'] = "Please provide a reason for changing book status.";
    header("location:copy-edit.php?id=" . $id);
    exit;
  }

  // 4. Update Accession if changed
  if ($accession_changed) {
    $updAcc = $dbh->prepare("UPDATE tblbookcopies SET accession_no = :acc WHERE id = :id");
    $updAcc->execute([':acc' => $new_accession, ':id' => $id]);
  }

  $shift_changed = ($old_shift !== $new_shift);
  $rack_changed = ($old_rack_id !== $new_rack_id);

  // 5. Update Status + History + available count
  if ($status_changed) {

    // Update main record
    $upd = $dbh->prepare("UPDATE tblbookcopies SET book_status=:bs, reason=:r WHERE id=:id");
    $upd->execute([':bs' => $new_status, ':r' => $reason, ':id' => $id]);

    // Insert history
    $hist = $dbh->prepare("INSERT INTO tblbookcopy_reason_history(copy_id, old_status, new_status, reason, changed_by)
                           VALUES(:cid, :os, :ns, :r, :cb)");
    $hist->execute([
      ':cid' => $id,
      ':os' => $old_status,
      ':ns' => $new_status,
      ':r' => $reason,
      ':cb' => $changed_by
    ]);

    // Recalculate available count
    $cntQ = $dbh->prepare("SELECT COUNT(*) FROM tblbookcopies WHERE book_id=:bid AND book_status='available'");
    $cntQ->execute([':bid' => $copy['book_id']]);
    $availableCount = (int) $cntQ->fetchColumn();

    $updBook = $dbh->prepare("UPDATE tblbooks SET current_count=:cc WHERE id=:bid");
    $updBook->execute([':cc' => $availableCount, ':bid' => $copy['book_id']]);
  }

  // SUCCESS message builder
  $msgParts = [];

  if ($accession_changed)
    $msgParts[] = "Accession Number";
  if ($shift_changed)
    $msgParts[] = "Shift";
  if ($status_changed)
    $msgParts[] = "Status";
  if ($rack_changed)
    $msgParts[] = "Cupboard info";

  if (!empty($msgParts)) {
    $_SESSION['msg'] = implode(", ", $msgParts) . " updated successfully.";
  } else {
    $_SESSION['error'] = "No changes detected.";
  }

  header('location:copy-edit.php?id=' . $id);
  exit;
}

?>

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

<head>
  <meta charset="utf-8">
  <title>Edit Copy | Online Library</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">
  <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.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;
    }

    .card-header {
      font-weight: bold;
    }
  </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">EDIT COPY</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>

      <div class="container">
        <div class="card square-card mb-4">
          <div class="card-header bg-primary text-white">
            <i class="fa fa-edit mr-2"></i> Edit Copy: <?= htmlentities($copy['book_no']) ?>
            (<?= htmlentities($copy['BookName']) ?>)
          </div>
          <div class="card-body">
            <form method="post">
              <div class="form-row">
                <div class="form-group col-md-6">
                  <label><i class="fa fa-key mr-1 text-secondary"></i> Accession Number</label>
                  <input type="text" name="accession_no" class="form-control"
                    value="<?= htmlentities($copy['accession_no']) ?>" required>
                </div>

                <?php
                // Fetch all racks for dropdown
                $rackQ = $dbh->prepare("
                                        SELECT r.*
                                        FROM tbl_racks r
                                        WHERE r.id = :current_rack_id
                                          OR r.id NOT IN (SELECT rack_id FROM tblbookcopies WHERE rack_id != :current_rack_id)
                                        ORDER BY r.id ASC
                                    ");
                $rackQ->bindParam(':current_rack_id', $copy['rack_id'], PDO::PARAM_INT);
                $rackQ->execute();
                $racks = $rackQ->fetchAll(PDO::FETCH_ASSOC);

                ?>
                <div class="form-group col-md-6">
                  <label><i class="fa fa-warehouse mr-1 text-secondary"></i> Cupboard / Shelf / Book</label>
                  <select name="rack_id" class="form-control select2">
                    <option value="">-- Select cupboard --</option>
                    <?php foreach ($racks as $r):
                      $sel = ($r['id'] == $copy['rack_id']) ? 'selected' : ''; ?>
                      <option value="<?= $r['id'] ?>" <?= $sel ?>>
                        Cupboard <?= htmlentities($r['rack_no']) ?> |
                        Shelf <?= htmlentities($r['shelf_no']) ?> |
                        Book <?= htmlentities($r['floor']) ?>
                      </option>
                    <?php endforeach; ?>
                  </select>
                </div>

                <div class="form-group col-md-6">
                  <label><i class="fa-solid fa-arrows-rotate mr-1 text-secondary"></i>Shift</label>
                  <select name="shift" class="form-control">
                    <option value="">-- Select shift --</option>
                    <option value="1" <?= ($copy['shift'] == 1) ? 'selected' : '' ?>>I</option>
                    <option value="2" <?= ($copy['shift'] == 2) ? 'selected' : '' ?>>II</option>
                  </select>
                </div>
              </div>

              <div class="form-row">
                <div class="form-group col-md-6">
                  <label><i class="fa fa-book mr-1 text-secondary"></i> Book Status</label>
                  <select name="book_status" id="book_status" class="form-control" required>
                    <?php
                    $opts = ['available', 'damaged', 'lost', 'NA'];
                    foreach ($opts as $o) {
                      $sel = ($copy['book_status'] === $o) ? 'selected' : '';
                      echo "<option value=\"$o\" $sel>" . ucfirst($o) . "</option>";
                    }
                    ?>
                  </select>
                  <small class="form-text text-muted">
                    <i class="fa fa-info-circle"></i> Copies marked as <b>damaged</b>, <b>lost</b>, or <b>NA</b> will
                    not be counted as available.
                  </small>
                </div>

                <div class="form-group col-md-6" id="reason-group" style="display:none;">
                  <label><i class="fa fa-comment-dots mr-1 text-secondary"></i> Reason</label>
                  <textarea name="reason" id="reason" class="form-control" rows="3"
                    placeholder="Enter reason for changing the status" <?= !empty($copy['reason']) ? 'readonly' : '' ?>><?= htmlentities($copy['reason'] ?? '') ?></textarea>
                  <?php if (!empty($copy['reason'])): ?>
                    <small class="form-text text-muted"><i class="fa fa-lock"></i> This reason is locked and cannot be
                      edited.</small>
                  <?php endif; ?>
                </div>
              </div>

              <div class="text-center mt-3">
                <button type="submit" class="btn btn-success mr-2">
                  <i class="fa fa-save"></i> Save Changes
                </button>
                <a href="book-copies.php?bookid=<?= (int) $copy['book_id'] ?>" class="btn btn-secondary">
                  <i class="fa fa-times"></i> Cancel
                </a>
              </div>
            </form>

          </div>
          <!-- Reason History Section -->
          <hr class="my-4">
          <h5 class="mb-3"><i class="fa fa-history text-secondary mr-2"></i> Reason History</h5>
          <?php
          $hist = $dbh->prepare("SELECT * FROM tblbookcopy_reason_history WHERE copy_id=:cid ORDER BY changed_at DESC");
          $hist->execute([':cid' => $id]);
          $rows = $hist->fetchAll(PDO::FETCH_ASSOC);

          if (!$rows) {
            echo '<div class="alert alert-info"><i class="fa fa-info-circle"></i> No reason history found for this copy.</div>';
          } else {
            echo '<div class="table-responsive"><table class="table table-hover table-striped table-bordered">';
            echo '<thead class="thead-dark">
          <tr>
            <th>#</th>
            <th>Old Status</th>
            <th>New Status</th>
            <th>Reason</th>
            <!--<th>Changed By</th> -->
            <th>Changed At</th>
          </tr>
        </thead><tbody>';
            $i = 1;
            foreach ($rows as $r) {
              echo '<tr>
            <td>' . $i++ . '</td>
            <td>' . ucfirst(htmlentities($r['old_status'])) . '</td>
            <td>' . ucfirst(htmlentities($r['new_status'])) . '</td>
            <td>' . nl2br(htmlentities($r['reason'])) . '</td>
            <!-- <td>' . htmlentities($r['changed_by']) . '</td> -->
            <td>' . htmlentities(date('d-m-Y h:i A', strtotime($r['changed_at']))) . '</td>
          </tr>';
            }
            echo '</tbody></table></div>';
          }
          ?>

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

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

  <!-- jQuery + Bootstrap JS -->
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
  <script>
    const reasonField = document.getElementById('reason');
    const statusSelect = document.getElementById('book_status');
    const reasonGroup = document.getElementById('reason-group');

    // Store current reason temporarily when switching between statuses
    let reasonCache = reasonField.value;

    statusSelect.addEventListener('change', function () {
      const status = this.value;

      if (status === 'available' || status === 'damaged' || status === 'lost') {
        reasonGroup.style.display = 'block';
        reasonField.removeAttribute('readonly');
        // Restore previously typed reason if any
        reasonField.value = reasonCache || reasonField.value;
      } else {
        reasonGroup.style.display = 'none';
      }
    });

    // Keep latest reason in cache
    reasonField.addEventListener('input', () => {
      reasonCache = reasonField.value;
    });

    // Initialize visibility
    (function init() {
      const status = statusSelect.value;
      if (status === 'available' || status === 'damaged' || status === 'lost') {
        reasonGroup.style.display = 'block';
      }
    })();
  </script>
  <script>
    $(document).ready(function () {
      $('.select2').select2({
        width: '100%',
        placeholder: "Search rack...",
        allowClear: true
      });
    });
  </script>

</body>

</html>