<?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,
]);

// Handle POST requests for add/delete/return actions (edit removed)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        $action = $_POST['action'];

        if ($action === 'add_user') {
            // Add new user
            $username = trim($_POST['username'] ?? '');
            $password = $_POST['password'] ?? '';
            $role = $_POST['role'] ?? 'member';

            if ($username === '' || $password === '' || !in_array($role, ['admin', 'member'])) {
                $_SESSION['error'] = 'Invalid input for adding user.';
            } else {
                // Check if username already exists
                $stmt = $pdo->prepare("SELECT COUNT(*) FROM users WHERE username = ?");
                $stmt->execute([$username]);
                if ($stmt->fetchColumn() > 0) {
                    $_SESSION['error'] = 'Username already exists.';
                } else {
                    // Hash password
                    $password_hash = password_hash($password, PASSWORD_DEFAULT);

                    $stmt = $pdo->prepare("INSERT INTO users (username, password_hash, role, created_at) VALUES (?, ?, ?, NOW())");
                    $stmt->execute([$username, $password_hash, $role]);
                    $_SESSION['success'] = "User '$username' added successfully.";
                }
            }
        }
        // Removed edit_user handling

        elseif (isset($_POST['delete_user'])) {
            // Delete user (except main admin id=1)
            $user_id = (int)$_POST['delete_user'];
            if ($user_id === 1) {
                $_SESSION['error'] = 'Cannot delete main admin.';
            } else {
                $stmt = $pdo->prepare("DELETE FROM users WHERE id = ?");
                $stmt->execute([$user_id]);
                $_SESSION['success'] = "User deleted successfully.";
            }
        } elseif ($action === 'add_book') {
            // Add new book
            $title = trim($_POST['title'] ?? '');
            $author = trim($_POST['author'] ?? '');
            $category = trim($_POST['category'] ?? '');
            $total_copies = (int)($_POST['total_copies'] ?? 1);
            $total_copies = max(1, $total_copies);

            if ($title === '' || $author === '' || $total_copies < 1) {
                $_SESSION['error'] = 'Invalid input for adding book.';
            } else {
                $stmt = $pdo->prepare("INSERT INTO books (title, author, category, total_copies, available_copies, created_at) VALUES (?, ?, ?, ?, ?, NOW())");
                $stmt->execute([$title, $author, $category, $total_copies, $total_copies]);
                $_SESSION['success'] = "Book '$title' added successfully.";
            }
        }
        // Removed edit_book handling

        elseif (isset($_POST['delete_book'])) {
            // Delete book
            $book_id = (int)$_POST['delete_book'];
            if ($book_id > 0) {
                $stmt = $pdo->prepare("DELETE FROM books WHERE id = ?");
                $stmt->execute([$book_id]);
                $_SESSION['success'] = "Book deleted successfully.";
            } else {
                $_SESSION['error'] = 'Invalid book ID.';
            }
        } elseif (isset($_POST['return_book'])) {
            // Mark borrow record as returned
            $record_id = (int)($_POST['record_id'] ?? 0);
            if ($record_id > 0) {
                $stmt = $pdo->prepare("SELECT br.due_date, br.book_id, br.return_date FROM borrow_records br WHERE id = ?");
                $stmt->execute([$record_id]);
                $record = $stmt->fetch();

                if (!$record) {
                    $_SESSION['error'] = 'Borrow record not found.';
                } elseif (!empty($record['return_date'])) {
                    $_SESSION['error'] = 'Book already returned.';
                } else {
                    $due_date = new DateTime($record['due_date']);
                    $return_date = new DateTime();
                    $interval = $return_date->diff($due_date);
                    $fine = 0;

                    if ($return_date > $due_date) {
                        $days_late = $interval->days;
                        $fine = $days_late * 1; // 1$ per day late
                    }

                    $stmt = $pdo->prepare("UPDATE borrow_records SET return_date = NOW(), fine = ? WHERE id = ?");
                    $stmt->execute([$fine, $record_id]);

                    $stmt = $pdo->prepare("UPDATE books SET available_copies = available_copies + 1 WHERE id = ?");
                    $stmt->execute([$record['book_id']]);

                    $_SESSION['success'] = 'Book marked as returned.';
                }
            } else {
                $_SESSION['error'] = 'Invalid borrow record.';
            }
        }

        header('Location: '.$_SERVER['PHP_SELF']);
        exit;
    }
}

// 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 all borrow records
$borrow_records = $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
")->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();

// Logout
if (isset($_GET['action']) && $_GET['action'] === 'logout') {
    session_destroy();
    header('Location: login.php');
    exit;
}
?>
<!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">

    <?php if (isset($_SESSION['error'])): ?>
      <div class="alert alert-danger alert-dismissible fade show" role="alert">
          <?=htmlspecialchars($_SESSION['error'])?>
          <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
      </div>
      <?php unset($_SESSION['error']); ?>
    <?php endif; ?>

    <?php if (isset($_SESSION['success'])): ?>
      <div class="alert alert-success alert-dismissible fade show" role="alert">
          <?=htmlspecialchars($_SESSION['success'])?>
          <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
      </div>
      <?php unset($_SESSION['success']); ?>
    <?php endif; ?>

    <!-- 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">
                    <?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">
                    <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>

<!-- 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>

<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>
document.addEventListener('DOMContentLoaded', () => {

    // Initialize datatables
    new simpleDatatables.DataTable("#usersTable");
    new simpleDatatables.DataTable("#booksTable");
    new simpleDatatables.DataTable("#borrowRecordsTable");
    new simpleDatatables.DataTable("#recentBorrowsTable");

    // Bootstrap form validation
    (() => {
      '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');
        });
      });
    })();

});
</script>

</body>
</html>  in this admin has very less feature and i want more features that admin has in library management system like update books also