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

// If staff not logged in, redirect
if (strlen($_SESSION['staff_login']) == 0) {
    header('location:index.php');
    exit;
}

$sid      = $_SESSION['staffid']; // staff ID from session
$bookname = $_GET['bookname'] ?? '';
$status   = $_GET['status'] ?? '';
$from     = $_GET['from'] ?? '';
$to       = $_GET['to'] ?? '';
?>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <title>My Borrowed Books | 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">
  <!-- DataTables -->
  <link href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap4.min.css" rel="stylesheet">
  <link href="https://cdn.datatables.net/buttons/2.4.1/css/buttons.bootstrap4.min.css" rel="stylesheet">

  <style>
    .header-line {
      color: #2258d5;
      font-size: 20px;
      font-weight: bold;
    }
    .table-wrapper {
      overflow-x: auto;
      padding: 10px;
    }
    .badge-returned { background-color: #28a745; }
    .badge-issued { background-color: #ffc107; }
  </style>
</head>
<body>

<div class="d-flex flex-column min-vh-100">
  <?php include('includes/header.php'); ?>

  <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 mr-2"></i> My Borrowed Books (Staff)</h5>
      </div>
    </div>

    <!-- Filter Form -->
    <form method="get" class="form-row mb-4">
      <div class="col-md-3">
        <input type="text" name="bookname" class="form-control" placeholder="Search by Book Name" value="<?= htmlentities($bookname) ?>">
      </div>
      <div class="col-md-2">
        <select name="status" class="form-control">
          <option value="">All Status</option>
          <option value="returned" <?= $status == 'returned' ? 'selected' : '' ?>>Returned</option>
          <option value="not_returned" <?= $status == 'not_returned' ? 'selected' : '' ?>>Not Returned</option>
        </select>
      </div>
      <div class="col-md-2">
        <input type="date" name="from" class="form-control" value="<?= htmlentities($from) ?>">
      </div>
      <div class="col-md-2">
        <input type="date" name="to" class="form-control" value="<?= htmlentities($to) ?>">
      </div>
      <div class="col-md-2">
        <button class="btn btn-primary btn-block" type="submit"><i class="fa fa-filter mr-1"></i>Filter</button>
      </div>
    </form>

    <!-- Report Table -->
    <div class="card mb-5">
      <div class="card-header bg-secondary text-white">
        <i class="fa fa-book mr-2"></i> Issued Book History
      </div>
      <div class="card-body table-wrapper">
        <table id="bookTable" class="table table-bordered table-hover table-sm">
          <thead class="table-theme-header">
            <tr>
              <th>#</th>
              <th>Book Name</th>
              <th>ISBN</th>
              <th>Issue Date</th>
              <th>Due Date</th>
              <th>Return Date</th>
              <th>Fine (₹)</th>
              <th>Status</th>
            </tr>
          </thead>
          <tbody>
            <?php
            $sql = "SELECT b.BookName, b.ISBNNumber, i.IssuesDate, i.DueDate, i.ReturnDate, i.fine
                    FROM tblissuedbookdetails i 
                    JOIN tblbooks b ON b.id = i.BookId 
                    WHERE i.BorrowerID = :sid AND i.BorrowerType = 'staff'";

            if ($bookname) $sql .= " AND b.BookName LIKE :bookname";
            if ($status === 'returned') $sql .= " AND i.ReturnDate IS NOT NULL";
            if ($status === 'not_returned') $sql .= " AND i.ReturnDate IS NULL";
            if ($from) $sql .= " AND DATE(i.IssuesDate) >= :from";
            if ($to) $sql .= " AND DATE(i.IssuesDate) <= :to";
            $sql .= " ORDER BY i.id DESC";

            $query = $dbh->prepare($sql);
            $query->bindParam(':sid', $sid, PDO::PARAM_STR);
            if ($bookname) {
              $bk = "%$bookname%";
              $query->bindParam(':bookname', $bk, PDO::PARAM_STR);
            }
            if ($from) $query->bindParam(':from', $from, PDO::PARAM_STR);
            if ($to) $query->bindParam(':to', $to, PDO::PARAM_STR);

            $query->execute();
            $results = $query->fetchAll(PDO::FETCH_OBJ);
            $cnt = 1;

            if ($results) {
              foreach ($results as $row) {
            ?>
              <tr>
                <td><?= $cnt++; ?></td>
                <td><?= htmlentities($row->BookName); ?></td>
                <td><?= htmlentities($row->ISBNNumber); ?></td>
                <td><?= htmlentities($row->IssuesDate); ?></td>
                <td><?= htmlentities($row->DueDate); ?></td>
                <td>
                  <?= $row->ReturnDate 
                      ? htmlentities($row->ReturnDate) 
                      : "<span class='text-danger'>Not Returned</span>"; ?>
                </td>
                <td><?= $row->fine !== null ? htmlentities($row->fine) : '0'; ?></td>
                <td>
                  <?= $row->ReturnDate 
                      ? "<span class='badge badge-returned text-white'>Returned</span>" 
                      : "<span class='badge badge-issued text-white'>Issued</span>"; ?>
                </td>
              </tr>
            <?php }} else { ?>
              <tr><td colspan="8" class="text-center text-muted">No records found.</td></tr>
            <?php } ?>
          </tbody>
        </table>
      </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 src="https://cdn.datatables.net/buttons/2.4.1/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.bootstrap4.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.html5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.1/js/buttons.print.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>

<script>
  $(document).ready(function () {
    $('#bookTable').DataTable({
      dom: 'Bfrtip',
      buttons: [
        {
          extend: 'print',
          className: 'btn btn-info',
          text: '<i class="fa fa-print"></i> Print'
        },
        {
          extend: 'excelHtml5',
          className: 'btn btn-success',
          text: '<i class="fa fa-file-excel"></i> Export Excel'
        }
      ],
      language: {
        search: "🔍 Search:"
      },
      pageLength: 10,
      ordering: true,
      responsive: true
    });
  });
</script>

</body>
</html>
