<?php
// ===========================
// 📄 borrowed_list.php (Versi Diperbaiki)
// ===========================

require __DIR__ . '/../Login/config.php';
if (session_status() === PHP_SESSION_NONE) {
  session_start();
}

// === CEK LOGIN ===
if (!isset($_SESSION['user_id'])) {
  header('Location: ../Login/login.php');
  exit;
}

$user_id = $_SESSION['user_id'];

// === FOTO PROFIL USER ===
$photoURL = "../uploads/default.jpg";
$stmtUser = $pdo->prepare("SELECT photo FROM users WHERE id = ?");
$stmtUser->execute([$user_id]);
$photo = $stmtUser->fetchColumn();
if (!empty($photo) && file_exists("../uploads/" . $photo)) {
  $photoURL = "../uploads/" . $photo;
}

// === AMBIL DATA PEMINJAMAN USER ===
$stmt = $pdo->prepare("
  SELECT 
    b.id AS book_id, 
    b.judul, 
    b.penulis, 
    b.gambar, 
    bi.no_buku, 
    bi.rak, 
    br.tgl_pinjam, 
    br.tgl_kembali, 
    br.tgl_jatuh_tempo,  -- 🟢 tambahkan baris ini
    GREATEST(DATEDIFF(CURDATE(), br.tgl_jatuh_tempo), 0) AS overdue_days,
    br.status
  FROM borrowings br
  JOIN book_items bi ON br.book_item_id = bi.id
  JOIN books b ON bi.book_id = b.id
  WHERE br.user_id = ?
  ORDER BY br.tgl_pinjam DESC
");
$stmt->execute([$user_id]);
$all_borrowed = $stmt->fetchAll(PDO::FETCH_ASSOC);

$active = [];
$returned = [];

foreach ($all_borrowed as $row) {
  if (in_array(strtolower($row['status']), ['menunggu_konfirmasi', 'diterima', 'dipinjam'])) {
    $active[] = $row;
  } elseif (strtolower($row['status']) === 'dikembalikan') {
    $returned[] = $row;
  }
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Buku yang Dipinjam | 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: linear-gradient(135deg, #f9f9f9, #e9f5ec);
      color: #222;
      overflow-x: hidden;
    }
    a { text-decoration: none; color: inherit; }

    /* === HEADER === */
    header {
      position: relative;
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 12px 25px;
      background: #fff;
      border-bottom: 1px solid #ddd;
      top: 0;
      z-index: 1000;
    }

    .left-header {
      display: flex;
      align-items: center;
      gap: 15px;
    }

    .hamburger {
      font-size: 28px;
      color: #069797;
      cursor: pointer;
      user-select: none;
      transition: color 0.3s;
    }

    .logo {
      font-size: 22px;
      font-weight: 600;
      color: #069797;
    }

    nav {
      display: flex;
      align-items: center;
      gap: 20px;
      position: relative;
    }

    /* === NOTIFIKASI === */
    .notif-wrapper {
      position: relative;
      display: inline-block;
    }

    .notif-icon {
      font-size: 22px;
      cursor: pointer;
      color: #069797;
      display: inline-flex;
      align-items: center;
      gap: 8px;
    }

    .notif-badge {
      background: red;
      color: #fff;
      border-radius: 50%;
      font-size: 12px;
      padding: 2px 6px;
      margin-left: 6px;
      display: none;
    }

    #notif-list {
      display: none;
      position: absolute;
      top: 60px; right: 0;
      background: #fff;
      border: 1px solid #ddd;
      box-shadow: 0 4px 12px rgba(0,0,0,0.1);
      width: 300px;
      border-radius: 10px;
      z-index: 1200;
      padding: 10px 15px;
    }

    #notif-list .notif-row {
      display: flex;
      gap: 10px;
      align-items: flex-start;
      padding: 8px 6px;
      border-radius: 6px;
    }

    #notif-list .notif-row + .notif-row { margin-top: 6px; }
    #notif-list .notif-row small { display:block; color:#777; font-size:12px; margin-top:4px; }

    .notif-wrapper.open #notif-list { display: block; }

    @media (max-width: 480px) {
      #notif-list { width: 90vw; right: 5vw; top: 56px; }
    }

    /* === SIDEBAR === */
    .sidebar {
      width: 250px;
      height: 100vh;
      background: #fff;
      border-right: 1px solid #ddd;
      position: fixed;
      top: 0; left: -100%;
      transition: left 0.3s ease;
      z-index: 1100;
      overflow-y: auto;
    }

    .sidebar.active { left: 0; }

    .sidebar-header {
  text-align: left;            /* 🔹 ubah dari center → left */
  padding: 20px 15px;
  border-bottom: 1px solid #ddd;
  
}
.sidebar-header .logo {
  font-size: 20px;
  font-weight: 600;
  color: #069797;
  margin-bottom: 12px;
  margin-left: 10px;            /* 🔹 tambahkan biar agak ke kanan dikit */
}
.sidebar-header img {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid #069797;
  margin-bottom: 8px;
  display: block;         /* 🔹 agar bisa diatur margin otomatis */
  margin-left: auto;      /* 🔹 ini membuat foto di tengah */
  margin-right: auto;     /* 🔹 ini juga */
}
    .sidebar-header .user-info { text-align: left; padding-left: 10px; }
    .sidebar-header h2 { margin: 0; font-size: 17px; color: #333; }
    .sidebar-header p { margin: 0; font-size: 13px; color: #777; }

    .sidebar-menu {
      list-style: none;
      padding: 0;
      margin: 10px 0;
    }

    .sidebar-menu li {
      padding: 12px 20px;
      font-size: 14px;
      color: #444;
      display: flex;
      align-items: center;
      cursor: pointer;
      transition: background 0.2s;
    }

    .sidebar-menu li i {
      margin-right: 10px;
      font-size: 16px;
      color: #666;
    }

    .sidebar-menu li:hover { background: #f5f5f5; }
    .sidebar-menu li.active {
      background: #e0ebff;
      color: #069797;
    }

    .sidebar-menu li.active i { color: #069797; }

    .overlay {
      position: fixed;
      top: 0; left: 0;
      width: 100%; height: 100%;
      background: rgba(0,0,0,0.5);
      display: none;
      z-index: 1050;
    }

    .overlay.active { display: block; }

    /* === KONTEN UTAMA === */
    .container {
      width: 95%;
      max-width: 1400px;
      margin: 100px auto;
      background: #fff;
      padding: 30px 50px;
      border-radius: 10px;
      box-shadow: 0 2px 10px rgba(0,0,0,0.05);
    }

    .container h2 {
      color: #069797;
      font-size: 24px;
      margin-bottom: 20px;
      font-weight: 600;
    }

    .borrowed-card {
      display: flex;
      gap: 20px;
      border: 1px solid #eee;
      border-radius: 8px;
      padding: 15px;
      margin-bottom: 20px;
      background: #fcfcfc;
      align-items: flex-start;
    }

    .borrowed-card img {
      width: 150px;
      height: 210px;
      object-fit: cover;
      border-radius: 6px;
      flex-shrink: 0;
      box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    }

    .borrowed-info { flex: 1; }

    .borrowed-info h3 {
      margin: 0;
      font-size: 18px;
      color: #069797;
    }

    .borrowed-info p {
      margin: 6px 0;
      color: #444;
      font-size: 14px;
    }

    .status {
  display: inline-block;
  padding: 6px 10px;
  border-radius: 6px;
  font-size: 13px;
  font-weight: 600;
  text-transform: capitalize;
  color: #222;
}

/* Warna berdasarkan status */
.status.menunggu_konfirmasi { background-color: #fff3cd; color: #856404; } /* 🟡 */
.status.diterima { background-color: #d4edda; color: #155724; } /* 🟢 */
.status.dipinjam { background-color: #cce5ff; color: #004085; } /* 🔵 */
.status.dikembalikan { background-color: #f8f9fa; color: #383d41; } /* ⚪ */
.status.ditolak { background-color: #f8d7da; color: #721c24; } /* 🔴 */


    .empty {
      text-align: center;
      color: #666;
      padding: 40px 0;
    }

    /* === FOOTER === */
    footer {
      background: #fff;
      margin-top: 40px;
      padding: 20px 40px;
      font-size: 14px;
      color: #222;
    }

    .footer-bottom {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-top: 15px;
      font-size: 13px;
      flex-wrap: wrap;
    }

    .footer-links a {
      margin-left: 15px;
      color: #222;
      font-weight: 500;
    }
    .btn-cancel {
  background: #ffdddd;
  color: #a00;
  border: 1px solid #cc0000;
  padding: 6px 12px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 13px;
  margin-left: 10px;
  transition: 0.2s;
}

.btn-cancel:hover {
  background: #ffcccc;
}
.cancel-link {
  color: #d33;
  font-size: 14px;
  font-weight: 500;
  margin-left: 10px;
  text-decoration: underline;
  cursor: pointer;
  transition: color 0.2s;
}

.cancel-link:hover {
  color: #a00;
}
<style>
.review-label {
  display: inline-block;
  background-color: #d4edda; /* hijau muda lembut */
  color: #155724;            /* teks hijau tua */
  font-weight: 600;
  font-size: 13px;
  padding: 4px 10px;
  border-radius: 6px;
  cursor: pointer;
  transition: background-color 0.2s ease;
}

.review-label:hover {
  background-color: #c3e6cb; /* sedikit lebih gelap saat hover */
}
  </style>
</head>
<body>

<!-- ===== SIDEBAR ===== -->
<aside class="sidebar" id="sidebar">
  <div class="sidebar-header">
    <div class="logo">📚 Pustakaia</div>
    <img src="<?= htmlspecialchars($photoURL) ?>" alt="Foto Profil">
    <div class="user-info">
      <h2><?= htmlspecialchars($_SESSION['fullname'] ?? 'Pengguna') ?></h2>
      <p><?= htmlspecialchars(ucfirst($_SESSION['role'] ?? 'User')) ?></p>
    </div>
  </div>
  <ul class="sidebar-menu">
    <li onclick="window.location.href='books.php'"><i class="fa fa-book"></i> Semua Buku</li>
    <li onclick="window.location.href='notifications_page.php'"><i class="fa fa-bell"></i> Notifikasi</li>
    <li onclick="window.location.href='favorites.php'"><i class="fa fa-heart"></i> Favorit</li>
    <li onclick="window.location.href='saved.php'"><i class="fa fa-bookmark"></i> Simpanan Saya</li>
    <li class="active"><i class="fa fa-book-reader"></i> Pinjaman Saya</li>
    <li><a href="library_card.php"><i class="fa fa-id-card"></i> Kartu Perpustakaan</li>
  </ul>
  <hr>
  <ul class="sidebar-menu">
    <li><a href="profile.php"><i class="fa fa-cog"></i> Pengaturan</a></li>
    <li onclick="window.location.href='../Login/Logout.php'"><i class="fa fa-sign-out-alt"></i> Keluar</li>
  </ul>
</aside>

<div class="overlay" id="overlay"></div>

<!-- ===== HEADER ===== -->
<header>
  <div class="left-header">
    <span class="hamburger" id="hamburger">☰</span>
    <div class="logo">📚 Pustakaia</div>
  </div>

  <nav>
    <div class="notif-wrapper" id="notif-wrapper">
      <div class="notif-icon" id="notif-btn">🔔 <span id="notif-count" class="notif-badge"></span></div>
      <div id="notif-list" aria-hidden="true">
        <div style="text-align:center; color:#777;">Memuat notifikasi...</div>
      </div>
    </div>
    <a href="../Login/Logout.php">Keluar</a>
  </nav>
</header>

<!-- ===== KONTEN UTAMA ===== -->
<div class="container">
  <h2>📖 Buku yang Sedang Dipinjam</h2>
  <?php if (count($active) === 0): ?>
    <div class="empty">Belum ada buku yang sedang kamu pinjam.</div>
  <?php else: ?>
    <?php foreach ($active as $row): ?>
      <div class="borrowed-card">
        <img src="<?= htmlspecialchars('../' . ($row['gambar'] ?: 'Uploads/default.png')) ?>" 
             alt="<?= htmlspecialchars($row['judul']) ?>">
        <div class="borrowed-info">
          <h3><?= htmlspecialchars($row['judul']) ?></h3>
          <p><strong><?= htmlspecialchars($row['penulis'] ?: '-') ?></strong></p>
          <p>No Buku: <?= htmlspecialchars($row['no_buku']) ?> | Rak: <?= htmlspecialchars($row['rak'] ?: '-') ?></p>
          <p>Tanggal Pinjam: 
            <?= !empty($row['tgl_pinjam']) 
              ? htmlspecialchars(date('d-m-Y', strtotime($row['tgl_pinjam']))) 
              : '-' ?>
          </p>

          <?php
            $status = strtolower($row['status']);
            $ket = '';

            switch ($status) {
              case 'menunggu_konfirmasi':
                $ket = 'Menunggu admin mengonfirmasi peminjaman.';
                break;
              case 'diterima':
                $ket = 'Silakan ke perpustakaan untuk mengambil buku Anda.';
                break;
                case 'dipinjam':
                  $tglJatuhTempo = !empty($row['tgl_jatuh_tempo'])
                      ? date('d-m-Y', strtotime($row['tgl_jatuh_tempo']))
                      : '-';
                
                  // 🔹 Coba ambil kolom overdue_days dari SQL (jika sudah ada)
                  $lateDays = (int)($row['overdue_days'] ?? 0);
                
                  // 🔹 Kalau belum ada di SQL, hitung manual
                  if (empty($lateDays) && !empty($row['tgl_jatuh_tempo'])) {
                      $due = new DateTime(date('Y-m-d', strtotime($row['tgl_jatuh_tempo'])));
                      $todayDt = new DateTime(date('Y-m-d'));
                      if ($todayDt > $due) {
                          $lateDays = $due->diff($todayDt)->days;
                      }
                  }
                
                  // 🔹 Hitung denda
                  $fine = $lateDays * 1000;
                
                  if ($lateDays > 0) {
                      $ket = "📅 Telat mengembalikan buku! Denda: Rp " . number_format($fine, 0, ',', '.') . " ({$lateDays} hari).";
                  } else {
                      $ket = "Buku harus dikembalikan sebelum tanggal {$tglJatuhTempo}.";
                  }
                  break;
              
              case 'dikembalikan':
                $ket = 'Buku telah dikembalikan. Klik untuk menambahkan ulasan.';
                break;
              case 'ditolak':
                $ket = 'Peminjaman ditolak oleh admin.';
                break;
              default:
                $ket = '-';
            }
          ?>

          <p>Status: <span class="status <?= htmlspecialchars($status) ?>">
            <?= ucfirst($status) ?>
          </span></p>
          <p><em><?= htmlspecialchars($ket) ?></em></p>

          <?php if (in_array($row['status'], ['menunggu_konfirmasi', 'diterima'])): ?>
            <a href="cancel_borrow.php?book_id=<?= $row['book_id'] ?>"
               onclick="return confirm('Yakin ingin membatalkan peminjaman buku ini?')"
               class="cancel-link">Batalkan</a>
          <?php endif; ?>

          <a href="detail.php?id=<?= $row['book_id'] ?>" class="btn">Lihat Detail</a>
        </div>
      </div>
    <?php endforeach; ?>
  <?php endif; ?>

  <!-- PEMBATAS -->
  <hr style="margin:40px 0;border:none;border-top:2px dashed #ccc;">

  <h2>📚 Buku yang Telah Dipinjam</h2>
  <?php if (count($returned) === 0): ?>
    <div class="empty">Belum ada buku yang sudah dikembalikan.</div>
  <?php else: ?>
    <?php foreach ($returned as $row): ?>
      <div class="borrowed-card">
        <img src="<?= htmlspecialchars('../' . ($row['gambar'] ?: 'Uploads/default.png')) ?>" 
             alt="<?= htmlspecialchars($row['judul']) ?>">
        <div class="borrowed-info">
          <h3><?= htmlspecialchars($row['judul']) ?></h3>
          <p><strong><?= htmlspecialchars($row['penulis'] ?: '-') ?></strong></p>
          <p>No Buku: <?= htmlspecialchars($row['no_buku']) ?> | Rak: <?= htmlspecialchars($row['rak'] ?: '-') ?></p>
          <p>Tanggal Pinjam: 
            <?= !empty($row['tgl_pinjam']) 
              ? htmlspecialchars(date('d-m-Y', strtotime($row['tgl_pinjam']))) 
              : '-' ?>
          </p>
          <p>Tanggal Kembali: 
            <?= !empty($row['tgl_kembali']) 
              ? htmlspecialchars(date('d-m-Y', strtotime($row['tgl_kembali']))) 
              : '-' ?>
          </p>

          <p>Status: <span class="status dikembalikan">Dikembalikan</span></p>
          <p><em>Buku telah dikembalikan. Klik untuk menambahkan ulasan.</em></p>
          <span 
  class="review-label"
  onclick="openReviewModal(<?= $row['book_id'] ?>, '<?= htmlspecialchars(addslashes($row['judul'])) ?>')">
  Tulis Ulasan
</span>

        </div>
      </div>
    <?php endforeach; ?>
  <?php endif; ?>
</div>
<!-- ===== FOOTER ===== -->
<footer>
  <hr style="border:none;border-top:1px solid #ddd;margin:20px 0 10px 0;width:100%;">
  <div class="footer-bottom">
    <p>© 2025, Pustakaia | Website developed by Grup 3</p>
    <div class="footer-links">
      <a href="#">Terms of Use</a>
      <a href="#">Privacy Policy</a>
    </div>
  </div>
</footer>
<!-- === POPUP REVIEW === -->
<div id="reviewModal" class="modal" style="
  display:none; position:fixed; top:0; left:0; width:100%; height:100%;
  background:rgba(0,0,0,0.6); z-index:2000; justify-content:center; align-items:center;
">
  <div style="
    background:#fff; border-radius:12px; padding:25px 30px; width:90%; max-width:450px;
    box-shadow:0 5px 20px rgba(0,0,0,0.2); position:relative;
  ">
    <h3 id="reviewTitle" style="margin-top:0; color:#069797;">Tulis Ulasan</h3>
    <form id="reviewForm">
      <input type="hidden" name="book_id" id="reviewBookId">

      <label>Rating:</label><br>
      <div id="ratingStars" style="font-size:22px; margin:5px 0;"></div>

      <input type="hidden" name="rating" id="ratingValue" value="0">

      <label for="komentar">Komentar:</label><br>
      <textarea name="komentar" id="komentar" rows="4" style="width:100%;resize:none;"></textarea><br><br>

      <button type="submit" style="
        background:#069797; color:#fff; border:none; padding:10px 18px;
        border-radius:8px; cursor:pointer;">Kirim</button>
      <button type="button" onclick="closeReviewModal()" style="
        background:#ccc; border:none; padding:10px 18px; border-radius:8px; margin-left:10px;
        cursor:pointer;">Batal</button>
    </form>
  </div>
</div>

<script>
/* === SIDEBAR TOGGLE === */
const sidebar = document.getElementById('sidebar');
const overlay = document.getElementById('overlay');
const hamburger = document.getElementById('hamburger');

hamburger.addEventListener('click', () => {
  sidebar.classList.add('active');
  overlay.classList.add('active');
});

overlay.addEventListener('click', () => {
  sidebar.classList.remove('active');
  overlay.classList.remove('active');
});

/* === NOTIFIKASI === */
const notifWrapper = document.getElementById('notif-wrapper');
const notifBtn = document.getElementById('notif-btn');
const notifList = document.getElementById('notif-list');
const notifCount = document.getElementById('notif-count');

notifBtn.addEventListener('click', (e) => {
  e.stopPropagation();
  notifWrapper.classList.toggle('open');
  fetch('read_notifications.php').catch(()=>{});
  notifCount.style.display = 'none';
});

document.addEventListener('click', (e) => {
  if (!notifWrapper.contains(e.target)) notifWrapper.classList.remove('open');
});

function loadNotifications() {
  fetch('notifications.php')
  .then(res => res.json())
  .then(data => {
    if (data.count && data.count > 0) {
      notifCount.style.display = 'inline-block';
      notifCount.textContent = data.count;
    } else notifCount.style.display = 'none';

    let html = '';
    if (data.notifications && data.notifications.length) {
      data.notifications.forEach(n => {
        html += `<div class="notif-row">
          <div style="font-size:18px;line-height:1;">📕</div>
          <div>
            <div style="font-size:13px;color:#222;">${escapeHtml(n.message)}</div>
            <small>${escapeHtml(n.created_at)}</small>
          </div>
        </div>`;
      });
      html += `<div style="padding-top:8px;border-top:1px solid #eee;margin-top:8px;"><a href="notifications_page.php">Lihat Selengkapnya →</a></div>`;
    } else {
      html = '<div style="text-align:center;color:#777;">Tidak ada notifikasi</div>';
    }
    notifList.innerHTML = html;
  })
  .catch(err => {
    notifList.innerHTML = '<div style="text-align:center;color:#777;">Gagal memuat notifikasi</div>';
    console.error(err);
  });
}

function escapeHtml(str) {
  if (!str) return '';
  return String(str).replace(/[&<>"']/g, m => ({
    '&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'
  }[m]));
}

loadNotifications();
// === POPUP REVIEW ===
function openReviewModal(bookId, title) {
  document.getElementById('reviewModal').style.display = 'flex';
  document.getElementById('reviewBookId').value = bookId;
  document.getElementById('reviewTitle').textContent = 'Tulis Ulasan untuk "' + title + '"';
  generateStars();
}

function closeReviewModal() {
  document.getElementById('reviewModal').style.display = 'none';
}

// === BINTANG RATING ===
function generateStars() {
  const ratingStars = document.getElementById('ratingStars');
  const ratingValue = document.getElementById('ratingValue');
  ratingStars.innerHTML = '';
  for (let i = 1; i <= 5; i++) {
    const star = document.createElement('span');
    star.textContent = '★';
    star.style.cursor = 'pointer';
    star.style.color = '#ccc';
    star.addEventListener('click', () => {
      ratingValue.value = i;
      document.querySelectorAll('#ratingStars span').forEach((s, idx) => {
        s.style.color = idx < i ? '#FFD700' : '#ccc';
      });
    });
    ratingStars.appendChild(star);
  }
}

// === AJAX KIRIM REVIEW ===
document.getElementById('reviewForm').addEventListener('submit', function(e) {
  e.preventDefault();

  const formData = new FormData(this);

  fetch('submit_review.php', {
    method: 'POST',
    body: formData
  })
  .then(res => res.text())
  .then(response => {
    alert(response);
    closeReviewModal();
  })
  .catch(err => {
    console.error(err);
    alert('Gagal mengirim ulasan.');
  });
});

</script>

</body>
</html>
