<?php
session_start();
ob_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);
include "../include/config.php";
$userlogin=$_SESSION['email'];
$role=$_SESSION['role'];

$intake=$_SESSION['department'];

if (isset($_SESSION['email'])){

// ✅ Delete book
if (isset($_GET['delete'])) {
    $id = intval($_GET['delete']);
    mysqli_query($conn, "DELETE FROM catalogue WHERE id=$id");
    $successMsg = "Book deleted successfully!";
}

// ✅ Update book
if (isset($_POST['update_catalogue'])) {
    $id       = intval($_POST['id']);
    $title    = mysqli_real_escape_string($conn, $_POST['title']);
    $author   = mysqli_real_escape_string($conn, $_POST['author']);
    $isbn     = mysqli_real_escape_string($conn, $_POST['isbn']);
    $edition  = mysqli_real_escape_string($conn, $_POST['edition']);
    $copies   = intval($_POST['copies']);

    // Cover upload
    if (!empty($_FILES['cover']['name'])) {
        $ext   = pathinfo($_FILES['cover']['name'], PATHINFO_EXTENSION);
        $cover = $id . "." . $ext;
        move_uploaded_file($_FILES['cover']['tmp_name'], "covers/" . $cover);
        $sql = "UPDATE catalogue SET title='$title', author='$author', isbn='$isbn', edition='$edition', copies='$copies', cover='$cover' WHERE id=$id";
    } else {
        $sql = "UPDATE catalogue SET title='$title', author='$author', isbn='$isbn', edition='$edition', copies='$copies' WHERE id=$id";
    }

    if (mysqli_query($conn, $sql)) {
        $successMsg = "Book updated successfully!";
    } else {
        $errorMsg = "Error: " . mysqli_error($conn);
    }
}

// ✅ Add new book
if (isset($_POST['add_catalogue'])) {
    $title    = mysqli_real_escape_string($conn, $_POST['title']);
    $author   = mysqli_real_escape_string($conn, $_POST['author']);
    $isbn     = mysqli_real_escape_string($conn, $_POST['isbn']);
    $edition  = mysqli_real_escape_string($conn, $_POST['edition']);
    $copies   = intval($_POST['copies']);
    $cover    = "";

    if (!empty($_FILES['cover']['name'])) {
        $ext   = pathinfo($_FILES['cover']['name'], PATHINFO_EXTENSION);
        $cover = uniqid() . "." . $ext;
        move_uploaded_file($_FILES['cover']['tmp_name'], "covers/" . $cover);
    }

    $sql = "INSERT INTO catalogue (title, author, isbn, edition, copies, cover)
            VALUES ('$title', '$author', '$isbn', '$edition', '$copies', '$cover')";
    if (mysqli_query($conn, $sql)) {
        $successMsg = "New book added successfully!";
    } else {
        $errorMsg = "Error: " . mysqli_error($conn);
    }
}

// ✅ Fetch all catalogue
$books = mysqli_query($conn, "SELECT * FROM catalogue ORDER BY id ASC");
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title></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://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://kit.fontawesome.com/a076d05399.js' 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="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.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=Signika+Negative:wght@300..700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="res/bootstrap@5.2.0.min.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=Source+Sans+Pro&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 href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js" integrity="sha384-IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i+tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.min.js" integrity="sha384-cVKIPhGWiC2Al4u+LWgxfKTRIcfu0JTxR+EQDz/bgldoEyl4H0zUF0QKbrJ0EcQF" crossorigin="anonymous"></script>
</head>


<style>
body { font-family: 'Roboto', sans-serif; background: #f5f7fa; }
.card { border-radius: 20px; box-shadow: 0 8px 25px rgba(0,0,0,0.1); padding: 30px; margin-top: 30px; }
h2 { color: var(--primary); margin-bottom: 20px; font-weight: 700; }
.table img { width: 50px; border-radius: 5px; }
.btn { border-radius: 8px; padding: 8px 16px; font-weight: 500; }
.btn-report { 
    background: linear-gradient(135deg, #6c5ce7, #a29bfe);
    border: none;
    color: white;
    transition: all 0.3s ease;
}
.btn-report:hover {
    background: linear-gradient(135deg, #5d4fd9, #8d7ffc);
    transform: translateY(-2px);
    box-shadow: 0 4px 15px rgba(108, 92, 231, 0.3);
    color: white;
}
.search-container {
    display: flex;
    gap: 10px;
}
.action-buttons {
    display: flex;
    gap: 10px;
}
</style>
</head>
<body>
    <?php include "../include/nav.php";?>
    <div class="content">
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-12">
            <div class="card">
                <h2 class="text-center">Library Catalogue Management</h2>

                <?php if(isset($successMsg)) echo "<div class='alert alert-success'>$successMsg</div>"; ?>
                <?php if(isset($errorMsg)) echo "<div class='alert alert-danger'>$errorMsg</div>"; ?>

                <div class="d-flex justify-content-between mb-3 flex-wrap">
                    <div class="search-container">
                        <input type="text" id="searchInput" class="form-control" placeholder="Search books..." style="width: 300px;">
                    </div>
                     <?php
                                if($role=="Librarian"){?>
                    <div class="action-buttons">
                        <a href="owing.php" class="btn btn-report">
                            <i class="fas fa-chart-bar me-2"></i>View Reports
                        </a>
                        <button class="btn btn-success" data-bs-toggle="modal" data-bs-target="#addModal">
                            <i class="fas fa-plus me-2"></i>Add Book
                        </button>
                    </div>
                </div>
<?php
}
?>
                <table class="table table-bordered table-hover" id="catalogueTable">
                    <thead class="table-dark">
                        <tr>
                            <th>Book ID</th>
                            <th>Cover</th>
                            <th>Title</th>
                            <th>Author</th>
                            <th>ISBN</th>
                            <th>Edition</th>
                            <th>Copies</th>
                             <?php
                                if($role=="Librarian"){?>
                            <th>Action</th>
                            <?php
                                }
                                ?>
                        </tr>
                    </thead>
                    <tbody>
                        <?php while($row = mysqli_fetch_assoc($books)) { ?>
                        <tr>
                                <td><?php echo $row['id']; ?></td>

                            <td><img src="covers/<?php echo $row['cover']; ?>" onerror="this.src='covers/default.png'"></td>
                            <td><?php echo $row['title']; ?></td>
                            <td><?php echo $row['author']; ?></td>
                            <td><?php echo $row['isbn']; ?></td>
                            <td><?php echo $row['edition']; ?></td>
                            <td><?php echo $row['copies']; ?></td>
                              <?php
                                if($role=="Librarian"){?>
                            <td>
                              
                                <button class=" btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#editModal<?php echo $row['id']; ?>">
                                    <i class="fas fa-edit me-1"></i>Edit
                                </button>
                                <a href="?delete=<?php echo $row['id']; ?>" class="btn btn-sm btn-danger" onclick="return confirm('Delete this book?');">
                                    <i class="fas fa-trash me-1"></i>Delete
                                </a>
                            </td>
                            <?php
                                }
                                ?>
                        </tr>

                        <!-- Edit Modal -->
                        <div class="modal fade" id="editModal<?php echo $row['id']; ?>" tabindex="-1">
                          <div class="modal-dialog">
                            <div class="modal-content">
                              <form method="post" enctype="multipart/form-data">
                                <div class="modal-header">
                                  <h5 class="modal-title">Edit Book</h5>
                                  <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                                </div>
                                <div class="modal-body">
                                  <input type="hidden" name="id" value="<?php echo $row['id']; ?>">
                                  <div class="mb-2">
                                    <label>Title</label>
                                    <input type="text" name="title" value="<?php echo $row['title']; ?>" class="form-control" required>
                                  </div>
                                  <div class="mb-2">
                                    <label>Author</label>
                                    <input type="text" name="author" value="<?php echo $row['author']; ?>" class="form-control" required>
                                  </div>
                                  <div class="mb-2">
                                    <label>ISBN</label>
                                    <input type="text" name="isbn" value="<?php echo $row['isbn']; ?>" class="form-control">
                                  </div>
                                  <div class="mb-2">
                                    <label>Edition</label>
                                    <input type="text" name="edition" value="<?php echo $row['edition']; ?>" class="form-control">
                                  </div>
                                  <div class="mb-2">
                                    <label>Copies</label>
                                    <input type="number" name="copies" value="<?php echo $row['copies']; ?>" class="form-control">
                                  </div>
                                  <div class="mb-2">
                                    <label>Cover (optional)</label>
                                    <input type="file" name="cover" accept="image/*" class="form-control">
                                  </div>
                                </div>
                                <div class="modal-footer">
                                  <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                                  <button type="submit" name="update_catalogue" class="btn btn-success">Save Changes</button>
                                </div>
                              </form>
                            </div>
                          </div>
                        </div>
                        <?php } ?>
                    </tbody>
                </table>

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

<!-- Add Book Modal -->
<div class="modal fade" id="addModal" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content">
      <form method="post" enctype="multipart/form-data">
        <div class="modal-header">
          <h5 class="modal-title">Add New Book</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
        </div>
        <div class="modal-body">
          <div class="mb-2">
            <label>Title</label>
            <input type="text" name="title" class="form-control" required>
          </div>
          <div class="mb-2">
            <label>Author</label>
            <input type="text" name="author" class="form-control" required>
          </div>
          <div class="mb-2">
            <label>ISBN</label>
            <input type="text" name="isbn" class="form-control">
          </div>
          <div class="mb-2">
            <label>Edition</label>
            <input type="text" name="edition" class="form-control">
          </div>
          <div class="mb-2">
            <label>Copies</label>
            <input type="number" name="copies" class="form-control">
          </div>
          <div class="mb-2">
            <label>Cover (optional)</label>
            <input type="file" name="cover" accept="image/*" class="form-control">
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
          <button type="submit" name="add_catalogue" class="btn btn-success">Add Book</button>
        </div>
      </form>
    </div>
  </div>
</div>

<script>
// ✅ Live Search Filter
document.getElementById("searchInput").addEventListener("keyup", function() {
    var value = this.value.toLowerCase();
    var rows = document.querySelectorAll("#catalogueTable tbody tr");
    rows.forEach(function(row) {
        row.style.display = row.innerText.toLowerCase().includes(value) ? "" : "none";
    });
});
</script>
</body>
</html>
<?php
}else {
  header("location:../index.php");
}
?>