<?php
session_start();

if (!isset($_SESSION['username']) || $_SESSION['role'] !== 'admin') {
    header('Location: login.php');
    exit;
}

require 'config.php';

// PDO connection
$pdo = new PDO("mysql:host=localhost;dbname=library_db;charset=utf8mb4", 'root', 'root', [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);

// Stats
$totalUsers = $pdo->query("SELECT COUNT(*) FROM users")->fetchColumn();
$totalBooks = $pdo->query("SELECT COUNT(*) FROM books")->fetchColumn();
$totalBorrowed = $pdo->query("SELECT COUNT(*) FROM borrow_records WHERE return_date IS NULL")->fetchColumn();
$totalAdmins = $pdo->query("SELECT COUNT(*) FROM users WHERE role='admin'")->fetchColumn();

// Recent borrow records (limit 5)
$recentBorrows = $pdo->query("
    SELECT br.id, u.username, b.title, br.borrow_date, br.due_date, br.return_date, br.fine
    FROM borrow_records br
    JOIN users u ON br.user_id = u.id
    JOIN books b ON br.book_id = b.id
    ORDER BY br.borrow_date DESC LIMIT 5
")->fetchAll();

// Fetch users and books
$users = $pdo->query("SELECT id, username, role, created_at FROM users ORDER BY created_at DESC")->fetchAll();
$books = $pdo->query("SELECT * FROM books ORDER BY created_at DESC")->fetchAll();

// Handle logout
if (isset($_GET['action']) && $_GET['action'] === 'logout') {
    session_destroy();
    header('Location: login.php');
    exit;
}

// You can include your POST handling add/edit/delete code here if needed...

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>Admin Dashboard - Library LMS</title>
    <meta name="viewport" content="width=device-width, initial-scale=1" />

    <!-- Bootstrap 5 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet" />

    <!-- Simple DataTables CSS -->
    <link href="https://cdn.jsdelivr.net/npm/simple-datatables@7.1.2/dist/style.css" rel="stylesheet" />

    <!-- Bootstrap Icons -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css" rel="stylesheet" />

    <style>
        body { background: #f9fafb; }
        .card-icon {
            font-size: 2.4rem;
            opacity: 0.3;
        }
        .card:hover {
            box-shadow: 0 10px 20px rgb(0 0 0 / 0.12);
            transition: all 0.3s ease;
        }
        .action-btns button {
            margin-right: 5px;
        }
    </style>
</head>
<body>

<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
    <div class="container">
        <a class="navbar-brand" href="#">Library LMS Admin</a>
        <div class="d-flex align-items-center ms-auto">
            <span class="text-white me-3">Welcome, <?=htmlspecialchars($_SESSION['username'])?></span>
            <a href="?action=logout" class="btn btn-outline-light btn-sm">Logout <i class="bi bi-box-arrow-right"></i></a>
        </div>
    </div>
</nav>

<div class="container my-4">

    <!-- Stats Cards -->
    <div class="row g-4 mb-5">
        <div class="col-md-3">
            <div class="card shadow-sm p-3">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <h6 class="text-uppercase text-muted">Total Users</h6>
                        <h3><?= $totalUsers ?></h3>
                    </div>
                    <i class="bi bi-people-fill card-icon"></i>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card shadow-sm p-3">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <h6 class="text-uppercase text-muted">Total Books</h6>
                        <h3><?= $totalBooks ?></h3>
                    </div>
                    <i class="bi bi-book-fill card-icon"></i>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card shadow-sm p-3">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <h6 class="text-uppercase text-muted">Borrowed Books</h6>
                        <h3><?= $totalBorrowed ?></h3>
                    </div>
                    <i class="bi bi-journal-arrow-up card-icon"></i>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card shadow-sm p-3">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <h6 class="text-uppercase text-muted">Admins</h6>
                        <h3><?= $totalAdmins ?></h3>
                    </div>
                    <i class="bi bi-shield-lock-fill card-icon"></i>
                </div>
            </div>
        </div>
    </div>

    <!-- Recent Borrow Records -->
    <h4 class="mb-3">Recent Borrow Records</h4>
    <table class="table table-striped" id="recentBorrowsTable">
        <thead>
            <tr>
                <th>ID</th>
                <th>User</th>
                <th>Book</th>
                <th>Borrow Date</th>
                <th>Due Date</th>
                <th>Return Date</th>
                <th>Fine</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach($recentBorrows as $r): ?>
            <tr>
                <td><?= $r['id'] ?></td>
                <td><?= htmlspecialchars($r['username']) ?></td>
                <td><?= htmlspecialchars($r['title']) ?></td>
                <td><?= $r['borrow_date'] ?></td>
                <td><?= $r['due_date'] ?></td>
                <td><?= $r['return_date'] ?? '-' ?></td>
                <td><?= $r['fine'] ? '$'.number_format($r['fine'], 2) : '-' ?></td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>

    <hr>

    <!-- Users Management -->
    <h4 class="mb-3">Users</h4>
    <button class="btn btn-primary mb-3" data-bs-toggle="modal" data-bs-target="#addUserModal">
        <i class="bi bi-person-plus-fill"></i> Add User
    </button>
    <table class="table table-hover" id="usersTable">
        <thead>
            <tr>
                <th>ID</th>
                <th>Username</th>
                <th>Role</th>
                <th>Created At</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($users as $u): ?>
            <tr>
                <td><?= $u['id'] ?></td>
                <td><?= htmlspecialchars($u['username']) ?></td>
                <td>
                    <?php if ($u['role']=='admin'): ?>
                        <span class="badge bg-danger">Admin</span>
                    <?php else: ?>
                        <span class="badge bg-secondary">Member</span>
                    <?php endif ?>
                </td>
                <td><?= $u['created_at'] ?></td>
                <td class="action-btns">
                    <button class="btn btn-sm btn-warning edit-user-btn"
                        data-id="<?= $u['id'] ?>"
                        data-username="<?= htmlspecialchars($u['username'], ENT_QUOTES) ?>"
                        data-role="<?= $u['role'] ?>"
                        <?= $u['id']==1 ? 'disabled title="Cannot edit main admin"' : '' ?>
                    >
                        <i class="bi bi-pencil-square"></i> Edit
                    </button>
                    <?php if($u['id']!=1): ?>
                    <form method="post" style="display:inline-block" onsubmit="return confirm('Delete user <?=htmlspecialchars(addslashes($u['username']))?>?');">
                        <input type="hidden" name="delete_user" value="<?= $u['id'] ?>">
                        <button class="btn btn-sm btn-danger"><i class="bi bi-trash-fill"></i></button>
                    </form>
                    <?php else: ?>
                        <span class="text-muted">Admin</span>
                    <?php endif ?>
                </td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>

    <hr>

    <!-- Books Management -->
    <h4 class="mb-3">Books Inventory</h4>
    <button class="btn btn-success mb-3" data-bs-toggle="modal" data-bs-target="#addBookModal">
        <i class="bi bi-book-fill"></i> Add Book
    </button>
    <table class="table table-hover" id="booksTable">
        <thead>
            <tr>
                <th>ID</th>
                <th>Title</th>
                <th>Author</th>
                <th>Category</th>
                <th>Total Copies</th>
                <th>Available Copies</th>
                <th>Added On</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach($books as $b): ?>
            <tr>
                <td><?= $b['id'] ?></td>
                <td><?= htmlspecialchars($b['title']) ?></td>
                <td><?= htmlspecialchars($b['author']) ?></td>
                <td><?= htmlspecialchars($b['category']) ?></td>
                <td><?= $b['total_copies'] ?></td>
                <td><?= $b['available_copies'] ?></td>
                <td><?= $b['created_at'] ?></td>
                <td class="action-btns">
                    <button class="btn btn-warning btn-sm edit-book-btn"
                        data-id="<?= $b['id'] ?>"
                        data-title="<?= htmlspecialchars($b['title'], ENT_QUOTES) ?>"
                        data-author="<?= htmlspecialchars($b['author'], ENT_QUOTES) ?>"
                        data-category="<?= htmlspecialchars($b['category'], ENT_QUOTES) ?>"
                        data-total="<?= $b['total_copies'] ?>"
                    >
                        <i class="bi bi-pencil-square"></i> Edit
                    </button>
                    <form method="post" style="display:inline-block" onsubmit="return confirm('Delete book <?=htmlspecialchars(addslashes($b['title']))?>?');" >
                        <input type="hidden" name="delete_book" value="<?= $b['id'] ?>">
                        <button class="btn btn-sm btn-danger"><i class="bi bi-trash-fill"></i></button>
                    </form>
                </td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>

    <hr>

    <!-- Borrow Records -->
    <h4 class="mb-3">Borrow Records</h4>
    <table class="table table-hover" id="borrowRecordsTable">
        <thead>
            <tr>
                <th>ID</th>
                <th>Username</th>
                <th>Book Title</th>
                <th>Borrow Date</th>
                <th>Due Date</th>
                <th>Return Date</th>
                <th>Fine</th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach($borrow_records as $br): ?>
            <tr>
                <td><?= $br['id'] ?></td>
                <td><?= htmlspecialchars($br['username']) ?></td>
                <td><?= htmlspecialchars($br['title']) ?></td>
                <td><?= $br['borrow_date'] ?></td>
                <td><?= $br['due_date'] ?></td>
                <td><?= $br['return_date'] ?? '-' ?></td>
                <td><?= $br['fine'] ? '$'.number_format($br['fine'],2) : '-' ?></td>
                <td class="action-btns">
                    <?php if(empty($br['return_date'])): ?>
                    <form method="post" onsubmit="return confirm('Mark this book as returned?');" style="display:inline-block;">
                        <input type="hidden" name="record_id" value="<?= $br['id'] ?>">
                        <button name="return_book" class="btn btn-sm btn-primary"><i class="bi bi-arrow-return-left"></i> Return</button>
                    </form>
                    <?php else: ?>
                    <span class="badge bg-success">Returned</span>
                    <?php endif; ?>
                </td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>

</div>

<!-- Modals -->

<!-- Add User Modal -->
<div class="modal fade" id="addUserModal" tabindex="-1" aria-labelledby="addUserModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <form method="post" class="modal-content needs-validation" novalidate>
        <input type="hidden" name="action" value="add_user" />
      <div class="modal-header">
        <h5 class="modal-title" id="addUserModalLabel">Add New User</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
            <div class="mb-3">
                <label for="add-username" class="form-label">Username *</label>
                <input type="text" class="form-control" id="add-username" name="username" required />
                <div class="invalid-feedback">Please enter a username.</div>
            </div>
            <div class="mb-3">
                <label for="add-password" class="form-label">Password *</label>
                <input type="password" class="form-control" id="add-password" name="password" required />
                <div class="invalid-feedback">Please enter a password.</div>
            </div>
            <div class="mb-3">
                <label for="add-role" class="form-label">Role *</label>
                <select name="role" id="add-role" class="form-select" required>
                    <option value="member" selected>Member</option>
                    <option value="admin">Admin</option>
                </select>
                <div class="invalid-feedback">Please select a role.</div>
            </div>
      </div>
      <div class="modal-footer">
        <button type="submit" class="btn btn-primary">Add User</button>
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
      </div>
    </form>
  </div>
</div>

<!-- Edit User Modal -->
<div class="modal fade" id="editUserModal" tabindex="-1" aria-labelledby="editUserModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <form method="post" class="modal-content needs-validation" novalidate>
        <input type="hidden" name="action" value="edit_user" />
        <input type="hidden" name="user_id" id="edit-user-id" />
      <div class="modal-header">
        <h5 class="modal-title" id="editUserModalLabel">Edit User</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
            <div class="mb-3">
                <label for="edit-username" class="form-label">Username *</label>
                <input type="text" class="form-control" id="edit-username" name="username" required />
                <div class="invalid-feedback">Please enter a username.</div>
            </div>
            <div class="mb-3">
                <label for="edit-role" class="form-label">Role *</label>
                <select name="role" id="edit-role" class="form-select" required>
                    <option value="member">Member</option>
                    <option value="admin">Admin</option>
                </select>
                <div class="invalid-feedback">Please select a role.</div>
            </div>
      </div>
      <div class="modal-footer">
        <button type="submit" class="btn btn-primary">Save Changes</button>
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
      </div>
    </form>
  </div>
</div>

<!-- Add Book Modal -->
<div class="modal fade" id="addBookModal" tabindex="-1" aria-labelledby="addBookModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <form method="post" class="modal-content needs-validation" novalidate>
        <input type="hidden" name="action" value="add_book"/>
      <div class="modal-header">
        <h5 class="modal-title" id="addBookModalLabel">Add New Book</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
            <div class="mb-3">
                <label for="add-title" class="form-label">Title *</label>
                <input type="text" class="form-control" id="add-title" name="title" required />
                <div class="invalid-feedback">Please enter a title.</div>
            </div>
            <div class="mb-3">
                <label for="add-author" class="form-label">Author *</label>
                <input type="text" class="form-control" id="add-author" name="author" required />
                <div class="invalid-feedback">Please enter the author.</div>
            </div>
            <div class="mb-3">
                <label for="add-category" class="form-label">Category</label>
                <input type="text" class="form-control" id="add-category" name="category" />
            </div>
            <div class="mb-3">
                <label for="add-total_copies" class="form-label">Total Copies *</label>
                <input type="number" min="1" class="form-control" id="add-total_copies" name="total_copies" required value="1" />
                <div class="invalid-feedback">Please enter total copies (>=1).</div>
            </div>
      </div>
      <div class="modal-footer">
        <button type="submit" class="btn btn-success">Add Book</button>
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
      </div>
    </form>
  </div>
</div>

<!-- Edit Book Modal -->
<div class="modal fade" id="editBookModal" tabindex="-1" aria-labelledby="editBookModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <form method="post" class="modal-content needs-validation" novalidate>
        <input type="hidden" name="action" value="edit_book"/>
        <input type="hidden" name="book_id" id="edit-book-id" />
      <div class="modal-header">
        <h5 class="modal-title" id="editBookModalLabel">Edit Book</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
            <div class="mb-3">
                <label for="edit-title" class="form-label">Title *</label>
                <input type="text" class="form-control" id="edit-title" name="title" required />
                <div class="invalid-feedback">Please enter a title.</div>
            </div>
            <div class="mb-3">
                <label for="edit-author" class="form-label">Author *</label>
                <input type="text" class="form-control" id="edit-author" name="author" required />
                <div class="invalid-feedback">Please enter the author.</div>
            </div>
            <div class="mb-3">
                <label for="edit-category" class="form-label">Category</label>
                <input type="text" class="form-control" id="edit-category" name="category" />
            </div>
            <div class="mb-3">
                <label for="edit-total_copies" class="form-label">Total Copies *</label>
                <input type="number" min="1" class="form-control" id="edit-total_copies" name="total_copies" required />
                <div class="invalid-feedback">Please enter total copies (>=1).</div>
            </div>
      </div>
      <div class="modal-footer">
        <button type="submit" class="btn btn-primary">Save Changes</button>
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
      </div>
    </form>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/simple-datatables@7.1.2/dist/simple-datatables.js"></script>
<script>
    new simpleDatatables.DataTable("#usersTable");
    new simpleDatatables.DataTable("#booksTable");
    new simpleDatatables.DataTable("#borrowRecordsTable");
    new simpleDatatables.DataTable("#recentBorrowsTable");

    (() => {
      'use strict'
      const forms = document.querySelectorAll('.needs-validation');
      Array.from(forms).forEach(form => {
        form.addEventListener('submit', evt => {
          if (!form.checkValidity()) {
            evt.preventDefault();
            evt.stopPropagation();
          }
          form.classList.add('was-validated');
        });
      });
    })();

    document.querySelectorAll('.edit-user-btn').forEach(btn => {
        btn.addEventListener('click', () => {
            document.getElementById('edit-user-id').value = btn.dataset.id;
            document.getElementById('edit-username').value = btn.dataset.username;
            document.getElementById('edit-role').value = btn.dataset.role;
            new bootstrap.Modal(document.getElementById('editUserModal')).show();
        });
    });

    document.querySelectorAll('.edit-book-btn').forEach(btn => {
        btn.addEventListener('click', () => {
            document.getElementById('edit-book-id').value = btn.dataset.id;
            document.getElementById('edit-title').value = btn.dataset.title;
            document.getElementById('edit-author').value = btn.dataset.author;
            document.getElementById('edit-category').value = btn.dataset.category;
            document.getElementById('edit-total_copies').value = btn.dataset.total;
            new bootstrap.Modal(document.getElementById('editBookModal')).show();
        });
    });
</script>
</body>
</html>  error regarding borrow records solve it and give afull updated code