<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);
include('includes/config.php');

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

$bookid = intval($_GET['bookid']);

// Fetch book details with is_deleted flags
$sql = "SELECT b.*, 
        c.CategoryName, c.is_deleted AS category_deleted,
        r.rack_no, r.shelf_no, r.floor,
        d.department_name, d.is_deleted AS department_deleted,
        p.PublisherName, p.is_deleted AS publisher_deleted,
        g.degree_name, g.is_deleted AS degree_deleted
        FROM tblbooks b
        LEFT JOIN tblcategory c ON c.id = b.CatId
        LEFT JOIN tblpublishers p ON p.id = b.Publisher
        LEFT JOIN tblbookcopies bc ON bc.book_id = b.id
        LEFT JOIN tbl_racks r ON r.id = bc.rack_id
        LEFT JOIN tbldepartment d ON d.department_id = b.department_id
        LEFT JOIN tbldegree g ON g.degree_id = b.degree_id
        WHERE b.id = :bookid";

$query = $dbh->prepare($sql);
$query->bindParam(':bookid', $bookid, PDO::PARAM_INT);
$query->execute();
$book = $query->fetch(PDO::FETCH_ASSOC);
// Fetch book copies (accession_no & cbrb_no)
$sqlCopies = "SELECT accession_no FROM tblbookcopies WHERE book_id = :bookid";
$queryCopies = $dbh->prepare($sqlCopies);
$queryCopies->bindParam(':bookid', $bookid, PDO::PARAM_INT);
$queryCopies->execute();
$copies = $queryCopies->fetchAll(PDO::FETCH_ASSOC);

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

// Fetch author names (with is_deleted flag)
$authorsList = [];
if (!empty($book['AuthorIds'])) {
    $authorIds = explode(',', $book['AuthorIds']);
    $placeholders = implode(',', array_fill(0, count($authorIds), '?'));
    $authorQuery = $dbh->prepare("SELECT AuthorName, is_deleted FROM tblauthors WHERE id IN ($placeholders)");
    $authorQuery->execute($authorIds);

    while ($row = $authorQuery->fetch(PDO::FETCH_ASSOC)) {
        $name = htmlentities($row['AuthorName']);
        if (!empty($row['is_deleted']) && $row['is_deleted'] == 1) {
            $name .= " <small class='text-muted'>(deleted)</small>";
        }
        $authorsList[] = $name;
    }
}
$authorsDisplay = !empty($authorsList) ? implode(', ', $authorsList) : 'N/A';
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>View Book | Library System</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="icon" type="image/x-icon" href="../<?php echo $_SESSION['logo']; ?>">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">

    <style>
        .square-card {
            background-color: #f8f9fa;
            border: 1px solid #dee2e6;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.05);
            border-radius: 5px;
        }

        .form-label {
            font-weight: 600;
        }

        .main-content {
            margin-left: 180px;
            margin-top: 50px;
            padding: 20px;
        }

        .header-line {
            color: #2258d5;
            font-size: 20px;
            font-weight: 600;
            margin-bottom: 20px;
        }

        small.text-muted {
            opacity: 0.7;
            font-style: italic;
        }
    </style>
</head>

<body>
    <div class="d-flex flex-column min-vh-100">
        <?php include('includes/header.php'); ?>

        <div class="main-content flex-grow-1">
            <div class="row mb-4">
                <div class="col-md-12">
                    <h5 class="header-line"><i class="fas fa-book mr-2"></i>View Book Details</h5>
                </div>
            </div>

            <div class="row justify-content-center">
                <div class="col-lg-6 col-md-8 col-sm-10 mx-auto">
                    <div class="card square-card">
                        <div
                            class="card-header bg-secondary text-white d-flex justify-content-between align-items-center">
                            <div><i class="fas fa-info-circle mr-2"></i>Book Information</div>
                            <a href="manage-books.php" class="btn btn-light btn-sm">
                                <i class="fa fa-arrow-left"></i> Back
                            </a>
                        </div>

                        <div class="card-body">
                            <table class="table table-bordered table-striped">
                                <tr>
                                    <th>Book Name</th>
                                    <td><?= htmlentities($book['BookName'] ?? '') ?></td>
                                </tr>

                                <tr>
                                    <th>Category</th>
                                    <td>
                                        <?= htmlentities($book['CategoryName'] ?? '') ?>
                                        <?php if (!empty($book['category_deleted']) && $book['category_deleted'] == 1): ?>
                                            <small class="text-muted">(deleted)</small>
                                        <?php endif; ?>
                                    </td>
                                </tr>

                                <tr>
                                    <th>Authors</th>
                                    <td><?= $authorsDisplay ?></td>
                                </tr>

                                <tr>
                                    <th>ISBN Number</th>
                                    <td><?= htmlentities($book['ISBNNumber'] ?? '') ?></td>
                                </tr>

                                <tr>
                                    <th>Edition</th>
                                    <td><?= htmlentities($book['Edition'] ?? '') ?></td>
                                </tr>

                                <tr>
                                    <th>Volume</th>
                                    <td><?= htmlentities($book['Volume'] ?? '') ?></td>
                                </tr>

                                <tr>
                                    <th>Publisher</th>
                                    <td>
                                        <?= htmlentities($book['PublisherName'] ?? '') ?>
                                        <?php if (!empty($book['publisher_deleted']) && $book['publisher_deleted'] == 1): ?>
                                            <small class="text-muted">(deleted)</small>
                                        <?php endif; ?>
                                    </td>
                                </tr>

                                <tr>
                                    <th>Publication Year</th>
                                    <td><?= htmlentities($book['PublicationYear'] ?? '') ?></td>
                                </tr>

                                <!-- <tr>
                                    <th>CBRB No(s)</th>
                                    <td>
                                        <?php
                                        // if (!empty($copies)) {
                                        //     $cbrbNos = array_column($copies, 'cbrb_no');
                                        //     echo htmlentities(implode(', ', $cbrbNos));
                                        // } else {
                                        //     echo 'N/A';
                                        // }
                                        ?>
                                    </td>
                                </tr> -->

                                <tr>
                                    <th>Accession No(s)</th>
                                    <td>
                                        <?php
                                        if (!empty($copies)) {
                                            $accessionNos = array_column($copies, 'accession_no');
                                            echo htmlentities(implode(', ', $accessionNos));
                                        } else {
                                            echo 'N/A';
                                        }
                                        ?>
                                    </td>
                                </tr>


                                <tr>
                                    <th>Number of Copies</th>
                                    <td><?= htmlentities($book['total_count'] ?? '') ?></td>
                                </tr>

                                <tr>
                                    <th>Available Copies</th>
                                    <td><?= htmlentities($book['current_count'] ?? '') ?></td>
                                </tr>

                                <tr>
                                    <th>Price per Book</th>
                                    <td><?= htmlentities($book['BookPrice'] ?? '') ?></td>
                                </tr>

                                <tr>
                                    <th>Total Price</th>
                                    <td><?= htmlentities($book['total_price'] ?? '') ?></td>
                                </tr>

                                <tr>
                                    <th>Purchase Date</th>
                                    <td><?= htmlentities($book['PurchaseDate'] ?? '') ?></td>
                                </tr>

                                <!-- <tr>
                                    <th>Cupboard Info</th>
                                    <td>
                                        Cupboard: <?= htmlentities($book['rack_no'] ?? '') ?> |
                                        Shelf: <?= htmlentities($book['shelf_no'] ?? '') ?> |
                                        Book: <?= htmlentities($book['floor'] ?? '') ?>
                                    </td>
                                </tr> -->

                                <tr>
                                    <th>Department</th>
                                    <td>
                                        <?= htmlentities($book['department_name'] ?? '') ?>
                                        <?php if (!empty($book['department_deleted']) && $book['department_deleted'] == 1): ?>
                                            <small class="text-muted">(deleted)</small>
                                        <?php endif; ?>
                                    </td>
                                </tr>

                                <tr>
                                    <th>Degree</th>
                                    <td>
                                        <?= htmlentities($book['degree_name'] ?? '') ?>
                                        <?php if (!empty($book['degree_deleted']) && $book['degree_deleted'] == 1): ?>
                                            <small class="text-muted">(deleted)</small>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <?php include('includes/footer.php'); ?>
</body>

</html>