<?php
session_start();
require_once '../config/database.php';

// Check if user is logged in and has permission
if (!isset($_SESSION['user_id']) || ($_SESSION['user_role'] != 'admin' && $_SESSION['user_role'] != 'teacher')) {
    header('Location: ../login.php');
    exit();
}

$success_message = '';
$error_message = '';

// Handle book deletion
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['delete_book'])) {
    $book_id = (int)$_POST['book_id'];
    
    if ($book_id > 0) {
        try {
            // Check if the book has any active issues
            $stmt = $pdo->prepare("SELECT COUNT(*) FROM library_issues WHERE book_id = ? AND status = 'issued'");
            $stmt->execute([$book_id]);
            
            if ($stmt->fetchColumn() > 0) {
                $error_message = 'এই বইটি বর্তমানে ইস্যু করা আছে, তাই মুছে ফেলা যাবে না।';
            } else {
                $stmt = $pdo->prepare("DELETE FROM library_books WHERE id = ?");
                $stmt->execute([$book_id]);
                $success_message = 'বই সফলভাবে মুছে ফেলা হয়েছে।';
            }
        } catch (Exception $e) {
            $error_message = 'বই মুছতে সমস্যা হয়েছে: ' . $e->getMessage();
        }
    }
}

// Filtering and Pagination
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
$category_filter = isset($_GET['category']) ? trim($_GET['category']) : '';
$availability_filter = isset($_GET['availability']) ? trim($_GET['availability']) : '';

$limit = 20;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($page - 1) * $limit;

$where_clauses = [];
$params = [];

if ($search) {
    $where_clauses[] = "(title LIKE :search OR author LIKE :search OR isbn LIKE :search)";
    $params[':search'] = "%$search%";
}

if ($category_filter) {
    $where_clauses[] = "category = :category";
    $params[':category'] = $category_filter;
}

if ($availability_filter === 'available') {
    $where_clauses[] = "available_copies > 0";
} elseif ($availability_filter === 'unavailable') {
    $where_clauses[] = "available_copies <= 0";
}

$where_sql = count($where_clauses) > 0 ? 'WHERE ' . implode(' AND ', $where_clauses) : '';

// Get total book count for pagination
$stmt = $pdo->prepare("SELECT COUNT(*) FROM library_books $where_sql");
$stmt->execute($params);
$total_books = $stmt->fetchColumn();
$total_pages = ceil($total_books / $limit);

// Get books for the current page
$stmt = $pdo->prepare("SELECT * FROM library_books $where_sql ORDER BY title LIMIT :limit OFFSET :offset");
$stmt->bindParam(':limit', $limit, PDO::PARAM_INT);
$stmt->bindParam(':offset', $offset, PDO::PARAM_INT);
foreach ($params as $key => &$val) {
    $stmt->bindParam($key, $val);
}
$stmt->execute();
$books = $stmt->fetchAll();

// Get all categories for dropdown
$categories = $pdo->query("SELECT DISTINCT category FROM library_books WHERE category IS NOT NULL AND category != '' ORDER BY category")->fetchAll(PDO::FETCH_COLUMN);

?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>সব বই - লাইব্রেরি</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="../assets/css/style.css" rel="stylesheet">
</head>
<body>
    <!-- Navigation -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container-fluid">
            <a class="navbar-brand" href="../index.php"><i class="fas fa-graduation-cap"></i> স্কুল ম্যানেজমেন্ট সিস্টেম</a>
            <div class="navbar-nav ms-auto">
                <a class="nav-link" href="manage.php"><i class="fas fa-plus"></i> নতুন বই যোগ</a>
                <a class="nav-link" href="../logout.php"><i class="fas fa-sign-out-alt"></i> লগআউট</a>
            </div>
        </div>
    </nav>

    <div class="container-fluid mt-4">
        <div class="card">
            <div class="card-header">
                <div class="d-flex justify-content-between align-items-center">
                    <h5><i class="fas fa-books"></i> সব বইয়ের তালিকা</h5>
                    <a href="manage.php" class="btn btn-success"><i class="fas fa-plus"></i> নতুন বই যোগ করুন</a>
                </div>
            </div>
            <div class="card-body">
                <?php if ($success_message): ?>
                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                        <?php echo $success_message; ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                <?php endif; ?>
                <?php if ($error_message): ?>
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        <?php echo $error_message; ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    </div>
                <?php endif; ?>

                <!-- Search and Filter Form -->
                <form method="GET" action="" class="mb-4">
                    <div class="row g-3">
                        <div class="col-md-4">
                            <input type="text" name="search" class="form-control" placeholder="বইয়ের নাম, লেখক বা ISBN..." value="<?php echo htmlspecialchars($search); ?>">
                        </div>
                        <div class="col-md-3">
                            <select name="category" class="form-select">
                                <option value="">সব বিভাগ</option>
                                <?php foreach ($categories as $category): ?>
                                    <option value="<?php echo htmlspecialchars($category); ?>" <?php echo ($category_filter == $category) ? 'selected' : ''; ?>><?php echo htmlspecialchars($category); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <select name="availability" class="form-select">
                                <option value="">সব</option>
                                <option value="available" <?php echo ($availability_filter == 'available') ? 'selected' : ''; ?>>উপলব্ধ</option>
                                <option value="unavailable" <?php echo ($availability_filter == 'unavailable') ? 'selected' : ''; ?>>अनुपलब्ध</option>
                            </select>
                        </div>
                        <div class="col-md-2">
                            <button type="submit" class="btn btn-primary w-100"><i class="fas fa-search"></i> খুঁজুন</button>
                        </div>
                    </div>
                </form>

                <div class="table-responsive">
                    <table class="table table-bordered table-hover">
                        <thead class="table-light">
                            <tr>
                                <th>বইয়ের নাম</th>
                                <th>লেখক</th>
                                <th>বিভাগ</th>
                                <th>কপি (মোট/উপলব্ধ)</th>
                                <th>অবস্থান</th>
                                <th>কার্যক্রম</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($books)): ?>
                                <tr>
                                    <td colspan="6" class="text-center text-muted">কোন বই পাওয়া যায়নি।</td>
                                </tr>
                            <?php else: ?>
                                <?php foreach ($books as $book): ?>
                                    <tr>
                                        <td>
                                            <strong><?php echo htmlspecialchars($book['title']); ?></strong>
                                            <?php if ($book['isbn']): ?>
                                                <br><small class="text-muted">ISBN: <?php echo htmlspecialchars($book['isbn']); ?></small>
                                            <?php endif; ?>
                                        </td>
                                        <td><?php echo htmlspecialchars($book['author']); ?></td>
                                        <td><span class="badge bg-info"><?php echo htmlspecialchars($book['category']); ?></span></td>
                                        <td>
                                            <span class="badge bg-primary"><?php echo $book['total_copies']; ?></span> /
                                            <span class="badge <?php echo ($book['available_copies'] > 0) ? 'bg-success' : 'bg-danger'; ?>"><?php echo $book['available_copies']; ?></span>
                                        </td>
                                        <td><?php echo htmlspecialchars($book['location']); ?></td>
                                        <td>
                                            <div class="btn-group btn-group-sm">
                                                <a href="edit_book.php?id=<?php echo $book['id']; ?>" class="btn btn-warning" title="সম্পাদনা">
                                                    <i class="fas fa-edit"></i>
                                                </a>
                                                <form method="POST" action="" onsubmit="return confirm('আপনি কি নিশ্চিত যে এই বইটি মুছে ফেলতে চান?');" class="d-inline">
                                                    <input type="hidden" name="book_id" value="<?php echo $book['id']; ?>">
                                                    <button type="submit" name="delete_book" class="btn btn-danger" title="মুছে ফেলুন">
                                                        <i class="fas fa-trash"></i>
                                                    </button>
                                                </form>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>

                <!-- Pagination -->
                <?php if ($total_pages > 1): ?>
                <nav>
                    <ul class="pagination justify-content-center">
                        <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                            <li class="page-item <?php echo ($i == $page) ? 'active' : ''; ?>">
                                <a class="page-link" href="?page=<?php echo $i; ?>&search=<?php echo urlencode($search); ?>&category=<?php echo urlencode($category_filter); ?>&availability=<?php echo urlencode($availability_filter); ?>"><?php echo $i; ?></a>
                            </li>
                        <?php endfor; ?>
                    </ul>
                </nav>
                <?php endif; ?>

            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
