<?php
session_start();
ob_start();
include "../include/config.php";

// Check if user is logged in
if (!isset($_SESSION['email'])) {
    header("location:../index.php");
    exit();
}

$userlogin = $_SESSION['email'];
$email = $_SESSION['email'];

// Handle book addition
$message = "";
if (isset($_POST['add_book'])) {
    $title = $_POST['title'];
    $author = $_POST['author'];
    $category = $_POST['category'];
    $description = $_POST['description'];
    
    // Handle file upload
    $cover = "";
    if (!empty($_FILES['cover']['name'])) {
        $target_dir = "cover/";
        $cover = basename($_FILES["cover"]["name"]);
        $target_file = $target_dir . $cover;
        move_uploaded_file($_FILES["cover"]["tmp_name"], $target_file);
    }
    
    // Handle PDF upload
    $file = "";
    if (!empty($_FILES['file']['name'])) {
        $target_dir = "library/";
        $file = basename($_FILES["file"]["name"]);
        $target_file = $target_dir . $file;
        move_uploaded_file($_FILES["file"]["tmp_name"], $target_file);
    }
    
    // Insert into database
    $sql = "INSERT INTO library (title, author, category, description, cover, file) 
            VALUES ('$title', '$author', '$category', '$description', '$cover', '$file')";
    
    if ($conn->query($sql)) {
        $message = "<p style='color:green;'>Book added successfully!</p>";
        header("Location: elibray.php?success=Book added successfully");
    } else {
        $message = "<p style='color:red;'>Error: " . $conn->error . "</p>";
    }
}

// Handle book deletion
if (isset($_GET['delete'])) {
    $id = intval($_GET['delete']);
    $conn->query("DELETE FROM library WHERE id = $id");
    header("Location: elibray.php?success=Book deleted successfully");
    exit();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Library Management</title>
    <link rel="stylesheet" href="../../boostrap/1.css">
    <link rel="stylesheet" href="../../boostrap/2.css">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@300&family=Source+Sans+Pro:wght@300&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <link rel="icon" href="favicon.png" type="image/png">
    <meta name="theme-color" content="var(--primary)">
    <script src='https://kit.fontawesome.com/a076d05399.js' crossorigin='anonymous'></script>
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-Fy6S3B9q64WdZWQUiU+q4/2Lc9npb8tCaSX9FK7E8HnRr0Jz8D6OP9dO5Vg3Q9ct" crossorigin="anonymous"></script>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css" integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N" crossorigin="anonymous">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Signika+Negative:wght@300..700&display=swap" rel="stylesheet">
  
</head>
<style>
    body {
        padding: 0px;
        margin: 0px;
        font-size: 16px;
        width: 100%;
        background: white;
        font-family: 'Source Sans Pro', sans-serif;
    }
    nav {
        background: var(--primary);
        line-height: 60px;
    }
    nav a {
        color: white;
        text-decoration: none;
    }
    .content {
        margin-left: 200px;
        padding: 20px;
    }
    .btn {
        background: var(--primary);
        border: none;
        border-radius: 2px;
        outline: none;
        color: white;
        padding: 8px 15px;
    }
    .btn:hover {
        background: #b02a37;
        color: white;
    }
    
    /* New book card style with image as background */
    .book-card {
        position: relative;
        height: 280px;
        width: 100%;
        border-radius: 8px;
        overflow: hidden;
        margin-bottom: 20px;
        box-shadow: 0 4px 8px rgba(0,0,0,0.1);
        transition: transform 0.3s;
    }
    .book-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 6px 12px rgba(0,0,0,0.15);
    }
    .book-cover {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        object-fit: cover;
        z-index: 1;
    }
    .book-overlay {
        position: absolute;
        bottom: 0;
        left: 0;
        width: 100%;
        background: linear-gradient(transparent, rgba(0,0,0,0.8));
        padding: 15px;
        color: white;
        z-index: 2;
    }
    .book-title {
        font-weight: bold;
        font-size: 1rem;
        margin-bottom: 5px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }
    .book-author {
        font-size: 0.85rem;
        opacity: 0.9;
        margin-bottom: 5px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }
    .book-category {
        background: rgba(208, 63, 77, 0.8);
        padding: 3px 8px;
        border-radius: 15px;
        font-size: 0.75rem;
        display: inline-block;
    }
    .book-actions {
        position: absolute;
        top: 10px;
        right: 10px;
        z-index: 3;
        opacity: 0;
        transition: opacity 0.3s;
    }
    .book-card:hover .book-actions {
        opacity: 1;
    }
    .btn-sm {
        padding: 4px 8px;
        font-size: 0.8rem;
        margin-bottom: 5px;
    }
    .search-box {
        margin-bottom: 20px;
    }
    @media only screen and (max-width: 768px) {
        .content {
            margin-left: 0;
        }
        .book-card {
            height: 240px;
        }
    }
</style>
<body>
<?php include "../include/nav.php";?>

<div class="content" style="padding:20px">

    <div class="d-flex justify-content-between align-items-center mb-4">
        <h3>E-book Management</h3>
        <button class="btn" data-toggle="modal" data-target="#addBookModal">
            <i class="fa fa-plus"></i> Add New Book
        </button>
    </div>

    <?php if (isset($_GET['success'])): ?>
        <div class="alert alert-success" style="text-align:center;">
            <p><i class="fa fa-check"></i> <?php echo $_GET['success']; ?></p>
        </div>
    <?php endif; ?>

    <?php if (isset($_GET['error'])): ?>
        <div class="alert alert-danger" style="text-align:center;">
            <p><i class="fa fa-exclamation-circle"></i> <?php echo $_GET['error']; ?></p>
        </div>
    <?php endif; ?>

    <!-- Search Box -->
    <div class="search-box">
        <input type="text" id="bookSearch" class="form-control" placeholder="Search books by title, author, or category...">
    </div>

    <!-- Books Grid -->
    <div class="row" id="booksContainer">
        <?php
        $sql = "SELECT * FROM library ORDER BY added_on DESC";
        $result = $conn->query($sql);
        
        if ($result->num_rows > 0) {
            while($row = $result->fetch_assoc()) {
                $cover_path = !empty($row['cover']) ? "cover/" . $row['cover'] : "https://via.placeholder.com/300x400/333/fff?text=No+Cover";
                $file_path = !empty($row['file']) ? "library/" . $row['file'] : "#";
                ?>
                <div class="col-xl-3 col-lg-3 col-md-3 col-sm-3 mb-3 book-item">
                    <div class="book-card">
                        <img src="<?php echo $cover_path; ?>" alt="Book Cover" class="book-cover" onerror="this.src='https://via.placeholder.com/300x400/333/fff?text=No+Cover'">
                        
                        <div class="book-actions">
                            <?php if (!empty($row['file'])): ?>
                                <a href="<?php echo $file_path; ?>" target="_blank" class="btn btn-sm btn-primary d-block">
                                    <i class="fa fa-book"></i>
                                </a>
                            <?php else: ?>
                                <span class="btn btn-sm btn-secondary d-block disabled">
                                    <i class="fa fa-book"></i>
                                </span>
                            <?php endif; ?>
                            <a href="?delete=<?php echo $row['id']; ?>" class="btn btn-sm btn-danger d-block" 
                               onclick="return confirm('Are you sure you want to delete this book?');">
                                <i class="fa fa-trash"></i>
                            </a>
                        </div>
                        
                        <div class="book-overlay">
                            <div class="book-title"><?php echo htmlspecialchars($row['title']); ?></div>
                            <div class="book-author"><?php echo htmlspecialchars($row['author']); ?></div>
                            <div class="book-category"><?php echo htmlspecialchars($row['category']); ?></div>
                        </div>
                    </div>
                </div>
                <?php
            }
        } else {
            echo '<div class="col-12 text-center text-muted"><p>No books found in the library.</p></div>';
        }
        ?>
    </div>
</div>

<!-- Add Book Modal -->
<div class="modal fade" id="addBookModal" tabindex="-1" role="dialog" aria-labelledby="addBookModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="addBookModalLabel">Add New Book</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <?php echo $message; ?>
                <form method="POST" enctype="multipart/form-data">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="title">Book Title *</label>
                                <input type="text" class="form-control" id="title" name="title" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="author">Author *</label>
                                <input type="text" class="form-control" id="author" name="author" required>
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="category">Category *</label>
                                <select class="form-control" id="category" name="category" required>
                                    <option value="">Select Category</option>
                                    <option value="Psychology">Psychology </option>
                                    <option value="Sociology">Sociology</option>
                                    <option value="Biochemistry">Biochemistry</option>
                                    <option value="Nursing education">Nursing education</option>
                                    <option value="Research">Research</option>
                                    <option value="Nursing practice">Nursing practice</option>
                                    <option value=" Fundamental of nursing"> Fundamental of nursing</option>
                                    <option value="Leadership and management ">Leadership and management </option>
                                    <option value="Pharmacology">Pharmacology</option>
                  <option value="Clinical medicine">Clinical medicine</option>    
                  <option value="Psychiatry">Psychiatry</option>
                   <option value="Surgery">Surgery</option>    
                  <option value="Geriatrics">Geriatrics</option>
                                    
                  <option value="Gynaecology">Gynaecology</option>    
                  <option value="Obstetrics">Obstetrics</option>
                   <option value="Pediatrics">Pediatrics</option>    
                  <option value="Fiction">Fiction</option>
                                    
                  <option value="Non fiction">Non fiction</option>    
                  <option value="Religious">Religious</option>
                  <option value="Immunology">Immunology</option>    
                  <option value="Communication skills and ICT
">Communication skills and ICT
</option>
                   <option value="Human anatomy and physiology">Human anatomy and physiology</option>    
                  <option value="Public health and epidemiology">Public health and epidemiology</option>
                                    
                  <option value="Zambian publication">Zambian publication</option>    
                  <option value="Parasitology">Parasitology</option>
                   <option value="Hematology">Hematology</option>
                 
                                    
                                    
                                    
                                    <option value="Other">Other</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="cover">Book Cover Image</label>
                                <input type="file" class="form-control-file" id="cover" name="cover" accept="image/*">
                            </div>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label for="description">Description</label>
                        <textarea class="form-control" id="description" name="description" rows="3"></textarea>
                    </div>
                    
                    <div class="form-group">
                        <label for="file">Book File (PDF)</label>
                        <input type="file" class="form-control-file" id="file" name="file" accept=".pdf">
                    </div>
                    
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                        <button type="submit" name="add_book" class="btn btn-primary">Add Book</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
// Live search functionality
document.getElementById('bookSearch').addEventListener('keyup', function() {
    let filter = this.value.toLowerCase();
    let books = document.querySelectorAll('.book-item');
    
    books.forEach(book => {
        let title = book.querySelector('.book-title').textContent.toLowerCase();
        let author = book.querySelector('.book-author').textContent.toLowerCase();
        let category = book.querySelector('.book-category').textContent.toLowerCase();
        
        if (title.includes(filter) || author.includes(filter) || category.includes(filter)) {
            book.style.display = 'block';
        } else {
            book.style.display = 'none';
        }
    });
});
</script>

</body>
</html>