<?php
session_start();
include('includes/config.php');
date_default_timezone_set('Asia/Kolkata');

if (strlen($_SESSION['alogin']) == 0) {
    header('location:index.php');
    exit;
}

$id = isset($_GET['id']) ? (int) $_GET['id'] : 0;
$bookid = isset($_GET['bookid']) ? (int) $_GET['bookid'] : 0;

if ($id <= 0 || $bookid <= 0) {
    die('Invalid request');
}

// Fetch book price before deleting copy
$getBookPrice = $dbh->prepare("SELECT BookPrice, total_price FROM tblbooks WHERE id=:bid");
$getBookPrice->bindParam(':bid', $bookid, PDO::PARAM_INT);
$getBookPrice->execute();
$bookData = $getBookPrice->fetch(PDO::FETCH_OBJ);

if (!$bookData) {
    $_SESSION['error'] = "Book not found.";
    header('location:manage-books.php');
    exit;
}

$bookPrice = (float) $bookData->BookPrice;
$totalPrice = (float) $bookData->total_price;

// Delete the copy
$del = $dbh->prepare("DELETE FROM tblbookcopies WHERE id=:id AND book_id=:bid");
$del->bindParam(':id', $id, PDO::PARAM_INT);
$del->bindParam(':bid', $bookid, PDO::PARAM_INT);
$del->execute();

// Recompute total_count and current_count for the parent book
$totQ = $dbh->prepare("SELECT COUNT(*) FROM tblbookcopies WHERE book_id=:bid");
$totQ->bindParam(':bid', $bookid, PDO::PARAM_INT);
$totQ->execute();
$totalCount = (int) $totQ->fetchColumn();

$availQ = $dbh->prepare("SELECT COUNT(*) FROM tblbookcopies WHERE book_id=:bid AND book_status='available'");
$availQ->bindParam(':bid', $bookid, PDO::PARAM_INT);
$availQ->execute();
$availableCount = (int) $availQ->fetchColumn();

// If NO copies left → DELETE book record
if ($totalCount === 0) {
    $deleteBook = $dbh->prepare("DELETE FROM tblbooks WHERE id=:bid");
    $deleteBook->bindParam(':bid', $bookid, PDO::PARAM_INT);
    $deleteBook->execute();

    $_SESSION['msg'] = "All copies deleted. Book record removed successfully.";
    header('location:manage-books.php');
    exit;
}
$updatedate = date('Y-m-d H:i:s');
// Otherwise → Update counts and reduce total price
$newTotalPrice = $totalPrice - $bookPrice;
if ($newTotalPrice < 0) {
    $newTotalPrice = 0; // Safety check
}

$upd = $dbh->prepare("UPDATE tblbooks 
                      SET total_count=:t, 
                          current_count=:c,
                          total_price=:p,
                          UpdationDate=:updatedate 
                      WHERE id=:bid");
$upd->bindParam(':t', $totalCount, PDO::PARAM_INT);
$upd->bindParam(':c', $availableCount, PDO::PARAM_INT);
$upd->bindParam(':p', $newTotalPrice, PDO::PARAM_STR);
$upd->bindParam(':bid', $bookid, PDO::PARAM_INT);
$upd->bindParam(':updatedate', $updatedate);

$upd->execute();

$_SESSION['msg'] = "Copy deleted successfully. Price updated.";
header('location:book-copies.php?bookid=' . $bookid);
exit;
?>