<?php
session_start();

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

require 'config.php';

$userId = $_SESSION['user_id'];

// Messages for borrow/return/profile update
$message = '';
if (!empty($_GET['borrowed'])) {
    $message = '<div class="alert alert-success">Book borrowed successfully.</div>';
}
if (!empty($_GET['returned'])) {
    $message = '<div class="alert alert-success">Book returned successfully.</div>';
}
if (!empty($_GET['profile_updated'])) {
    $message = '<div class="alert alert-success">Profile updated successfully.</div>';
}
if (!empty($_GET['profile_error'])) {
    $message = '<div class="alert alert-danger">' . htmlspecialchars($_GET['profile_error']) . '</div>';
}

// User's borrowed books with fine calculation
$stmtBorrowed = $pdo->prepare("
    SELECT br.id as borrow_id, b.title, b.author, br.borrow_date, br.due_date,
        CASE 
            WHEN br.return_date IS NULL AND br.due_date < CURDATE()
            THEN DATEDIFF(CURDATE(), br.due_date) * 1 ELSE 0
        END AS fine
    FROM borrow_records br
    JOIN books b ON br.book_id = b.id
    WHERE br.user_id = ? AND br.return_date IS NULL
    ORDER BY br.due_date ASC
");
$stmtBorrowed->execute([$userId]);
$borrowedBooks = $stmtBorrowed->fetchAll();

// Search feature for available books
$search = trim($_GET['search'] ?? '');
$searchParam = "%" . $search . "%";
$searchActive = $search !== '';

if ($searchActive) {
    $stmtBooksTotal = $pdo->prepare("SELECT COUNT(*) FROM books WHERE available_copies > 0 AND (title LIKE ? COLLATE utf8mb4_general_ci OR author LIKE ? COLLATE utf8mb4_general_ci)");
    $stmtBooksTotal->execute([$searchParam, $searchParam]);
    $totalBooks = $stmtBooksTotal->fetchColumn();

    $perPage = 12;
    $page = max(1, intval($_GET['page'] ?? 1));
    $offset = ($page - 1) * $perPage;

    $stmtBooks = $pdo->prepare("
        SELECT * FROM books 
        WHERE available_copies > 0 
          AND (title LIKE ? COLLATE utf8mb4_general_ci OR author LIKE ? COLLATE utf8mb4_general_ci) 
        ORDER BY title 
        LIMIT ? OFFSET ?
    ");
    $stmtBooks->bindValue(1, $searchParam, PDO::PARAM_STR);
    $stmtBooks->bindValue(2, $searchParam, PDO::PARAM_STR);
    $stmtBooks->bindValue(3, $perPage, PDO::PARAM_INT);
    $stmtBooks->bindValue(4, $offset, PDO::PARAM_INT);
    $stmtBooks->execute();
} else {
    $perPage = 12;
    $page = max(1, intval($_GET['page'] ?? 1));
    $offset = ($page - 1) * $perPage;

    $stmtBooksTotal = $pdo->query("SELECT COUNT(*) FROM books WHERE available_copies > 0");
    $totalBooks = $stmtBooksTotal->fetchColumn();

    $stmtBooks = $pdo->prepare("
        SELECT * FROM books 
        WHERE available_copies > 0 
        ORDER BY title 
        LIMIT ? OFFSET ?
    ");
    $stmtBooks->bindValue(1, $perPage, PDO::PARAM_INT);
    $stmtBooks->bindValue(2, $offset, PDO::PARAM_INT);
    $stmtBooks->execute();
}
$availableBooks = $stmtBooks->fetchAll();

$totalPages = ceil($totalBooks / $perPage);

require 'header.php';
?>

<link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@400;700&family=Open+Sans&display=swap" rel="stylesheet">

<style>
  /* Your styles here */
  body { font-family: 'Open Sans', sans-serif; background: #f0f2f5; color: #333; }
  .welcome-section { background: #6c63ff; color: white; padding: 2rem 1rem; border-radius: .5rem; text-align: center; margin-bottom: 2rem; box-shadow: 0 0 15px rgba(108, 99, 255, 0.3); }
  .welcome-section img.avatar { width: 100px; height: 100px; border-radius: 50%; object-fit: cover; border: 3px solid white; margin-bottom: 1rem; }
  .section-title { font-family: 'Montserrat', sans-serif; font-weight: 700; margin-bottom: 1.2rem; color: #4a4a4a; border-bottom: 2px solid #6c63ff; display: inline-block; padding-bottom: 0.25rem; }
  .card-book { border-radius: 12px; box-shadow: 0 4px 15px rgba(0,0,0,0.1); overflow: hidden; transition: transform 0.2s ease, box-shadow 0.2s ease; cursor: pointer; background: white; display: flex; flex-direction: column; justify-content: space-between; }
  .card-book:hover { transform: translateY(-6px); box-shadow: 0 10px 25px rgba(0,0,0,0.15); }
  .card-body-book { padding: 1rem; flex: 1; }
  .card-body-book h5 { font-weight: 700; font-size: 1.1rem; margin-bottom: 0.25rem; }
  .card-body-book p.author { margin-bottom: 0.5rem; font-style: italic; color: #666; font-size: 0.9rem; }
  .fine-badge { background: #e74c3c; color: white; font-weight: 700; padding: 0.2rem 0.5rem; border-radius: 5px; font-size: 0.8rem; }
  .btn-borrow, .btn-return { width: 100%; font-weight: 700; }
  table tr td { vertical-align: middle; }
  .search-bar { max-width: 500px; margin-bottom: 1rem; }
  .pagination { justify-content: center; }
</style>

<div class="container py-4">

  <div class="welcome-section shadow-sm">
    <img src="https://i.pravatar.cc/100?u=<?= urlencode($_SESSION['username']) ?>" alt="User Avatar" class="avatar mx-auto d-block" />
    <h1>Hello, <?= htmlspecialchars($_SESSION['username']) ?>!</h1>
    <p>Welcome back to the Library LMS member dashboard.</p>
    <button type="button" class="btn btn-light btn-sm mt-2" data-bs-toggle="modal" data-bs-target="#editProfileModal">
      Edit Profile
    </button>
  </div>

  <?= $message ?>

  <section class="mb-5">
    <h2 class="section-title">Your Borrowed Books</h2>

    <?php if (!$borrowedBooks): ?>
        <div class="alert alert-info">You currently have no borrowed books.</div>
    <?php else: ?>
        <div class="row g-4">
          <?php foreach ($borrowedBooks as $book): ?>
            <div class="col-sm-6 col-md-4 col-lg-3">
              <div class="card-book">
                <div class="card-body-book">
                  <h5><?= htmlspecialchars($book['title']) ?></h5>
                  <p class="author">by <?= htmlspecialchars($book['author']) ?></p>
                  <p><strong>Borrowed:</strong> <?= $book['borrow_date'] ?></p>
                  <p><strong>Due:</strong> <?= $book['due_date'] ?></p>
                  <?php if ($book['fine'] > 0): ?>
                    <span class="fine-badge" title="Overdue fine">Overdue Fine: $<?= number_format($book['fine'], 2) ?></span>
                  <?php endif; ?>
                  <a href="return.php?id=<?= $book['borrow_id'] ?>" class="btn btn-danger btn-return mt-3" onclick="return confirm('Return this book?');" title="Return Book">Return Book</a>
                </div>
              </div>
            </div>
          <?php endforeach; ?>
        </div>
    <?php endif; ?>
  </section>

  <section>
    <h2 class="section-title">Available Books</h2>

    <form method="get" class="search-bar d-flex mb-3" role="search" autocomplete="off">
      <input type="search" name="search" class="form-control me-2" placeholder="Search books by title or author..." aria-label="Search books" value="<?= htmlspecialchars($search) ?>">
      <button class="btn btn-outline-primary" type="submit">Search</button>
      <?php if ($searchActive): ?>
        <a href="member_dashboard.php" class="btn btn-outline-danger ms-2">Clear Search</a>
      <?php endif; ?>
    </form>

    <?php if (!$availableBooks): ?>
      <div class="alert alert-warning">No books available at this time.</div>
    <?php else: ?>
      <div class="row g-4">
        <?php foreach ($availableBooks as $book): ?>
          <div class="col-sm-6 col-md-4 col-lg-3">
            <div class="card-book shadow-sm">
              <div class="card-body-book">
                <h5><?= htmlspecialchars($book['title']) ?></h5>
                <p class="author">by <?= htmlspecialchars($book['author']) ?></p>
                <p><strong>Available copies:</strong> <?= $book['available_copies'] ?></p>
                <a href="borrow.php?id=<?= $book['id'] ?>" class="btn btn-success btn-borrow" onclick="return confirm('Do you want to borrow this book?');" title="Borrow Book">Borrow</a>
              </div>
            </div>
          </div>
        <?php endforeach; ?>
      </div>

      <?php if ($totalPages > 1): ?>
      <nav aria-label="Page navigation">
        <ul class="pagination mt-4">
          <?php
          $queryParams = $_GET;
          for ($i = 1; $i <= $totalPages; $i++):
              $queryParams['page'] = $i;
              $url = htmlspecialchars($_SERVER['PHP_SELF'] . '?' . http_build_query($queryParams));
          ?>
            <li class="page-item <?= ($i === $page) ? 'active' : '' ?>">
              <a class="page-link" href="<?= $url ?>"><?= $i ?></a>
            </li>
          <?php endfor; ?>
        </ul>
      </nav>
      <?php endif; ?>
    <?php endif; ?>
  </section>
</div>

<!-- Edit Profile Modal -->
<div class="modal fade" id="editProfileModal" tabindex="-1" aria-labelledby="editProfileModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <form method="post" action="profile_update.php" class="modal-content needs-validation" novalidate>
      <div class="modal-header">
        <h5 class="modal-title" id="editProfileModalLabel">Edit Profile</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="usernameInput" class="form-label">Username</label>
          <input type="text" class="form-control" name="username" id="usernameInput" value="<?= htmlspecialchars($_SESSION['username']) ?>" required>
          <div class="invalid-feedback">Username is required.</div>
        </div>
        <div class="mb-3">
          <label for="passwordInput" class="form-label">New Password (optional)</label>
          <input type="password" class="form-control" name="password" id="passwordInput" placeholder="Enter new password">
        </div>
        <div class="mb-3">
          <label for="passwordConfirmInput" class="form-label">Confirm New Password</label>
          <input type="password" class="form-control" name="password_confirm" id="passwordConfirmInput" placeholder="Repeat new password">
        </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">Cancel</button>
      </div>
    </form>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

<script>
(() => {
  'use strict';

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

<?php require 'footer.php'; ?>   change the gui and inetrface and add more features related members that they have in lms