<?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 actions feedback
$messages = [];
if (!empty($_GET['borrowed'])) {
    $messages[] = ['type' => 'success', 'text' => 'Book borrowed successfully.'];
}
if (!empty($_GET['returned'])) {
    $messages[] = ['type' => 'success', 'text' => 'Book returned successfully.'];
}
if (!empty($_GET['profile_updated'])) {
    $messages[] = ['type' => 'success', 'text' => 'Profile updated successfully.'];
}
if (!empty($_GET['profile_error'])) {
    $messages[] = ['type' => 'danger', 'text' => htmlspecialchars($_GET['profile_error'])];
}

// Fetch user's borrowed books - CURRENT BORROWED
// Includes overdue fine and due soon indicator (due in 3 days or less)
$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,
        CASE 
            WHEN br.return_date IS NULL AND br.due_date BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 3 DAY)
            THEN 1 ELSE 0
        END AS due_soon
    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]);
$currentBorrowedBooks = $stmtBorrowed->fetchAll();

// Fetch borrow history (returned books) - UPDATED to select stored fine
$stmtHistory = $pdo->prepare("
    SELECT br.id AS borrow_id, b.title, b.author, br.borrow_date, br.due_date, br.return_date, br.fine
    FROM borrow_records br
    JOIN books b ON br.book_id = b.id
    WHERE br.user_id = ? AND br.return_date IS NOT NULL
    ORDER BY br.return_date DESC
    LIMIT 20
");
$stmtHistory->execute([$userId]);
$borrowHistory = $stmtHistory->fetchAll();

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

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

if ($searchActive) {
    // Count total matching books
    $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();

    // Fetch matching books with limit and offset
    $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 {
    $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';
?>

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

<style>
  body {
    font-family: 'Open Sans', sans-serif;
    background-color: #f8fafc;
    color: #212529;
  }
  /* Sidebar */
  .sidebar {
    height: 100vh;
    background: #5c5fef;
    color: white;
    padding: 2rem 1.5rem;
    min-width: 240px;
  }
  .sidebar h3 {
    font-family: 'Montserrat', sans-serif;
    font-weight: 700;
    margin-bottom: 2rem;
  }
  .sidebar a {
    display: block;
    color: white;
    padding: 0.75rem 1rem;
    margin-bottom: 0.5rem;
    border-radius: 8px;
    text-decoration: none;
    font-weight: 600;
    transition: background-color 0.3s ease;
  }
  .sidebar a.active, .sidebar a:hover {
    background-color: #4a4acf;
  }
  /* Main Layout */
  .main-content {
    padding: 2rem;
    flex: 1;
    overflow-x: hidden;
  }
  .header-user {
    display: flex;
    align-items: center;
    gap: 1rem;
    margin-bottom: 2rem;
  }
  .header-user img.avatar {
    width: 72px;
    height: 72px;
    border-radius: 50%;
    border: 3px solid #5c5fef;
    object-fit: cover;
  }
  .header-user h1 {
    font-family: 'Montserrat', sans-serif;
    font-weight: 700;
    font-size: 1.75rem;
    margin: 0;
    color: #3f3fff;
  }
  /* Messages */
  .messages {
    margin-bottom: 1.5rem;
  }
  /* Cards style */
  .card-book {
    background: #fff;
    border-radius: 14px;
    box-shadow: 0 4px 10px rgb(0 0 0 / 0.05);
    transition: transform 0.25s ease, box-shadow 0.25s ease;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    padding: 1rem 1.25rem;
    height: 100%;
  }
  .card-book:hover {
    transform: translateY(-5px);
    box-shadow: 0 10px 25px rgb(0 0 0 / 0.12);
  }
  .card-book h5 {
    font-family: 'Montserrat', sans-serif;
    font-weight: 600;
    color: #3f3fff;
    margin-bottom: 0.25rem;
  }
  .card-book .author {
    font-style: italic;
    color: #777;
    font-size: 0.9rem;
    margin-bottom: 0.75rem;
  }
  .card-book p {
    font-size: 0.9rem;
    margin-bottom: 0.4rem;
  }
  /* Buttons */
  .btn-borrow {
    background-color: #2dce89;
    color: white;
    font-weight: 700;
    border-radius: 6px;
    padding: 0.5rem;
    border: none;
    width: 100%;
    text-align: center;
    cursor: pointer;
  }
  .btn-borrow:hover {
    background-color: #1bb97b;
  }
  .btn-return {
    background-color: #f44336;
    color: white;
    font-weight: 700;
    border-radius: 6px;
    padding: 0.5rem;
    border: none;
    width: 100%;
    text-align: center;
    cursor: pointer;
  }
  .btn-return:hover {
    background-color: #d32f2f;
  }
  /* Fine badge */
  .fine-badge {
    background: #e55353;
    color: white;
    font-weight: 700;
    padding: 0.2rem 0.6rem;
    border-radius: 6px;
    font-size: 0.8rem;
    display: inline-block;
    margin-top: 0.75rem;
  }
  /* Due soon badge */
  .due-soon {
    background-color: #fbbc04;
    color: #664d03;
    font-weight: 700;
    padding: 0.2rem 0.5rem;
    border-radius: 6px;
    font-size: 0.8rem;
    margin-left: 0.5rem;
  }
  /* Section Titles */
  .section-title {
    font-family: 'Montserrat', sans-serif;
    font-weight: 700;
    font-size: 1.4rem;
    color: #344767;
    margin-bottom: 1rem;
    border-bottom: 3px solid #5c5fef;
    padding-bottom: 0.3rem;
    display: inline-block;
  }
  /* Flex & Grid Helpers */
  .flex-between {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .mb-4 {
    margin-bottom: 1.5rem !important;
  }
  /* Search bar */
  form.search-bar {
    max-width: 460px;
    margin-bottom: 1.5rem;
  }
  form.search-bar .form-control {
    border-right: 0;
    border-top-right-radius: 0;
    border-bottom-right-radius: 0;
  }
  form.search-bar button {
    border-top-left-radius: 0;
    border-bottom-left-radius: 0;
  }
  /* Tables */
  table.borrow-history {
    width: 100%;
    border-collapse: collapse;
    margin-top: 1rem;
  }
  table.borrow-history th, table.borrow-history td {
    padding: 0.7rem 1rem;
    border-bottom: 1px solid #eaeaea;
    text-align: left;
    font-size: 0.93rem;
  }
  table.borrow-history th {
    background-color: #f4f6fc;
    color: #5c5fef;
  }
  /* Pagination */
  nav.pagination-nav {
    margin-top: 1.5rem;
  }
  .pagination {
    justify-content: center;
  }
  /* Modal inputs */
  .form-label {
    font-weight: 600;
  }
  /* Responsive */
  @media (max-width: 768px) {
    .sidebar {
      display: none;
    }
    .main-content {
      padding: 1rem;
    }
  }
</style>

<div class="d-flex">
  <!-- Sidebar -->
  <nav class="sidebar d-none d-md-block">
    <h3>Member Panel</h3>
    <a href="#dashboard" class="active" data-bs-toggle="tab">Dashboard</a>
    <a href="#borrowedBooks" data-bs-toggle="tab">Borrowed Books</a>
    <a href="#searchBooks" data-bs-toggle="tab">Search & Borrow</a>
    <a href="#borrowHistory" data-bs-toggle="tab">Borrow History</a>
    <a href="#profileSection" data-bs-toggle="tab">Profile</a>
    <a href="logout.php">Logout</a>
  </nav>

  <!-- Main Content -->
  <div class="main-content">
    <div class="tab-content">

      <!-- Dashboard Tab -->
      <div class="tab-pane fade show active" id="dashboard" role="tabpanel">
        <div class="header-user">
          <img src="https://i.pravatar.cc/100?u=<?= urlencode($_SESSION['username']) ?>" alt="Avatar" class="avatar" />
          <div>
            <h1>Welcome back, <?= htmlspecialchars($_SESSION['username']) ?>!</h1>
            <p>Your Member Dashboard</p>
          </div>
        </div>

        <div class="messages">
          <?php foreach ($messages as $msg): ?>
              <div class="alert alert-<?= htmlspecialchars($msg['type']) ?>" role="alert">
                <?= $msg['text'] ?>
              </div>
          <?php endforeach; ?>
        </div>

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

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

      <!-- Borrowed Books Tab (Detailed List) -->
      <div class="tab-pane fade" id="borrowedBooks" role="tabpanel">
        <h2 class="section-title mb-4">Your Borrowed Books</h2>
        <?php if (!$currentBorrowedBooks): ?>
          <div class="alert alert-info">No current borrowed books found.</div>
        <?php else: ?>
        <table class="table table-striped">
          <thead>
            <tr>
              <th>Title & Author</th>
              <th>Borrow Date</th>
              <th>Due Date</th>
              <th>Fine</th>
              <th>Actions</th>
            </tr>
          </thead>
          <tbody>
            <?php foreach ($currentBorrowedBooks as $book): ?>
            <tr>
              <td>
                <strong><?= htmlspecialchars($book['title']) ?></strong><br/>
                <em><?= htmlspecialchars($book['author']) ?></em>
              </td>
              <td><?= date('M j, Y', strtotime($book['borrow_date'])) ?></td>
              <td>
                <?= date('M j, Y', strtotime($book['due_date'])) ?>
                <?php if ($book['due_soon']): ?>
                  <span class="badge bg-warning text-dark ms-1" title="Due Soon">&#9888;</span>
                <?php endif; ?>
              </td>
              <td>
                <?php if ($book['fine'] > 0): ?>
                  $<?= number_format($book['fine'], 2) ?>
                <?php else: ?>
                  -
                <?php endif; ?>
              </td>
              <td>
                <a href="return.php?id=<?= $book['borrow_id'] ?>" class="btn btn-sm btn-danger" onclick="return confirm('Return this book?');">Return</a>
              </td>
            </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
        <?php endif; ?>
      </div>

      <!-- Search & Borrow Tab -->
      <div class="tab-pane fade" id="searchBooks" role="tabpanel">
        <h2 class="section-title mb-3">Search & Borrow Books</h2>

        <form method="get" class="search-bar d-flex mb-4" 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-primary" type="submit">Search</button>
          <?php if($searchActive): ?>
            <a href="member_dashboard.php#searchBooks" class="btn btn-outline-secondary ms-2">Clear</a>
          <?php endif; ?>
        </form>

        <?php if (!$availableBooks): ?>
          <div class="alert alert-warning">No books available matching your search criteria.</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">
                  <div>
                    <h5><?= htmlspecialchars($book['title']) ?></h5>
                    <p class="author">by <?= htmlspecialchars($book['author']) ?></p>
                    <p><strong>Available Copies:</strong> <?= (int)$book['available_copies'] ?></p>
                  </div>
                  <a href="borrow.php?id=<?= $book['id'] ?>" class="btn-borrow" onclick="return confirm('Do you want to borrow this book?');" title="Borrow Book">Borrow</a>
                </div>
              </div>
            <?php endforeach; ?>
          </div>

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

      <!-- Borrow History Tab -->
      <div class="tab-pane fade" id="borrowHistory" role="tabpanel">
        <h2 class="section-title mb-4">Borrow History (Last 20 records)</h2>
        <?php if (!$borrowHistory): ?>
          <div class="alert alert-info">No borrow history found.</div>
        <?php else: ?>
        <table class="borrow-history">
          <thead>
            <tr>
              <th>Title & Author</th>
              <th>Borrow Date</th>
              <th>Due Date</th>
              <th>Return Date</th>
              <th>Fine</th>
            </tr>
          </thead>
          <tbody>
            <?php foreach ($borrowHistory as $record): ?>
              <tr>
                <td>
                  <strong><?= htmlspecialchars($record['title']) ?></strong><br/>
                  <em><?= htmlspecialchars($record['author']) ?></em>
                </td>
                <td><?= date('M j, Y', strtotime($record['borrow_date'])) ?></td>
                <td><?= date('M j, Y', strtotime($record['due_date'])) ?></td>
                <td><?= date('M j, Y', strtotime($record['return_date'])) ?></td>
                <td>
                  <?php if ($record['fine'] > 0): ?>
                    $<?= number_format($record['fine'], 2) ?>
                  <?php else: ?>
                    -
                  <?php endif; ?>
                </td>
              </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
        <?php endif; ?>
      </div>

      <!-- Profile Section -->
      <div class="tab-pane fade" id="profileSection" role="tabpanel">
        <h2 class="section-title mb-4">Your Profile</h2>
        <div class="card p-4 mb-4" style="max-width:480px;">
          <form method="post" action="profile_update.php" class="needs-validation" novalidate>
            <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 and must be valid.</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 class="invalid-feedback" id="password-mismatch-feedback">Passwords do not match.</div>
            </div>
            <button type="submit" class="btn btn-primary">Save Changes</button>
          </form>
        </div>
      </div>

    </div><!-- /.tab-content -->

  </div><!-- /.main-content -->
</div><!-- /.d-flex -->

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

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

  // Bootstrap tab activation from sidebar links
  const tabLinks = document.querySelectorAll('.sidebar a[data-bs-toggle="tab"]');
  const tabPanes = document.querySelectorAll('.tab-pane');

  tabLinks.forEach(link => {
    link.addEventListener('click', e => {
      e.preventDefault();
      // Remove active from all sidebar links & tab panes
      tabLinks.forEach(l => l.classList.remove('active'));
      tabPanes.forEach(p => p.classList.remove('show', 'active'));

      // Set active for clicked link
      link.classList.add('active');

      // Show appropriate tab pane
      const target = document.querySelector(link.getAttribute('href'));
      if (target) {
        target.classList.add('show', 'active');
        // Scroll to top when switching tab
        window.scrollTo({top: 0, behavior: 'smooth'});
      }
    });
  });

  // Bootstrap form validation for profile update
  const form = document.querySelector('form.needs-validation');
  const passwordInput = document.getElementById('passwordInput');
  const passwordConfirmInput = document.getElementById('passwordConfirmInput');
  const passwordMismatchFeedback = document.getElementById('password-mismatch-feedback');

  form.addEventListener('submit', event => {
    // Reset mismatch feedback visibility
    passwordMismatchFeedback.style.display = 'none';
    
    // Check validity of form native validation
    if (!form.checkValidity()) {
      event.preventDefault();
      event.stopPropagation();
      form.classList.add('was-validated');
      return;
    }

    // If password fields are filled, validate matching
    const pw = passwordInput.value.trim();
    const pwConfirm = passwordConfirmInput.value.trim();

    if (pw !== '' || pwConfirm !== '') {
      if (pw !== pwConfirm) {
        event.preventDefault();
        event.stopPropagation();
        passwordConfirmInput.classList.add('is-invalid');
        passwordMismatchFeedback.style.display = 'block';
        form.classList.add('was-validated');
      } else {
        passwordConfirmInput.classList.remove('is-invalid');
      }
    }
  });
})();
</script>

<?php require 'footer.php'; ?>  gui and interface is pretty basic make it advanced and give me a full updated code