<?php
session_start();
require '../Login/config.php';

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

$user_id = $_SESSION['user_id'];
$book_id = intval($_GET['book_id'] ?? 0);
if ($book_id <= 0) {
  header("Location: borrowed_list.php");
  exit;
}

// Cek pinjaman yang masih bisa dibatalkan
$stmt = $pdo->prepare("
  SELECT br.id, br.status, bi.id AS item_id
  FROM borrowings br
  JOIN book_items bi ON br.book_item_id = bi.id
  WHERE br.user_id = :uid AND bi.book_id = :bid
  AND br.status IN ('menunggu_konfirmasi', 'diterima')
  LIMIT 1
");
$stmt->execute([':uid' => $user_id, ':bid' => $book_id]);
$borrow = $stmt->fetch(PDO::FETCH_ASSOC);

if ($borrow) {
  try {
    $pdo->beginTransaction();

    // Hapus data peminjaman
    $pdo->prepare("DELETE FROM borrowings WHERE id = ?")->execute([$borrow['id']]);

    // Kembalikan status item buku menjadi 'tersedia'
    $pdo->prepare("UPDATE book_items SET status = 'tersedia' WHERE id = ?")->execute([$borrow['item_id']]);

    $pdo->commit();

    header("Location: borrowed_list.php?success=Buku berhasil dibatalkan");
    exit;
  } catch (Exception $e) {
    $pdo->rollBack();
    header("Location: borrowed_list.php?error=Gagal membatalkan peminjaman");
    exit;
  }
} else {
  header("Location: borrowed_list.php?error=Peminjaman tidak dapat dibatalkan");
  exit;
}
?>
