<?php
session_start();
require '../Login/config.php';
header('Content-Type: application/json; charset=utf-8');

if (!isset($_SESSION['user_id'])) {
  echo json_encode(['success'=>false,'message'=>'Silakan login.']);
  exit;
}
$user_id = $_SESSION['user_id'];
$input = json_decode(file_get_contents('php://input'), true);
$book_id = intval($input['book_id'] ?? 0);
if ($book_id <= 0) { echo json_encode(['success'=>false,'message'=>'ID buku tidak valid.']); exit; }

try {
  $stmt = $pdo->prepare("SELECT 1 FROM favorites WHERE user_id = ? AND book_id = ?");
  $stmt->execute([$user_id, $book_id]);
  if ($stmt->fetch()) {
    $pdo->prepare("DELETE FROM favorites WHERE user_id = ? AND book_id = ?")->execute([$user_id, $book_id]);
    echo json_encode(['success'=>true,'is_favorite'=>false,'message'=>'Dihapus dari favorit.']);
  } else {
    $pdo->prepare("INSERT INTO favorites (user_id, book_id) VALUES (?, ?)")->execute([$user_id, $book_id]);
    echo json_encode(['success'=>true,'is_favorite'=>true,'message'=>'Ditambahkan ke favorit.']);
  }
} catch (Exception $e) {
  error_log($e->getMessage());
  echo json_encode(['success'=>false,'message'=>'Terjadi kesalahan server.']);
}
