<?php
session_start();

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

require 'config.php';

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

// POST handlers (your add/delete user logic goes here)

// Fetch stats and recent data
$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();

$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();

$users = $pdo->query("SELECT id, username, role, created_at FROM users ORDER BY created_at DESC LIMIT 50")->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>Advanced 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" />
  <!-- Bootstrap Icons -->
  <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css" rel="stylesheet" />
  <!-- Simple DataTables CSS -->
  <link href="https://cdn.jsdelivr.net/npm/simple-datatables@7.1.2/dist/style.css" rel="stylesheet" />

  <style>
    /* ===== Reset & Globals ===== */
    body {
      background-color: #f3f6fd;
      font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
      color: #344767;
      margin: 0;
      overflow-y: scroll;
    }
    a {
      text-decoration: none;
    }

    /* ===== Sidebar Styles ===== */
    #sidebar {
      position: fixed;
      top: 0; bottom: 0; left: 0;
      width: 250px;
      background-color: #1b1f38;
      color: #fff;
      display: flex;
      flex-direction: column;
      padding: 1.5rem 1rem;
      box-shadow: 2px 0 12px rgba(27,31,56,0.6);
      z-index: 1030;
    }

    #sidebar .sidebar-brand {
      font-size: 1.8rem;
      font-weight: 700;
      padding-bottom: 1rem;
      border-bottom: 1px solid #3a3f67;
      margin-bottom: 1.5rem;
      letter-spacing: 2px;
      user-select: none;
    }

    #sidebar nav {
      flex-grow: 1;
    }

    #sidebar nav a {
      display: flex;
      align-items: center;
      padding: 0.7rem 1rem;
      color: #a6abc8;
      border-radius: 8px;
      margin-bottom: 0.8rem;
      font-weight: 600;
      font-size: 1rem;
      transition: background-color 0.25s ease, color 0.25s ease;
      user-select: none;
    }

    #sidebar nav a .bi {
      margin-right: 1rem;
      font-size: 1.3rem;
    }

    #sidebar nav a.active,
    #sidebar nav a:hover {
      background: #5865f2;
      color: #fff;
    }

    /* ===== Main Content Area ===== */
    #content {
      margin-left: 250px;
      padding: 2.5rem 3rem;
      transition: margin-left 0.3s ease;
      min-height: 100vh;
    }

    /* ===== Top Navbar ===== */
    .top-navbar {
      display: flex;
      justify-content: flex-end;
      align-items: center;
      padding-bottom: 2rem;
      gap: 1rem;
    }
    .top-navbar span {
      font-weight: 600;
      font-size: 1rem;
      color: #344767;
    }

    /* ===== Cards ===== */
    .stat-card {
      position: relative;
      background: linear-gradient(135deg, #6e8efb, #a777e3);
      color: #fff;
      border-radius: 20px;
      padding: 2rem 2.5rem;
      box-shadow: 0 12px 20px rgba(110,142,251,.4);
      transition: transform 0.3s ease, box-shadow 0.3s ease;
      cursor: default;
    }
    .stat-card:hover {
      transform: translateY(-10px);
      box-shadow: 0 18px 30px rgba(110,142,251,.6);
    }
    .stat-icon {
      position: absolute;
      top: 30px;
      right: 30px;
      font-size: 4rem;
      opacity: 0.12;
      user-select: none;
    }
    .stat-title {
      font-weight: 700;
      font-size: 0.85rem;
      text-transform: uppercase;
      letter-spacing: 0.1em;
      opacity: 0.8;
      margin-bottom: 0.8rem;
      user-select: none;
    }
    .stat-value {
      font-size: 2.8rem;
      font-weight: 800;
      user-select: text;
    }

    /* ===== Tables ===== */
    table {
      background: #fff;
      border-radius: 12px;
      box-shadow: 0 8px 16px rgba(0,0,0,0.05);
      overflow: hidden;
    }
    table thead {
      background-color: #5865f2 !important;
      color: white !important;
      font-weight: 600 !important;
    }
    table thead th, table tbody td {
      vertical-align: middle !important;
    }
    table tbody tr:hover {
      background-color: #ecefff;
      transition: background-color 0.25s ease;
    }

    /* Badges */
    .badge-role-admin {
      background-color: #ec4899 !important;
      font-weight: 600;
      padding: 0.3em 0.75em;
      border-radius: 12px;
    }
    .badge-role-member {
      background-color: #6b7280 !important;
      font-weight: 600;
      padding: 0.3em 0.75em;
      border-radius: 12px;
    }

    /* Buttons with shadows and scale */
    .btn {
      transition: transform 0.2s ease, box-shadow 0.3s ease;
    }
    .btn:hover {
      transform: translateY(-3px);
      filter: brightness(110%);
      box-shadow: 0 10px 25px rgb(99 102 241 / 0.45);
    }

    /* Modal */
    .modal-content {
      border-radius: 1rem;
    }
    .modal-header {
      border-bottom: 1px solid #dee2e6;
    }
    .modal-footer {
      border-top: 1px solid #dee2e6;
    }
  </style>
</head>
<body>

  <!-- Sidebar -->
  <nav id="sidebar">
    <div class="sidebar-brand">Library LMS</div>
    <nav>
      <a href="#" class="active"><i class="bi bi-speedometer2"></i> Dashboard</a>
      <a href="borrow_records.php"><i class="bi bi-journal-arrow-up"></i> Borrow Records</a>
      <a href="books.php"><i class="bi bi-book"></i> Books</a>
      <a href="#"><i class="bi bi-people"></i> Users</a>
    </nav>
  </nav>

  <!-- Content -->
  <main id="content" class="container-fluid">

    <div class="top-navbar mb-4">
      <span>Welcome, <?=htmlspecialchars($_SESSION['username'])?></span>
      <a href="?action=logout" class="btn btn-outline-primary btn-sm">Logout <i class="bi bi-box-arrow-right"></i></a>
    </div>

    <!-- Stats Cards -->
    <div class="row g-4 mb-5">
      <div class="col-md-3">
        <div class="stat-card">
          <i class="bi bi-people-fill stat-icon"></i>
          <p class="stat-title">Total Users</p>
          <h2 class="stat-value"><?= $totalUsers ?></h2>
        </div>
      </div>
      <div class="col-md-3">
        <div class="stat-card" style="background: linear-gradient(135deg,#4ade80,#16a34a);">
          <i class="bi bi-book-fill stat-icon"></i>
          <p class="stat-title">Total Books</p>
          <h2 class="stat-value"><?= $totalBooks ?></h2>
        </div>
      </div>
      <div class="col-md-3">
        <div class="stat-card" style="background: linear-gradient(135deg,#facc15,#ca8a04);">
          <i class="bi bi-journal-arrow-up stat-icon"></i>
          <p class="stat-title">Borrowed Books</p>
          <h2 class="stat-value"><?= $totalBorrowed ?></h2>
        </div>
      </div>
      <div class="col-md-3">
        <div class="stat-card" style="background: linear-gradient(135deg,#ef4444,#b91c1c);">
          <i class="bi bi-shield-lock-fill stat-icon"></i>
          <p class="stat-title">Admins</p>
          <h2 class="stat-value"><?= $totalAdmins ?></h2>
        </div>
      </div>
    </div>

    <!-- Recent Borrow Records -->
    <section class="mb-5">
      <h3 class="fw-semibold mb-4">Recent Borrow Records</h3>
      <div class="table-responsive shadow rounded">
        <table id="recentBorrowsTable" class="table table-striped table-hover align-middle">
          <thead class="table-primary">
            <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>
      </div>
      <a href="borrow_records.php" class="btn btn-primary mt-3">View All Borrow Records</a>
    </section>

    <!-- Users Section -->
    <section>
      <h3 class="fw-semibold mb-4">Users</h3>
      <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>
      <div class="table-responsive shadow rounded" style="max-height: 400px; overflow-y: auto;">
        <table id="usersTable" class="table table-hover align-middle">
          <thead class="table-secondary">
            <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 badge-role-admin">Admin</span>
                  <?php else: ?>
                    <span class="badge badge-role-member">Member</span>
                  <?php endif; ?>
                </td>
                <td><?= $u['created_at'] ?></td>
                <td>
                  <?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 type="submit" class="btn btn-sm btn-danger" title="Delete User"><i class="bi bi-trash-fill"></i></button>
                    </form>
                  <?php else: ?>
                    <span class="text-muted fst-italic">Protected</span>
                  <?php endif; ?>
                </td>
              </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    </section>

    <hr class="my-5"/>

    <!-- Books Section Summary -->
    <section>
      <h3 class="fw-semibold">Books Inventory</h3>
      <p class="fs-5">Total Books: <strong><?= $totalBooks ?></strong></p>
      <a href="books.php" class="btn btn-success btn-lg">
        <i class="bi bi-book-fill"></i> Manage Books
      </a>
    </section>

  </main>

  <!-- Add User Modal -->
  <div class="modal fade" id="addUserModal" tabindex="-1" aria-labelledby="addUserModalLabel" aria-hidden="true" style="--bs-modal-width: 400px;">
    <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 fw-semibold">Username *</label>
            <input type="text" name="username" id="add-username" class="form-control" placeholder="Enter username" required />
            <div class="invalid-feedback">Please enter a username.</div>
          </div>
          <div class="mb-3">
            <label for="add-password" class="form-label fw-semibold">Password *</label>
            <input type="password" name="password" id="add-password" class="form-control" placeholder="Enter password" required />
            <div class="invalid-feedback">Please enter a password.</div>
          </div>
          <div class="mb-3">
            <label for="add-role" class="form-label fw-semibold">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 fw-semibold">Add User</button>
          <button type="button" class="btn btn-light fw-semibold" data-bs-dismiss="modal">Close</button>
        </div>
      </form>
    </div>
  </div>

  <!-- Bootstrap JS and Simple DataTables -->
  <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 Simple-DataTables
      new simpleDatatables.DataTable("#usersTable");
      new simpleDatatables.DataTable("#recentBorrowsTable");

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

</body>
</html>  ihave this and i hav e user.php inetegrate both of them