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

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

if (!isset($_SESSION['stdid']) || $_SESSION['stdid'] == '') {
  die("Error: Student session ID not found. Please login again.");
}

$studentid = $_SESSION['stdid'];

if (isset($_POST['submit'])) {
  $bookid = intval($_POST['book']);
  $requestdate = date('Y-m-d H:i:s');

  $sqlCheck = "SELECT id FROM tblbookrequests WHERE book_id = :bookid AND student_id = :studentid AND status = 'Pending'";
  $queryCheck = $dbh->prepare($sqlCheck);
  $queryCheck->bindParam(':bookid', $bookid, PDO::PARAM_INT);
  $queryCheck->bindParam(':studentid', $studentid, PDO::PARAM_STR);
  $queryCheck->execute();

  if ($queryCheck->rowCount() > 0) {
    $message = ['type' => 'warning', 'text' => 'You already have a pending request for this book.'];
  } else {
    $sqlInsert = "INSERT INTO tblbookrequests (book_id, student_id, request_date, status) 
                  VALUES (:bookid, :studentid, :requestdate, 'Pending')";
    $queryInsert = $dbh->prepare($sqlInsert);
    $queryInsert->bindParam(':bookid', $bookid, PDO::PARAM_INT);
    $queryInsert->bindParam(':studentid', $studentid, PDO::PARAM_STR);
    $queryInsert->bindParam(':requestdate', $requestdate);
    $queryInsert->execute();

    $message = ['type' => 'success', 'text' => 'Book request submitted successfully.'];
  }
}
?>

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

<head>
  <meta charset="utf-8" />
  <title>Request 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 4.6 -->
  <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>
    .header-line {
      color:   #0d6efd;
      font-size: 20px;
    }

    .form-label {
      font-weight: bold;
    }
  </style>
</head>

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

  <div class="d-flex flex-column min-vh-100">
    <div class="main-content flex-grow-1 p-4">

      <div class="row mb-4">
        <div class="col-md-12">
          <h5 class="header-line"><i class="fa fa-book-reader mr-2"></i>Request a Book</h5>
        </div>
      </div>

      <?php if (isset($message)): ?>
        <div class="alert alert-<?= $message['type']; ?> alert-dismissible fade show" role="alert">
          <?= htmlentities($message['text']); ?>
          <button type="button" class="close" data-dismiss="alert">&times;</button>
        </div>
      <?php endif; ?>

      <!-- 📋 Request Form -->
      <div class="row mb-5">
        <div class="col-md-8 mx-auto">
          <div class="card">
            <div class="card-header bg-secondary text-white">
              <i class="fa fa-edit mr-2"></i> Fill Book Request Form
            </div>
            <div class="card-body">
              <form method="post">
                <div class="form-group">
                  <label for="book" class="form-label">Select Book</label>
                  <select name="book" class="form-control" required>
                    <option value="">-- Select Book --</option>
                    <?php
                    $sql = "SELECT 
                            b.id, b.BookName, b.ISBNNumber, b.current_count, 
                            r.rack_no, r.shelf_no, r.floor
                          FROM tblbooks b
                          LEFT JOIN tbl_racks r ON b.rack_id = r.id
                          WHERE b.current_count > 0";
                    $query = $dbh->prepare($sql);
                    $query->execute();
                    $books = $query->fetchAll(PDO::FETCH_OBJ);
                    foreach ($books as $book) {
                      echo "<option value='" . htmlentities($book->id) . "'>";
                      echo htmlentities($book->BookName) . " | ISBN: " . htmlentities($book->ISBNNumber);
                      echo " | Rack: " . htmlentities($book->rack_no) . ", Shelf: " . htmlentities($book->shelf_no) . ", Floor: " . htmlentities($book->floor);
                      echo " | Available: " . htmlentities($book->current_count);
                      echo "</option>";
                    }
                    ?>
                  </select>
                </div>
                <button type="submit" name="submit" class="btn btn-primary">
                  <i class="fa fa-paper-plane"></i> Submit Request
                </button>
              </form>
            </div>
          </div>
        </div>
      </div>

      <!-- 📜 Request History Table -->
      <div class="row">
        <div class="col-md-12">
          <h5 class="header-line"><i class="fa fa-history mr-2"></i>Your Book Requests</h5>
          <div class="card">
            <div class="card-body table-responsive">
              <table id="requestTable" class="table table-striped table-bordered">
                <thead class="table-theme-header">
                  <tr>
                    <th>Book Name</th>
                    <th>Status</th>
                    <th>Request Date</th>
                    <th>Admin Remark</th>
                    <th>Decision Date</th>
                  </tr>
                </thead>
                <tbody>
                  <?php
                  $sql = "SELECT b.BookName, r.status, r.request_date, r.admin_remark, r.decision_date
                        FROM tblbookrequests r
                        JOIN tblbooks b ON r.book_id = b.id
                        WHERE r.student_id = :studentid
                        ORDER BY r.request_date DESC";
                  $query = $dbh->prepare($sql);
                  $query->bindParam(':studentid', $studentid, PDO::PARAM_STR);
                  $query->execute();
                  $results = $query->fetchAll(PDO::FETCH_OBJ);
                  foreach ($results as $row) {
                    $statusColor = [
                      'approved' => 'text-success',
                      'pending' => 'text-warning',
                      'rejected' => 'text-danger'
                    ][strtolower($row->status)] ?? 'text-dark';
                    echo "<tr>
                      <td>" . htmlentities($row->BookName) . "</td>
                      <td class='{$statusColor} font-weight-bold'>" . htmlentities($row->status) . "</td>
                      <td>" . htmlentities($row->request_date) . "</td>
                      <td>" . htmlentities($row->admin_remark ?? '-') . "</td>
                      <td>" . htmlentities($row->decision_date ?? '-') . "</td>
                    </tr>";
                  }
                  ?>
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </div>

    </div>
  </div>

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

  <!-- 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.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 () {
      $('#requestTable').DataTable({
        order: [[2, 'desc']],
        pageLength: 10
      });
    });
  </script>
</body>

</html>