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

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

$user_id = $_SESSION['user_id'];
$book_id = intval($_POST['book_id'] ?? 0);
$rating = intval($_POST['rating'] ?? 0);
$komentar = trim($_POST['komentar'] ?? '');

if ($book_id <= 0 || $rating < 1 || $rating > 5) {
  die("Data tidak valid.");
}

// Pastikan user sudah kembalikan buku ini
$stmt = $pdo->prepare("
  SELECT COUNT(*) 
  FROM borrowings br
  JOIN book_items bi ON br.book_item_id = bi.id
  WHERE br.user_id = ? AND bi.book_id = ? AND br.status = 'dikembalikan'
");
$stmt->execute([$user_id, $book_id]);
if ($stmt->fetchColumn() == 0) {
  die("Kamu belum bisa memberi ulasan untuk buku ini.");
}

// Pastikan belum pernah review
$stmt = $pdo->prepare("SELECT COUNT(*) FROM reviews WHERE user_id = ? AND book_id = ?");
$stmt->execute([$user_id, $book_id]);
if ($stmt->fetchColumn() > 0) {
  die("Kamu sudah menulis ulasan untuk buku ini.");
}

// Simpan ulasan
$stmt = $pdo->prepare("INSERT INTO reviews (user_id, book_id, rating, komentar) VALUES (?, ?, ?, ?)");
$stmt->execute([$user_id, $book_id, $rating, $komentar]);

header("Location: borrowed_list.php?success=ulasan_tersimpan");
exit;
?>
