<?php
session_start();
date_default_timezone_set('Asia/Kolkata');
error_reporting(0);
include('includes/config.php');
if (strlen($_SESSION['alogin']) == 0) {
  header('location:index.php');
  exit;
}

if (isset($_POST['issue'])) {
  $borrowerid = strtoupper($_POST['borrowerid']);
  $borrowertype = $_POST['borrowertype'];
  $copyid = $_POST['bookdetails'];  // book copy id
  //$duedate = $_POST['duedate'];
  $days = intval($_POST['days'] ?? 0);
  $months = intval($_POST['months'] ?? 0);

  // Calculate due date from today
  $duedate = date('Y-m-d', strtotime("+$months months +$days days"));
  $issueddate = date("Y-m-d H:i:s"); // Output: 2025-09-08 11:25:30


  // ✅ Check if copy is available (using book_status now)
  $checkSql = "SELECT c.id, c.book_no, c.book_status, b.id as bookid 
               FROM tblbookcopies c 
               JOIN tblbooks b ON c.book_id = b.id 
               WHERE c.id = :copyid AND c.book_status = 'available'";
  $checkQuery = $dbh->prepare($checkSql);
  $checkQuery->bindParam(':copyid', $copyid, PDO::PARAM_INT);
  $checkQuery->execute();
  $copy = $checkQuery->fetch(PDO::FETCH_OBJ);

  if ($copy) {
    // Insert issued record
    $sql = "INSERT INTO tblissuedbookdetails (BorrowerID, BorrowerType, BookId, CopyId, DueDate, IssuesDate) 
            VALUES (:borrowerid, :borrowertype, :bookid, :copyid, :duedate, :issueddate)";
    $query = $dbh->prepare($sql);
    $query->bindParam(':borrowerid', $borrowerid);
    $query->bindParam(':borrowertype', $borrowertype);
    $query->bindParam(':bookid', $copy->bookid, PDO::PARAM_INT);
    $query->bindParam(':copyid', $copyid, PDO::PARAM_INT);
    $query->bindParam(':duedate', $duedate);
    $query->bindParam(':issueddate', $issueddate);
    $query->execute();

    $lastInsertId = $dbh->lastInsertId();

    if ($lastInsertId) {
      // ✅ Mark this copy as issued (update book_status)
      $updateSql = "UPDATE tblbookcopies SET book_status = 'issued' WHERE id = :copyid";
      $updateQuery = $dbh->prepare($updateSql);
      $updateQuery->bindParam(':copyid', $copyid, PDO::PARAM_INT);
      $updateQuery->execute();

      // Reduce main book count
      $updateBookSql = "UPDATE tblbooks SET current_count = current_count - 1 WHERE id = :bookid AND current_count > 0";
      $updateBookQuery = $dbh->prepare($updateBookSql);
      $updateBookQuery->bindParam(':bookid', $copy->bookid, PDO::PARAM_INT);
      $updateBookQuery->execute();

      $_SESSION['msg'] = "Book copy issued successfully.";
    } else {
      $_SESSION['error'] = "Something went wrong while issuing.";
    }
  } else {
    $_SESSION['error'] = "This book copy is not available.";
  }

  header('location:manage-issued-books.php');
  exit;
}
?>

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

<head>
  <meta charset="UTF-8">
  <title>Issue 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']; ?>">

  <!-- 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">
  <!-- Select2 -->
  <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />

  <style>
    .main-content {
      margin-left: 180px;
      margin-top: 50px;
      padding: 20px;
    }

    .form-label {
      font-weight: 600;
    }

    .square-card {
      border-radius: 5px;
      box-shadow: 0 4px 8px rgba(0, 0, 0, 0.05);
    }

    .header-line {
      color: #2258d5;
      font-size: 20px;
      font-weight: 600;
      margin-bottom: 20px;
    }
  </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 mb-4">
        <div class="col-md-12">
          <h5 class="header-line"><i class="fas fa-book-reader mr-2"></i>Issue a New Book</h5>
        </div>
      </div>

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

      <!-- Issue Book Form -->
      <div class="row justify-content-center">
        <div class="col-md-8">
          <!-- <div class="card square-card mb-4">
          <div class="card-header bg-secondary text-white">
            <i class="fas fa-plus-circle mr-2"></i>Issue Form
          </div> -->


          <div class="card square-card mb-5">
            <div class="card-header bg-secondary text-white d-flex justify-content-between align-items-center">
              <div>
                <i class="fa fa-book mr-2"></i> Issue Form
              </div>
              <a href="manage-issued-books.php" class="btn btn-sm btn-light shadow-sm">
                <i class="fas fa-arrow-left"></i> back
              </a>
            </div>

            <div class="card-body">
              <form method="post">

                <div class="form-group">
                  <label class="form-label">Borrower Type <span class="text-danger">*</span></label>
                  <select name="borrowertype" id="borrowertype" class="form-control" required>
                    <option value="">Select Type</option>
                    <option value="Student">Student</option>
                    <option value="Staff">Staff</option>
                  </select>
                </div>

                <div class="form-group">
                  <label for="borrowerid" class="form-label">Borrower ID <span class="text-danger">*</span></label>
                  <select name="borrowerid" id="borrowerid" class="form-control" required></select>
                  <small id="get_borrower_name" class="form-text text-muted"></small>
                </div>

                <div class="form-group">
                  <label for="bookid" class="form-label">Book Copy (Title / ISBN / Book No) <span
                      class="text-danger">*</span></label>
                  <select name="bookdetails" id="bookid" class="form-control" required></select>
                </div>

                <!-- <div class="form-group">
                <label for="duedate" class="form-label">Due Date <span class="text-danger">*</span></label>
                <input type="date" name="duedate" id="duedate" class="form-control" required>
              </div> -->



                <div class="form-group">
                  <label class="form-label"> Duration</label>
                  <div class="d-flex">
                    <input type="number" name="days" id="days" class="form-control mr-2" placeholder="Days" min="0"
                      value="" required>
                    <input type="number" name="months" id="months" class="form-control" placeholder="Months" min="0"
                      value="">
                  </div>
                  <small class="form-text text-muted">Enter number of days and months for due date. Due date will be
                    calculated automatically from today.</small>
                </div>



                <div class="d-flex justify-content-between">
                  <!-- <a href="manage-issued-books.php" class="btn btn-secondary">
                  <i class="fas fa-arrow-left"></i> Back
                </a> -->
                  <button type="submit" name="issue" class="btn btn-success">
                    <i class="fas fa-book-medical"></i> Issue Book
                  </button>
                </div>
              </form>
            </div>
          </div>
        </div>
      </div>
    </div>

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

  <!-- Scripts -->
  <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>
    $(document).ready(function () {
      $('#borrowertype').change(function () {
        let type = $(this).val();
        $('#borrowerid').val(null).trigger('change');
        if (type) {
          $('#borrowerid').select2({
            placeholder: 'Search ' + type + ' ID',
            ajax: {
              url: 'get_borrower_list.php',
              dataType: 'json',
              delay: 250,
              data: params => ({ q: params.term, type: type }),
              processResults: data => ({
                results: data.map(item => ({
                  id: item.BorrowerID,
                  text: `${item.BorrowerID} - ${item.FullName}`
                }))
              })
            }
          });
        }
      });

      $('#bookid').select2({
        placeholder: 'Search Book Copy (Title / ISBN / Book No)',
        ajax: {
          url: 'get_book_list.php',
          dataType: 'json',
          delay: 250,
          data: params => ({ q: params.term }),
          processResults: data => ({
            results: data.map(item => ({
              id: item.id,
              text: `Book Name: ${item.BookName} | ISBN: ${item.ISBNNumber} | Copy No: ${item.book_no} | Author Name: ${item.AuthorName}`
            }))
          })
        }
      });
    });
  </script>
</body>

</html>