<?php
require __DIR__ . '/../Login/config.php';
require __DIR__ . '/../lib/lib_notify.php';
if (session_status() === PHP_SESSION_NONE) session_start();

if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'admin') {
    header("Location: ../Login/login.php");
    exit;
}

// ==== Filter Status ====
$status_filter = $_GET['status'] ?? 'semua';
$where = '';
$params = [];
if ($status_filter !== 'semua') {
    $where = "WHERE br.status = :status";
    $params[':status'] = $status_filter;
}

// ==== Pencarian ====
$search = $_GET['search'] ?? '';
$searchClause = '';
if ($search !== '') {
    $searchClause = ($where ? " AND" : " WHERE") . " (
        u.fullname LIKE :search OR 
        b.judul LIKE :search OR 
        bi.no_buku LIKE :search OR 
        bi.rak LIKE :search
    )";
    $params[':search'] = "%$search%";
}

// ==== Filter Tanggal ====  <-- DIPINDAH KE ATAS, SEBELUM BANGUN SQL
$raw_date  = $_GET['date'] ?? '';          // "2025-11-12" (input date) atau "12/11/2025"
$date_type = $_GET['date_type'] ?? 'all';  // all|pinjam|jatuh_tempo|kembali

$filter_date = '';
if ($raw_date !== '') {
    if (strpos($raw_date, '/') !== false) {
        $dt = DateTime::createFromFormat('d/m/Y', $raw_date);
    } else {
        $dt = DateTime::createFromFormat('Y-m-d', $raw_date);
    }
    if ($dt) $filter_date = $dt->format('Y-m-d');
}

$dateClause = '';
if ($filter_date !== '') {
    $cmp = " = :fdate";
    if ($date_type === 'pinjam') {
        $dateClause = ($where || $searchClause ? " AND" : " WHERE") . " DATE(br.tgl_pinjam) {$cmp}";
    } elseif ($date_type === 'jatuh_tempo') {
        $dateClause = ($where || $searchClause ? " AND" : " WHERE") . " DATE(br.tgl_jatuh_tempo) {$cmp}";
    } elseif ($date_type === 'kembali') {
        $dateClause = ($where || $searchClause ? " AND" : " WHERE") . " DATE(br.tgl_kembali) {$cmp}";
    } else {
        $dateClause = ($where || $searchClause ? " AND" : " WHERE") .
            " (DATE(br.tgl_pinjam) {$cmp} OR DATE(br.tgl_jatuh_tempo) {$cmp} OR DATE(br.tgl_kembali) {$cmp})";
    }
    $params[':fdate'] = $filter_date;
}

// ==== Baru susun SQL & eksekusi ====
$sql = "
  SELECT 
    br.id AS borrow_id,
    u.id AS user_id,
    u.fullname AS nama_user,
    u.phone AS wa_number,
    b.judul AS judul_buku,
    bi.no_buku,
    bi.rak,
    br.tgl_pinjam,
    br.tgl_jatuh_tempo,
    br.tgl_kembali,
    br.denda,
    br.status,
    br.bukti_path,
    br.denda_bayar,
    br.denda_bayar_tanggal,
    br.bukti_denda_path,
    DATEDIFF(br.tgl_jatuh_tempo, br.tgl_pinjam) AS durasi_hari,
    GREATEST(DATEDIFF(CURDATE(), br.tgl_jatuh_tempo), 0) AS overdue_days,
    DATEDIFF(br.tgl_jatuh_tempo, CURDATE()) AS sisa_hari
  FROM borrowings br
  JOIN users u ON br.user_id = u.id
  JOIN book_items bi ON br.book_item_id = bi.id
  JOIN books b ON bi.book_id = b.id
  $where
  $searchClause
  $dateClause
  ORDER BY br.tgl_pinjam DESC
";

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$borrowings = $stmt->fetchAll(PDO::FETCH_ASSOC);

?>

<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Kelola Peminjaman - Pustakaia</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<style>
    body {
        margin: 0;
        font-family: "Poppins", Arial, sans-serif;
        background: #f4f7f9;
        color: #222;
        display: flex;
        flex-direction: column;
        min-height: 100vh;
    }
    a { text-decoration: none; color: inherit; }
    .container { display: flex; flex: 1; }
    main { flex: 1; padding: 20px; margin-left: 250px; }

    
        /* Sidebar */
        .sidebar {
            width: 250px;
            height: 100vh;
            background: #fff;
            border-right: 1px solid #ddd;
            padding: 10px 0;
            position: fixed;
            top: 0;
            left: 0;
            overflow-y: auto;
        }
        .sidebar-header {
            padding: 15px 20px;
            border-bottom: 1px solid #ddd;
        }
        .sidebar-header h2 {
            margin: 0;
            font-size: 18px;
            color: #069797;
        }
        .sidebar-header p {
            margin: 0;
            font-size: 12px;
            color: #777;
        }
        .sidebar-menu {
            list-style: none;
            padding: 0;
            margin: 0;
        }
        .sidebar-menu li {
            font-size: 14px;
            position: relative;
        }
        .sidebar-menu li > a {
            display: flex;
            align-items: center;
            padding: 12px 20px;
            color: #444;
            width: 100%;
            transition: background 0.2s;
        }
        .sidebar-menu li > a i {
            margin-right: 10px;
            font-size: 16px;
            color: #666;
        }
        .sidebar-menu li > a:hover {
            background: #f5f5f5;
            border-radius: 6px;
        }
        .sidebar-menu li > a.active {
            background: #e0ebff;
            color: #069797;
            font-weight: 600;
            border-radius: 6px;
        }
        .sidebar-menu li > a.active i { color: #069797; }
        .submenu {
  list-style: none;
  padding-left: 0;
  margin: 0;
  display: none;
}
.submenu li a {
  display: flex;
  align-items: center;
  padding: 8px 40px;
  font-size: 13px;
  color: #444;
}
.submenu li a:hover {
  background: #f5f5f5;
  border-radius: 6px;
}

    /* Table */
    table {
        width: 100%;
        border-collapse: collapse;
        background: #fff;
        box-shadow: 0 2px 6px rgba(0,0,0,0.1);
    }
    th, td {
        border: 1px solid #ddd;
        padding: 10px;
        font-size: 14px;
        text-align: left;
    }
    th {
        background: #069797;
        color: #fff;
    }
    tr:hover { background: #f9f9f9; }

    /* Filter */
    .filter-bar {
        margin-bottom: 15px;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }
    select {
        padding: 6px 10px;
        border-radius: 5px;
        border: 1px solid #ccc;
        font-size: 14px;
        outline: none;
    }

    /* Status */
    .status {
        font-weight: 600;
        padding: 4px 8px;
        border-radius: 5px;
        text-transform: capitalize;
        font-size: 13px;
    }
    .status.menunggu_konfirmasi { background: #fff3cd; color: #856404; }
    .status.diterima { background: #d4edda; color: #155724; }
    .status.dipinjam { background: #cce5ff; color: #004085; }
    .status.dikembalikan { background: #e2e3e5; color: #383d41; }
    .status.ditolak { background: #f8d7da; color: #721c24; }

    /* Tombol aksi */
    .aksi { white-space: nowrap; text-align: center; }
    .btn {
        padding: 6px 10px;
        font-size: 13px;
        border-radius: 5px;
        border: 1px solid transparent;
        cursor: pointer;
        font-weight: 500;
        transition: 0.2s ease;
    }
    .btn-accept { background: #e0f7f7; color: #069797; border: 1px solid #06a0a0; }
    .btn-accept:hover { background: #06a0a0; color: #fff; }
    .btn-reject { background: #ffe6e6; color: #c00; border: 1px solid #e55; }
    .btn-reject:hover { background: #c00; color: #fff; }
    .btn-mark { background: #e0ebff; color: #004085; border: 1px solid #99c; }
    .btn-mark:hover { background: #004085; color: #fff; }
    .btn-return { background: #e2e3e5; color: #383d41; border: 1px solid #bbb; }
    .btn-return:hover { background: #383d41; color: #fff; }

    /* Footer */
    footer {
        background: #fff;
        border-top: 1px solid #ddd;
        padding: 15px 30px;
        font-size: 14px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-top: auto;
        margin-left: 250px;
        color: #555;
    }
    @media (max-width: 900px){
  .filter-bar form { gap: 8px; }
}

</style>
</head>
<body>
<div class="container">
    <!-- SIDEBAR -->
<aside class="sidebar">
  <div class="sidebar-header">
    <h2>📚 Pustakaia</h2>
    <p>Admin Panel</p>
  </div>

  <ul class="sidebar-menu">
    <li><a href="dsadmin.php"><i class="fa fa-tachometer-alt"></i> Dashboard</a></li>

    <li class="has-submenu">
      <a href="#"><i class="fa fa-book"></i> Kelola Buku</a>
      <ul class="submenu">
        <li><a href="daftarbuku.php"><i class="fa fa-list"></i> Daftar Buku</a></li>
        <li><a href="add_book.php"><i class="fa fa-plus"></i> Tambahkan Buku</a></li>
      </ul>
    </li>

    <li class="has-submenu">
      <a href="#"><i class="fa fa-users"></i> Kelola Anggota</a>
      <ul class="submenu">
        <li><a href="daftaranggota.php"><i class="fa fa-list"></i> Daftar Anggota</a></li>
        <li><a href="add_anggota.php"><i class="fa fa-user-plus"></i> Tambahkan Anggota</a></li>
      </ul>
    </li>

    <!-- Ini item aktif -->
    <li><a href="borrow_requests.php" class="active"><i class="fa fa-exchange-alt"></i> Kelola Peminjaman</a></li>
  </ul>

  <hr>

  <ul class="sidebar-menu">
    <li><a href="#"><i class="fa fa-cog"></i> Pengaturan</a></li>
    <li><a href="../index2.php"><i class="fa fa-sign-out-alt"></i> Keluar</a></li>
  </ul>
</aside>

    <!-- Main -->
    <main>
        <h1>Kelola Peminjaman</h1>

        <form method="GET" style="display:flex; gap:10px; align-items:center; width:100%; flex-wrap:wrap;">
  <!-- Kolom search (dipendekkan) -->
  <div style="display:flex; gap:5px; align-items:center; flex:0 0 380px; max-width:100%;">
    <input type="text" name="search" placeholder="Cari nama/judul/no buku/rak..."
           value="<?= htmlspecialchars($_GET['search'] ?? '') ?>"
           style="flex:1; padding:6px 10px; border:1px solid #ccc; border-radius:5px; min-width:200px;">
    <button type="submit"
            style="padding:6px 12px; border:none; background:#069797; color:#fff; border-radius:5px; cursor:pointer;">
      <i class="fa fa-search"></i> Cari
    </button>
  </div>

  <!-- Status -->
  <div>
    <label for="status">Status:</label>
    <select name="status" id="status" onchange="this.form.submit()"
            style="padding:6px 10px; border-radius:5px; border:1px solid #ccc;">
      <option value="semua" <?= $status_filter === 'semua' ? 'selected' : '' ?>>Semua</option>
      <option value="menunggu_konfirmasi" <?= $status_filter === 'menunggu_konfirmasi' ? 'selected' : '' ?>>Menunggu Konfirmasi</option>
      <option value="diterima" <?= $status_filter === 'diterima' ? 'selected' : '' ?>>Diterima</option>
      <option value="dipinjam" <?= $status_filter === 'dipinjam' ? 'selected' : '' ?>>Dipinjam</option>
      <option value="dikembalikan" <?= $status_filter === 'dikembalikan' ? 'selected' : '' ?>>Dikembalikan</option>
      <option value="ditolak" <?= $status_filter === 'ditolak' ? 'selected' : '' ?>>Ditolak</option>
    </select>
  </div>

  <!-- Filter tanggal -->
  <div style="display:flex; gap:6px; align-items:center;">
    <label for="date" style="white-space:nowrap;">Tanggal:</label>
    <input type="date" id="date" name="date"
           value="<?= htmlspecialchars($filter_date ?: '') ?>"
           style="padding:6px 10px; border:1px solid #ccc; border-radius:5px;">

    <select name="date_type" id="date_type"
            style="padding:6px 10px; border-radius:5px; border:1px solid #ccc;"
            onchange="this.form.submit()">
      <option value="all"         <?= ($date_type==='all' ? 'selected' : '') ?>>Semua tanggal</option>
      <option value="pinjam"      <?= ($date_type==='pinjam' ? 'selected' : '') ?>>Tgl Pinjam</option>
      <option value="jatuh_tempo" <?= ($date_type==='jatuh_tempo' ? 'selected' : '') ?>>Jatuh Tempo</option>
      <option value="kembali"     <?= ($date_type==='kembali' ? 'selected' : '') ?>>Tgl Kembali</option>
    </select>
  </div>
</form>

        <!-- Table -->
        <table>
        <thead>
  <tr>
    <th>No</th>
    <th>Peminjam</th>
    <th>Judul Buku</th>
    <th>No Buku</th>
    <th>Rak</th>
    <th>Tgl Pinjam</th>
    <th>Jatuh Tempo</th>
    <th>Tgl Kembali</th>
    <th>Denda</th>
    <th>Durasi</th>
    <th>Bukti</th>
    <th>Bukti Pembayaran</th>
    <th>Terlambat</th>
    <th>Aksi</th>
    <th>Status</th>
  </tr>
</thead>
<tbody>
<?php if (!empty($borrowings)): ?>
  <?php $no = 1; foreach ($borrowings as $row): ?>
    <?php
      // 1) Hitung durasi & keterlambatan dulu
      $durasi_hari = isset($row['durasi_hari'])
        ? (int)$row['durasi_hari']
        : ((isset($row['tgl_pinjam'],$row['tgl_jatuh_tempo']) && $row['tgl_pinjam'] && $row['tgl_jatuh_tempo'])
            ? (int)((strtotime($row['tgl_jatuh_tempo']) - strtotime($row['tgl_pinjam'])) / 86400)
            : null);
    
      $overdue_days = isset($row['overdue_days'])
        ? (int)$row['overdue_days']
        : ((isset($row['tgl_jatuh_tempo']) && $row['tgl_jatuh_tempo'])
            ? max((int)((time() - strtotime($row['tgl_jatuh_tempo'])) / 86400), 0)
            : 0);
    
      $isLate = (strtolower($row['status']) === 'dipinjam' && $overdue_days > 0);
    
      // 2) Data WhatsApp
      //    -> pastikan di SELECT sudah: u.phone AS wa_number
      $wa_number = !empty($row['wa_number']) ? $row['wa_number'] : null;
    
      // format tanggal jatuh tempo (misal 05-11-2025)
      $tempo_fmt = !empty($row['tgl_jatuh_tempo'])
          ? date('d-m-Y', strtotime($row['tgl_jatuh_tempo']))
          : null;
    
      // sisa hari menuju jatuh tempo
      $sisa_hari = isset($row['sisa_hari'])
          ? (int)$row['sisa_hari']
          : (
              !empty($row['tgl_jatuh_tempo'])
                  ? (int)floor((strtotime($row['tgl_jatuh_tempo']) - strtotime(date('Y-m-d'))) / 86400)
                  : null
            );
    
      // 3) Bangun pesan WA (dasar)
      $msg_status = build_status_message(
        $row['nama_user'] ?? 'Peminjam',
        $row['judul_buku'] ?? 'Buku',
        strtolower($row['status']),
        $tempo_fmt
      );
    
      $msg_h1 = build_reminder_message(
        $row['nama_user'] ?? 'Peminjam',
        $row['judul_buku'] ?? 'Buku',
        'H-1',
        $tempo_fmt ?? '-'
      );
    
      $msg_overdue = build_reminder_message(
        $row['nama_user'] ?? 'Peminjam',
        $row['judul_buku'] ?? 'Buku',
        'OVERDUE',
        $tempo_fmt ?? '-'
      );
    
      // === Denda dinamis untuk OVERDUE ===
      // Ambil dari config FINE_PER_DAY jika ada, fallback 1000
      $DAILY_FINE = defined('FINE_PER_DAY') ? (int)FINE_PER_DAY : 1000;
    
      $overdue_days_int = max((int)$overdue_days, 0);
      if ($overdue_days_int > 0) {
        $total_fine = $overdue_days_int * $DAILY_FINE;
        $daily_fine_fmt = 'Rp ' . number_format($DAILY_FINE, 0, ',', '.');
        $total_fine_fmt = 'Rp ' . number_format($total_fine, 0, ',', '.');
    
        // Tambah info denda ke pesan WA Telat
        $msg_overdue .= "\n\n📅 Buku terlambat {$overdue_days_int} hari."
                      . "\n💰 Denda sementara: {$total_fine_fmt}"
                      . "\n(Bertambah {$daily_fine_fmt} per hari hingga buku dikembalikan)";
      }
      // === akhir denda dinamis ===
    
      // 4) Buat link wa.me
      $wa_link_status  = $wa_number ? wa_deeplink($wa_number, $msg_status)   : null;
      $wa_link_h1      = $wa_number ? wa_deeplink($wa_number, $msg_h1)       : null;
      $wa_link_overdue = $wa_number ? wa_deeplink($wa_number, $msg_overdue)  : null;
    
      // 5) Aturan tampil tombol
      $boleh_h1 = (strtolower($row['status']) === 'dipinjam' && $sisa_hari === 1);
      $boleh_overdue = (strtolower($row['status']) === 'dipinjam' && $overdue_days > 0);
    ?>
    
    <tr>
      <td><?= $no++ ?></td>
      <td><?= htmlspecialchars($row['nama_user']) ?></td>
      <td><?= htmlspecialchars($row['judul_buku']) ?></td>
      <td><?= htmlspecialchars($row['no_buku']) ?></td>
      <td><?= htmlspecialchars($row['rak']) ?></td>

      <td><?= htmlspecialchars($row['tgl_pinjam'] ?? '-') ?></td>

      <td style="<?= $isLate ? 'color:#c00;font-weight:700;' : '' ?>">
        <?= htmlspecialchars($row['tgl_jatuh_tempo'] ?? '-') ?>
      </td>

      <td><?= htmlspecialchars($row['tgl_kembali'] ?? '-') ?></td>

      <!-- ⇩ Urutan disamakan dengan THEAD: Denda → Durasi → Bukti → Terlambat -->
      <td>
        <?= !empty($row['denda']) && $row['denda'] > 0
          ? 'Rp ' . number_format((int)$row['denda'], 0, ',', '.')
          : '-' ?>
      </td>

      <td><?= is_null($durasi_hari) ? '-' : $durasi_hari . ' hari' ?></td>

      <td>
        <?php if (!empty($row['bukti_path'])): ?>
          <a href="<?= htmlspecialchars($row['bukti_path']) ?>" target="_blank" rel="noopener">Lihat Bukti</a>
        <?php else: ?>
          -
        <?php endif; ?>
      </td>

      
      <td>
  <?php
    $paid_and_has_proof = (
      (isset($row['denda_bayar']) && (int)$row['denda_bayar'] > 0)
      || !empty($row['bukti_denda_path'])
    );

    if (strtolower($row['status']) === 'dikembalikan' && $paid_and_has_proof) {
      $receipt_url = "payment_receipt.php?id=" . (int)$row['borrow_id'];
      // Ganti label tombol jadi "Kwitansi" seperti maumu
      echo '<a class="btn btn-mark" href="'.htmlspecialchars($receipt_url).'" target="_blank" rel="noopener noreferrer" title="Lihat & Cetak Kwitansi">
              <i class="fa fa-file-invoice"></i> Kwitansi
            </a>';

      if (!empty($row['bukti_denda_path'])) {
        echo '<div style="margin-top:6px;">
                <a class="btn btn-accept" href="'.htmlspecialchars($row['bukti_denda_path']).'" target="_blank" rel="noopener">Lihat Bukti</a>
              </div>';
      }
    } else {
      // Opsional: tombol upload bukti saat sudah dikembalikan tapi belum ada bukti
      if (strtolower($row['status']) === 'dikembalikan' && $overdue_days > 0) {
        $upload_url = "upload_payment_proof.php?id=" . (int)$row['borrow_id'];
        echo '<a class="btn btn-reject" href="'.htmlspecialchars($upload_url).'" title="kwintasi">
                <i class="fa fa-upload"></i> Upload Bukti
              </a>';
      } else {
        echo '-';
      }
    }
  ?>
</td>
<td><?= $overdue_days > 0 ? "<span style='color:#c00;font-weight:700;'>{$overdue_days} hari</span>" : '-' ?></td>
      <td class="aksi">
  <!-- Form ubah status (punyamu) -->
  <form method="GET" action="update_borrow_status.php" style="margin:0;">
    <input type="hidden" name="id" value="<?= (int)$row['borrow_id'] ?>">
    <select name="status" onchange="this.form.submit()"
            style="padding:4px 6px; border-radius:4px; font-size:13px;">
      <?php foreach (['menunggu_konfirmasi','diterima','dipinjam','dikembalikan','ditolak'] as $st): ?>
        <option value="<?= $st ?>" <?= $st === $row['status'] ? 'selected' : '' ?>>
          <?= ucfirst($st) ?>
        </option>
      <?php endforeach; ?>
    </select>
  </form>

  <!-- Tombol WA: Status (selalu ada kalau nomor WA tersedia) -->
  <?php if ($wa_link_status): ?>
    <div style="margin-top:6px;">
      <a class="btn btn-mark" href="<?= htmlspecialchars($wa_link_status) ?>" target="_blank" rel="noopener noreferrer" title="Kirim status via WhatsApp">
        <i class="fa-brands fa-whatsapp"></i> WA Status
      </a>
    </div>
  <?php else: ?>
    <div style="margin-top:6px; font-size:12px; color:#b00;">No WA kosong</div>
  <?php endif; ?>

  <!-- Tombol WA: H-1 -->
  <?php if ($wa_link_h1 && $boleh_h1): ?>
    <div style="margin-top:6px;">
      <a class="btn btn-accept" href="<?= htmlspecialchars($wa_link_h1) ?>" target="_blank" rel="noopener noreferrer" title="Pengingat H-1">
        <i class="fa-brands fa-whatsapp"></i> WA H-1
      </a>
    </div>
  <?php endif; ?>

  <!-- Tombol WA: Telat -->
  <?php if ($wa_link_overdue && $boleh_overdue): ?>
    <div style="margin-top:6px;">
      <a class="btn btn-reject" href="<?= htmlspecialchars($wa_link_overdue) ?>" target="_blank" rel="noopener noreferrer" title="Pengingat Telat">
        <i class="fa-brands fa-whatsapp"></i> WA Telat
      </a>
    </div>
  <?php endif; ?>
</td>


      <td>
        <span class="status <?= htmlspecialchars(strtolower($row['status'])) ?>">
          <?= htmlspecialchars($row['status']) ?>
        </span>
      </td>
    </tr>
  <?php endforeach; ?>
<?php else: ?>
  <tr><td colspan="14" style="text-align:center;">Tidak ada data peminjaman.</td></tr>
<?php endif; ?>
</tbody>
        </table>
    </main>
</div>

<footer>
    <div>© <?= date('Y') ?>, Pustakaia | Website developed by Grup 3</div>
    <div class="footer-right">
        <a href="#">Terms of Use</a>
        <a href="#">Privacy Policy</a>
    </div>
</footer>

<script>
document.querySelectorAll('.has-submenu > a').forEach(menu => {
    menu.addEventListener('click', e => {
        e.preventDefault();
        const submenu = menu.nextElementSibling;
        submenu.style.display = submenu.style.display === 'block' ? 'none' : 'block';
    });
});
</script>
</body>
</html>
