<?php
session_start();
error_reporting(0);
include('includes/config.php');
date_default_timezone_set('Asia/Kolkata');
$updatetime = date('Y-m-d H:i:s');
if (strlen($_SESSION['alogin']) == 0) {
  header('location:index.php');
  exit;
}

if (isset($_POST['request_id'], $_POST['action'])) {
  $request_id = intval($_POST['request_id']);
  $action = $_POST['action'];
  $admin_remark = trim($_POST['admin_remark'] ?? '');

  if ($action == 'approve' || $action == 'reject') {
    $status = ($action == 'approve') ? 'Approved' : 'Rejected';
    $sql = "UPDATE tblbookrequests SET status = :status, admin_remark = :remark, decision_date = :updatetime WHERE id = :id";
    $query = $dbh->prepare($sql);
    $query->bindParam(':status', $status, PDO::PARAM_STR);
    $query->bindParam(':remark', $admin_remark, PDO::PARAM_STR);
    $query->bindParam(':id', $request_id, PDO::PARAM_INT);
    $query->bindParam(':updatetime', $updatetime);

    $query->execute();
    $_SESSION['msg'] = "Request $status successfully.";
    header("location:manage-requests.php");
    exit;
  }
}
?>

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

<head>
  <meta charset="UTF-8" />
  <title>Manage Book Requests | 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 6 -->
  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">

  <!-- DataTables Bootstrap 4 -->
  <link href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap4.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;
    }

    .flash-message {
      max-width: 600px;
      margin: 0 auto 15px;
    }

    .table-wrapper {
      overflow-x: auto;
      padding: 10px;
    }

    .col-md-12 h5 {
      color: #0d6efd;
      font-size: 20px;
    }

    .dataTables_filter label {
      color: #000 !important;
      font-weight: 500;
    }

    .dataTables_filter input {
      height: 32px;
      font-size: 0.95rem;
      padding: 4px 8px;
    }
  </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">MANAGE BOOK REQUESTS</h5>
        </div>
      </div>

      <!-- Flash Messages -->
      <div class="row justify-content-center">
        <div class="col-md-8">
          <?php if (!empty($_SESSION['msg'])): ?>
            <div class="alert alert-success flash-message">
              <strong>Success:</strong> <?php echo htmlentities($_SESSION['msg']);
              unset($_SESSION['msg']); ?>
            </div>
          <?php endif; ?>
        </div>
      </div>

      <!-- Book Request Table -->
      <div class="card square-card bg-black text-white mb-5">
        <div class="card-header bg-secondary text-white">
          <i class="fa fa-table-list mr-2"></i> Book Requests
        </div>
        <div class="card-body table-wrapper">
          <table id="requestsTable" class="table table-bordered table-hover table-sm text-dark">
            <thead class="table-theme-header">
              <tr>
                <th>#</th>
                <th>Student</th>
                <th>Book</th>
                <th>Request Date</th>
                <th>Status</th>
                <th>Admin Remark</th>
                <th>Decision Date</th>
                <th>Action</th>
              </tr>
            </thead>
            <tbody>
              <?php
              $sql = "SELECT br.id, s.FullName, s.StudentId, b.BookName, br.request_date, br.status, br.admin_remark, br.decision_date
                  FROM tblbookrequests br
                  JOIN tblbooks b ON br.book_id = b.id
                  JOIN tblstudents s ON br.student_id = s.StudentId
                  ORDER BY br.id DESC";

              $query = $dbh->prepare($sql);
              $query->execute();
              $results = $query->fetchAll(PDO::FETCH_OBJ);
              $cnt = 1;
              foreach ($results as $row) {
                ?>
                <tr>
                  <td><?php echo htmlentities($cnt++); ?></td>
                  <td><?php echo htmlentities($row->FullName); ?> (<?php echo htmlentities($row->StudentId); ?>)</td>
                  <td><?php echo htmlentities($row->BookName); ?></td>
                  <td><?php echo htmlentities($row->request_date); ?></td>
                  <td>
                    <?php
                    if ($row->status == 'Approved')
                      echo "<span class='badge badge-success'>Approved</span>";
                    elseif ($row->status == 'Rejected')
                      echo "<span class='badge badge-danger'>Rejected</span>";
                    else
                      echo "<span class='badge badge-warning'>Pending</span>";
                    ?>
                  </td>
                  <td><?php echo htmlentities($row->admin_remark); ?></td>
                  <td><?php echo htmlentities($row->decision_date); ?></td>
                  <td>
                    <?php if ($row->status == 'Pending') { ?>
                      <form method="POST" class="form-inline">
                        <input type="hidden" name="request_id" value="<?php echo $row->id; ?>">
                        <input type="text" name="admin_remark" class="form-control form-control-sm mb-2"
                          placeholder="Remark" required>
                        <div class="btn-group">
                          <button type="submit" name="action" value="approve" class="btn btn-success btn-sm"
                            onclick="return confirm('Approve this request?');">Approve</button>
                          <button type="submit" name="action" value="reject" class="btn btn-danger btn-sm ml-2"
                            onclick="return confirm('Reject this request?');">Reject</button>
                        </div>
                      </form>
                    <?php } else {
                      echo "-";
                    } ?>
                  </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>
    $(document).ready(function () {
      $('#requestsTable').DataTable({
        pageLength: 10,
        lengthChange: true,
        ordering: true,
        responsive: true,
        language: {
          search: "🔍 Search requests:"
        }
      });
    });
  </script>

</body>

</html>