<?php
$page_title = 'Riwayat Peminjaman';
require_once('includes/load.php');
include_once('layouts/header.php');

if (isset($_GET['id']) && isset($_GET['status'])) {
  $id = (int)$_GET['id'];
  $status = $_GET['status'];

  // Validasi status yang diperbolehkan
  $allowed_status = ['Di Terima', 'Cancelled'];
  if (!in_array($status, $allowed_status)) {
    $session->msg('d', "Status tidak valid.");
    redirect('form_pengembalian.php?id=' . $id, false);
  }

  // Update status di database
  $query = "UPDATE peminjaman SET status = '{$status}' WHERE id = {$id}";
  if ($db->query($query)) {
    $session->msg('s', "Status berhasil diperbarui menjadi '{$status}'.");
  } else {
    $session->msg('d', "Gagal memperbarui status.");
  }

  // Redirect kembali ke halaman daftar peminjaman
  redirect('form_pengembalian.php?id=' . $id, false);
}

?>
<div class="col-md-12">
  <div class="panel panel-default">
    <div class="panel-heading clearfix">
      <strong>
        <span class="glyphicon glyphicon-th"></span>
        <span>Riwayat Peminjaman</span>
      </strong>
      <a href="form_peminjaman.php" class="btn btn-primary btn-sm pull-right">
        Tambah Peminjaman
      </a>
    </div>
    <div class="panel-body">
      <div class="table-responsive">
        <table class="table table-bordered table-hover">
          <thead>
            <tr class="info">
              <th>No</th>
              <th>Nama Peminjam</th>
              <th>Tanggal Pinjam</th>
              <th>Status</th>
              <th>Aksi</th>
            </tr>
          </thead>
          <tbody>
            <?php
            $query = "SELECT * FROM peminjaman";
            $result = $db->query($query);
            $no = 1; // Penomoran otomatis
            while ($row = mysqli_fetch_assoc($result)) {
              echo "<tr>
              <td>{$no}</td>
              <td>{$row['nama_peminjam']}</td>
              <td>" . date('d-m-Y', strtotime($row['tanggal_pinjam'])) . "</td>
              <td>{$row['status']}</td>
              <td>";
              echo "<a href='form_pengembalian.php?id={$row['id']}' class='btn btn-success btn-sm'>
              <i class='glyphicon glyphicon-share-alt'></i> Detail
            </a>";

              $no++;
              echo "</td></tr>";
            }
            ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</div>
<?php include_once('layouts/footer.php'); ?>